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 d713d0f493..e4229729de 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' @@ -349,7 +352,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 @@ -507,23 +510,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 @@ -734,101 +721,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 @@ -884,8 +776,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..663bd30e6a --- /dev/null +++ b/.github/workflows/unit-tests.yml @@ -0,0 +1,202 @@ +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 + # A pull request's cache is visible only to that pull request, and each copy is hundreds of megabytes against the + # repository's 10 GB cache limit. Only main saves, so every pull request restores main's set. + - name: Store Robolectric's Android jars + if: always() && github.event_name != 'pull_request' && 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..021fed17b3 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05. - mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). - [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122). +- Anti-cheat support under FEX is the work of [StonkGuy](https://github.com/StonkGuy): the x86-64 ptrace, seccomp and `/proc` emulation from his [FEX fork](https://github.com/StonkGuy/FEX) (`eac-2611` branch, MIT) is carried as build patch 0021 with his authorship, patches 0022 to 0029 build on it, and his `eac-tests` regression suite verifies them. - x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT). - x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. - DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence. @@ -113,7 +114,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 70336a0472..513fdef6aa 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'].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..4211f6bbc5 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -33,10 +33,15 @@ + + + + @@ -274,6 +279,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 a33cf37e49..01ae9fd830 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 2bfcb76202..4c592ded09 100644 --- a/app/src/main/cpp/fakeinput_steam.cpp +++ b/app/src/main/cpp/fakeinput_steam.cpp @@ -329,16 +329,28 @@ static constexpr int kWatchedFds = 1 << 16; static constexpr int kWatchedBits = sizeof(unsigned long) * 8; static std::atomic watched_fds[kWatchedFds / kWatchedBits]; static std::atomic watched_beyond{false}; +static std::atomic watched_count{0}; static void watch_fd(int fd) { if (fd < 0) return; - if (fd >= kWatchedFds) watched_beyond.store(true, std::memory_order_release); - else watched_fds[fd / kWatchedBits].fetch_or(1UL << (fd % kWatchedBits), std::memory_order_release); + if (fd >= kWatchedFds) { + watched_beyond.store(true, std::memory_order_release); + return; + } + const unsigned long bit = 1UL << (fd % kWatchedBits); + if (!(watched_fds[fd / kWatchedBits].fetch_or(bit, std::memory_order_acq_rel) & bit)) + watched_count.fetch_add(1, std::memory_order_acq_rel); } static void unwatch_fd(int fd) { - if (fd >= 0 && fd < kWatchedFds) - watched_fds[fd / kWatchedBits].fetch_and(~(1UL << (fd % kWatchedBits)), std::memory_order_release); + if (fd < 0 || fd >= kWatchedFds) return; + const unsigned long bit = 1UL << (fd % kWatchedBits); + if (watched_fds[fd / kWatchedBits].fetch_and(~bit, std::memory_order_acq_rel) & bit) + watched_count.fetch_sub(1, std::memory_order_acq_rel); +} + +static bool any_watched() { + return watched_count.load(std::memory_order_acquire) > 0 || watched_beyond.load(std::memory_order_acquire); } static bool watched(int fd) { @@ -4130,13 +4142,20 @@ 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) __chk_fail(); + 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); } @@ -4262,7 +4281,7 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout, const auto my_poll = next_symbol(Next::poll); const auto my_ppoll = next_symbol(Next::ppoll); - nfds_t first = 0; + nfds_t first = any_watched() ? 0 : nfds; while (first < nfds && !watched(fds[first].fd)) first++; bool has_fake_fds = false; std::vector real_fds; @@ -4365,12 +4384,12 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) { EXPORT int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout, const sigset_t *sigmask) { const auto my_ppoll = next_symbol(Next::ppoll); - if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) { - errno = EINVAL; - return -1; - } - for (nfds_t i = 0; i < nfds; ++i) { + for (nfds_t i = 0; any_watched() && i < nfds; ++i) { if (!is_fake_input_fd(fds[i].fd)) continue; + if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) { + errno = EINVAL; + return -1; + } if (!sigmask) return poll_fake(fds, nfds, static_cast(timespec_to_ms(timeout)), nullptr); sigset_t all_signals, original_mask; @@ -4390,19 +4409,21 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds, } EXPORT int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fdslen) { - if (fdslen / sizeof(*fds) < nfds) __chk_fail(); + 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) __chk_fail(); + 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); + if (!any_watched()) + return my_select ? my_select(nfds, readfds, writefds, exceptfds, timeout) : -1; fd_set original_readfds; fd_set original_writefds; 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/SMAA.hlsl b/app/src/main/cpp/shaders/SMAA.hlsl new file mode 100644 index 0000000000..d955d52401 --- /dev/null +++ b/app/src/main/cpp/shaders/SMAA.hlsl @@ -0,0 +1,1361 @@ +/** + * Copyright (C) 2013 Jorge Jimenez (jorge@iryoku.com) + * Copyright (C) 2013 Jose I. Echevarria (joseignacioechevarria@gmail.com) + * Copyright (C) 2013 Belen Masia (bmasia@unizar.es) + * Copyright (C) 2013 Fernando Navarro (fernandn@microsoft.com) + * Copyright (C) 2013 Diego Gutierrez (diegog@unizar.es) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to + * do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. As clarification, there + * is no requirement that the copyright notice and permission be included in + * binary distributions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + + +/** + * _______ ___ ___ ___ ___ + * / || \/ | / \ / \ + * | (---- | \ / | / ^ \ / ^ \ + * \ \ | |\/| | / /_\ \ / /_\ \ + * ----) | | | | | / _____ \ / _____ \ + * |_______/ |__| |__| /__/ \__\ /__/ \__\ + * + * E N H A N C E D + * S U B P I X E L M O R P H O L O G I C A L A N T I A L I A S I N G + * + * http://www.iryoku.com/smaa/ + * + * Hi, welcome aboard! + * + * Here you'll find instructions to get the shader up and running as fast as + * possible. + * + * IMPORTANTE NOTICE: when updating, remember to update both this file and the + * precomputed textures! They may change from version to version. + * + * The shader has three passes, chained together as follows: + * + * |input|------------------· + * v | + * [ SMAA*EdgeDetection ] | + * v | + * |edgesTex| | + * v | + * [ SMAABlendingWeightCalculation ] | + * v | + * |blendTex| | + * v | + * [ SMAANeighborhoodBlending ] <------· + * v + * |output| + * + * Note that each [pass] has its own vertex and pixel shader. Remember to use + * oversized triangles instead of quads to avoid overshading along the + * diagonal. + * + * You've three edge detection methods to choose from: luma, color or depth. + * They represent different quality/performance and anti-aliasing/sharpness + * tradeoffs, so our recommendation is for you to choose the one that best + * suits your particular scenario: + * + * - Depth edge detection is usually the fastest but it may miss some edges. + * + * - Luma edge detection is usually more expensive than depth edge detection, + * but catches visible edges that depth edge detection can miss. + * + * - Color edge detection is usually the most expensive one but catches + * chroma-only edges. + * + * For quickstarters: just use luma edge detection. + * + * The general advice is to not rush the integration process and ensure each + * step is done correctly (don't try to integrate SMAA T2x with predicated edge + * detection from the start!). Ok then, let's go! + * + * 1. The first step is to create two RGBA temporal render targets for holding + * |edgesTex| and |blendTex|. + * + * In DX10 or DX11, you can use a RG render target for the edges texture. + * In the case of NVIDIA GPUs, using RG render targets seems to actually be + * slower. + * + * On the Xbox 360, you can use the same render target for resolving both + * |edgesTex| and |blendTex|, as they aren't needed simultaneously. + * + * 2. Both temporal render targets |edgesTex| and |blendTex| must be cleared + * each frame. Do not forget to clear the alpha channel! + * + * 3. The next step is loading the two supporting precalculated textures, + * 'areaTex' and 'searchTex'. You'll find them in the 'Textures' folder as + * C++ headers, and also as regular DDS files. They'll be needed for the + * 'SMAABlendingWeightCalculation' pass. + * + * If you use the C++ headers, be sure to load them in the format specified + * inside of them. + * + * You can also compress 'areaTex' and 'searchTex' using BC5 and BC4 + * respectively, if you have that option in your content processor pipeline. + * When compressing then, you get a non-perceptible quality decrease, and a + * marginal performance increase. + * + * 4. All samplers must be set to linear filtering and clamp. + * + * After you get the technique working, remember that 64-bit inputs have + * half-rate linear filtering on GCN. + * + * If SMAA is applied to 64-bit color buffers, switching to point filtering + * when accesing them will increase the performance. Search for + * 'SMAASamplePoint' to see which textures may benefit from point + * filtering, and where (which is basically the color input in the edge + * detection and resolve passes). + * + * 5. All texture reads and buffer writes must be non-sRGB, with the exception + * of the input read and the output write in + * 'SMAANeighborhoodBlending' (and only in this pass!). If sRGB reads in + * this last pass are not possible, the technique will work anyway, but + * will perform antialiasing in gamma space. + * + * IMPORTANT: for best results the input read for the color/luma edge + * detection should *NOT* be sRGB. + * + * 6. Before including SMAA.h you'll have to setup the render target metrics, + * the target and any optional configuration defines. Optionally you can + * use a preset. + * + * You have the following targets available: + * SMAA_HLSL_3 + * SMAA_HLSL_4 + * SMAA_HLSL_4_1 + * SMAA_GLSL_3 * + * SMAA_GLSL_4 * + * + * * (See SMAA_INCLUDE_VS and SMAA_INCLUDE_PS below). + * + * And four presets: + * SMAA_PRESET_LOW (%60 of the quality) + * SMAA_PRESET_MEDIUM (%80 of the quality) + * SMAA_PRESET_HIGH (%95 of the quality) + * SMAA_PRESET_ULTRA (%99 of the quality) + * + * For example: + * #define SMAA_RT_METRICS float4(1.0 / 1280.0, 1.0 / 720.0, 1280.0, 720.0) + * #define SMAA_HLSL_4 + * #define SMAA_PRESET_HIGH + * #include "SMAA.h" + * + * Note that SMAA_RT_METRICS doesn't need to be a macro, it can be a + * uniform variable. The code is designed to minimize the impact of not + * using a constant value, but it is still better to hardcode it. + * + * Depending on how you encoded 'areaTex' and 'searchTex', you may have to + * add (and customize) the following defines before including SMAA.h: + * #define SMAA_AREATEX_SELECT(sample) sample.rg + * #define SMAA_SEARCHTEX_SELECT(sample) sample.r + * + * If your engine is already using porting macros, you can define + * SMAA_CUSTOM_SL, and define the porting functions by yourself. + * + * 7. Then, you'll have to setup the passes as indicated in the scheme above. + * You can take a look into SMAA.fx, to see how we did it for our demo. + * Checkout the function wrappers, you may want to copy-paste them! + * + * 8. It's recommended to validate the produced |edgesTex| and |blendTex|. + * You can use a screenshot from your engine to compare the |edgesTex| + * and |blendTex| produced inside of the engine with the results obtained + * with the reference demo. + * + * 9. After you get the last pass to work, it's time to optimize. You'll have + * to initialize a stencil buffer in the first pass (discard is already in + * the code), then mask execution by using it the second pass. The last + * pass should be executed in all pixels. + * + * + * After this point you can choose to enable predicated thresholding, + * temporal supersampling and motion blur integration: + * + * a) If you want to use predicated thresholding, take a look into + * SMAA_PREDICATION; you'll need to pass an extra texture in the edge + * detection pass. + * + * b) If you want to enable temporal supersampling (SMAA T2x): + * + * 1. The first step is to render using subpixel jitters. I won't go into + * detail, but it's as simple as moving each vertex position in the + * vertex shader, you can check how we do it in our DX10 demo. + * + * 2. Then, you must setup the temporal resolve. You may want to take a look + * into SMAAResolve for resolving 2x modes. After you get it working, you'll + * probably see ghosting everywhere. But fear not, you can enable the + * CryENGINE temporal reprojection by setting the SMAA_REPROJECTION macro. + * Check out SMAA_DECODE_VELOCITY if your velocity buffer is encoded. + * + * 3. The next step is to apply SMAA to each subpixel jittered frame, just as + * done for 1x. + * + * 4. At this point you should already have something usable, but for best + * results the proper area textures must be set depending on current jitter. + * For this, the parameter 'subsampleIndices' of + * 'SMAABlendingWeightCalculationPS' must be set as follows, for our T2x + * mode: + * + * @SUBSAMPLE_INDICES + * + * | S# | Camera Jitter | subsampleIndices | + * +----+------------------+---------------------+ + * | 0 | ( 0.25, -0.25) | float4(1, 1, 1, 0) | + * | 1 | (-0.25, 0.25) | float4(2, 2, 2, 0) | + * + * These jitter positions assume a bottom-to-top y axis. S# stands for the + * sample number. + * + * More information about temporal supersampling here: + * http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf + * + * c) If you want to enable spatial multisampling (SMAA S2x): + * + * 1. The scene must be rendered using MSAA 2x. The MSAA 2x buffer must be + * created with: + * - DX10: see below (*) + * - DX10.1: D3D10_STANDARD_MULTISAMPLE_PATTERN or + * - DX11: D3D11_STANDARD_MULTISAMPLE_PATTERN + * + * This allows to ensure that the subsample order matches the table in + * @SUBSAMPLE_INDICES. + * + * (*) In the case of DX10, we refer the reader to: + * - SMAA::detectMSAAOrder and + * - SMAA::msaaReorder + * + * These functions allow to match the standard multisample patterns by + * detecting the subsample order for a specific GPU, and reordering + * them appropriately. + * + * 2. A shader must be run to output each subsample into a separate buffer + * (DX10 is required). You can use SMAASeparate for this purpose, or just do + * it in an existing pass (for example, in the tone mapping pass, which has + * the advantage of feeding tone mapped subsamples to SMAA, which will yield + * better results). + * + * 3. The full SMAA 1x pipeline must be run for each separated buffer, storing + * the results in the final buffer. The second run should alpha blend with + * the existing final buffer using a blending factor of 0.5. + * 'subsampleIndices' must be adjusted as in the SMAA T2x case (see point + * b). + * + * d) If you want to enable temporal supersampling on top of SMAA S2x + * (which actually is SMAA 4x): + * + * 1. SMAA 4x consists on temporally jittering SMAA S2x, so the first step is + * to calculate SMAA S2x for current frame. In this case, 'subsampleIndices' + * must be set as follows: + * + * | F# | S# | Camera Jitter | Net Jitter | subsampleIndices | + * +----+----+--------------------+-------------------+----------------------+ + * | 0 | 0 | ( 0.125, 0.125) | ( 0.375, -0.125) | float4(5, 3, 1, 3) | + * | 0 | 1 | ( 0.125, 0.125) | (-0.125, 0.375) | float4(4, 6, 2, 3) | + * +----+----+--------------------+-------------------+----------------------+ + * | 1 | 2 | (-0.125, -0.125) | ( 0.125, -0.375) | float4(3, 5, 1, 4) | + * | 1 | 3 | (-0.125, -0.125) | (-0.375, 0.125) | float4(6, 4, 2, 4) | + * + * These jitter positions assume a bottom-to-top y axis. F# stands for the + * frame number. S# stands for the sample number. + * + * 2. After calculating SMAA S2x for current frame (with the new subsample + * indices), previous frame must be reprojected as in SMAA T2x mode (see + * point b). + * + * e) If motion blur is used, you may want to do the edge detection pass + * together with motion blur. This has two advantages: + * + * 1. Pixels under heavy motion can be omitted from the edge detection process. + * For these pixels we can just store "no edge", as motion blur will take + * care of them. + * 2. The center pixel tap is reused. + * + * Note that in this case depth testing should be used instead of stenciling, + * as we have to write all the pixels in the motion blur pass. + * + * That's it! + */ + +//----------------------------------------------------------------------------- +// SMAA Presets + +/** + * Note that if you use one of these presets, the following configuration + * macros will be ignored if set in the "Configurable Defines" section. + */ + +#if defined(SMAA_PRESET_LOW) +#define SMAA_THRESHOLD 0.15 +#define SMAA_MAX_SEARCH_STEPS 4 +#define SMAA_DISABLE_DIAG_DETECTION +#define SMAA_DISABLE_CORNER_DETECTION +#elif defined(SMAA_PRESET_MEDIUM) +#define SMAA_THRESHOLD 0.1 +#define SMAA_MAX_SEARCH_STEPS 8 +#define SMAA_DISABLE_DIAG_DETECTION +#define SMAA_DISABLE_CORNER_DETECTION +#elif defined(SMAA_PRESET_HIGH) +#define SMAA_THRESHOLD 0.1 +#define SMAA_MAX_SEARCH_STEPS 16 +#define SMAA_MAX_SEARCH_STEPS_DIAG 8 +#define SMAA_CORNER_ROUNDING 25 +#elif defined(SMAA_PRESET_ULTRA) +#define SMAA_THRESHOLD 0.05 +#define SMAA_MAX_SEARCH_STEPS 32 +#define SMAA_MAX_SEARCH_STEPS_DIAG 16 +#define SMAA_CORNER_ROUNDING 25 +#endif + +//----------------------------------------------------------------------------- +// Configurable Defines + +/** + * SMAA_THRESHOLD specifies the threshold or sensitivity to edges. + * Lowering this value you will be able to detect more edges at the expense of + * performance. + * + * Range: [0, 0.5] + * 0.1 is a reasonable value, and allows to catch most visible edges. + * 0.05 is a rather overkill value, that allows to catch 'em all. + * + * If temporal supersampling is used, 0.2 could be a reasonable value, as low + * contrast edges are properly filtered by just 2x. + */ +#ifndef SMAA_THRESHOLD +#define SMAA_THRESHOLD 0.1 +#endif + +/** + * SMAA_DEPTH_THRESHOLD specifies the threshold for depth edge detection. + * + * Range: depends on the depth range of the scene. + */ +#ifndef SMAA_DEPTH_THRESHOLD +#define SMAA_DEPTH_THRESHOLD (0.1 * SMAA_THRESHOLD) +#endif + +/** + * SMAA_MAX_SEARCH_STEPS specifies the maximum steps performed in the + * horizontal/vertical pattern searches, at each side of the pixel. + * + * In number of pixels, it's actually the double. So the maximum line length + * perfectly handled by, for example 16, is 64 (by perfectly, we meant that + * longer lines won't look as good, but still antialiased). + * + * Range: [0, 112] + */ +#ifndef SMAA_MAX_SEARCH_STEPS +#define SMAA_MAX_SEARCH_STEPS 16 +#endif + +/** + * SMAA_MAX_SEARCH_STEPS_DIAG specifies the maximum steps performed in the + * diagonal pattern searches, at each side of the pixel. In this case we jump + * one pixel at time, instead of two. + * + * Range: [0, 20] + * + * On high-end machines it is cheap (between a 0.8x and 0.9x slower for 16 + * steps), but it can have a significant impact on older machines. + * + * Define SMAA_DISABLE_DIAG_DETECTION to disable diagonal processing. + */ +#ifndef SMAA_MAX_SEARCH_STEPS_DIAG +#define SMAA_MAX_SEARCH_STEPS_DIAG 8 +#endif + +/** + * SMAA_CORNER_ROUNDING specifies how much sharp corners will be rounded. + * + * Range: [0, 100] + * + * Define SMAA_DISABLE_CORNER_DETECTION to disable corner processing. + */ +#ifndef SMAA_CORNER_ROUNDING +#define SMAA_CORNER_ROUNDING 25 +#endif + +/** + * If there is an neighbor edge that has SMAA_LOCAL_CONTRAST_FACTOR times + * bigger contrast than current edge, current edge will be discarded. + * + * This allows to eliminate spurious crossing edges, and is based on the fact + * that, if there is too much contrast in a direction, that will hide + * perceptually contrast in the other neighbors. + */ +#ifndef SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR +#define SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR 2.0 +#endif + +/** + * Predicated thresholding allows to better preserve texture details and to + * improve performance, by decreasing the number of detected edges using an + * additional buffer like the light accumulation buffer, object ids or even the + * depth buffer (the depth buffer usage may be limited to indoor or short range + * scenes). + * + * It locally decreases the luma or color threshold if an edge is found in an + * additional buffer (so the global threshold can be higher). + * + * This method was developed by Playstation EDGE MLAA team, and used in + * Killzone 3, by using the light accumulation buffer. More information here: + * http://iryoku.com/aacourse/downloads/06-MLAA-on-PS3.pptx + */ +#ifndef SMAA_PREDICATION +#define SMAA_PREDICATION 0 +#endif + +/** + * Threshold to be used in the additional predication buffer. + * + * Range: depends on the input, so you'll have to find the magic number that + * works for you. + */ +#ifndef SMAA_PREDICATION_THRESHOLD +#define SMAA_PREDICATION_THRESHOLD 0.01 +#endif + +/** + * How much to scale the global threshold used for luma or color edge + * detection when using predication. + * + * Range: [1, 5] + */ +#ifndef SMAA_PREDICATION_SCALE +#define SMAA_PREDICATION_SCALE 2.0 +#endif + +/** + * How much to locally decrease the threshold. + * + * Range: [0, 1] + */ +#ifndef SMAA_PREDICATION_STRENGTH +#define SMAA_PREDICATION_STRENGTH 0.4 +#endif + +/** + * Temporal reprojection allows to remove ghosting artifacts when using + * temporal supersampling. We use the CryEngine 3 method which also introduces + * velocity weighting. This feature is of extreme importance for totally + * removing ghosting. More information here: + * http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf + * + * Note that you'll need to setup a velocity buffer for enabling reprojection. + * For static geometry, saving the previous depth buffer is a viable + * alternative. + */ +#ifndef SMAA_REPROJECTION +#define SMAA_REPROJECTION 0 +#endif + +/** + * SMAA_REPROJECTION_WEIGHT_SCALE controls the velocity weighting. It allows to + * remove ghosting trails behind the moving object, which are not removed by + * just using reprojection. Using low values will exhibit ghosting, while using + * high values will disable temporal supersampling under motion. + * + * Behind the scenes, velocity weighting removes temporal supersampling when + * the velocity of the subsamples differs (meaning they are different objects). + * + * Range: [0, 80] + */ +#ifndef SMAA_REPROJECTION_WEIGHT_SCALE +#define SMAA_REPROJECTION_WEIGHT_SCALE 30.0 +#endif + +/** + * On some compilers, discard cannot be used in vertex shaders. Thus, they need + * to be compiled separately. + */ +#ifndef SMAA_INCLUDE_VS +#define SMAA_INCLUDE_VS 1 +#endif +#ifndef SMAA_INCLUDE_PS +#define SMAA_INCLUDE_PS 1 +#endif + +//----------------------------------------------------------------------------- +// Texture Access Defines + +#ifndef SMAA_AREATEX_SELECT +#if defined(SMAA_HLSL_3) +#define SMAA_AREATEX_SELECT(sample) sample.ra +#else +#define SMAA_AREATEX_SELECT(sample) sample.rg +#endif +#endif + +#ifndef SMAA_SEARCHTEX_SELECT +#define SMAA_SEARCHTEX_SELECT(sample) sample.r +#endif + +#ifndef SMAA_DECODE_VELOCITY +#define SMAA_DECODE_VELOCITY(sample) sample.rg +#endif + +//----------------------------------------------------------------------------- +// Non-Configurable Defines + +#define SMAA_AREATEX_MAX_DISTANCE 16 +#define SMAA_AREATEX_MAX_DISTANCE_DIAG 20 +#define SMAA_AREATEX_PIXEL_SIZE (1.0 / float2(160.0, 560.0)) +#define SMAA_AREATEX_SUBTEX_SIZE (1.0 / 7.0) +#define SMAA_SEARCHTEX_SIZE float2(66.0, 33.0) +#define SMAA_SEARCHTEX_PACKED_SIZE float2(64.0, 16.0) +#define SMAA_CORNER_ROUNDING_NORM (float(SMAA_CORNER_ROUNDING) / 100.0) + +//----------------------------------------------------------------------------- +// Porting Functions + +#if defined(SMAA_HLSL_3) +#define SMAATexture2D(tex) sampler2D tex +#define SMAATexturePass2D(tex) tex +#define SMAASampleLevelZero(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0)) +#define SMAASampleLevelZeroPoint(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0)) +#define SMAASampleLevelZeroOffset(tex, coord, offset) tex2Dlod(tex, float4(coord + offset * SMAA_RT_METRICS.xy, 0.0, 0.0)) +#define SMAASample(tex, coord) tex2D(tex, coord) +#define SMAASamplePoint(tex, coord) tex2D(tex, coord) +#define SMAASampleOffset(tex, coord, offset) tex2D(tex, coord + offset * SMAA_RT_METRICS.xy) +#define SMAA_FLATTEN [flatten] +#define SMAA_BRANCH [branch] +#endif +#if defined(SMAA_HLSL_4) || defined(SMAA_HLSL_4_1) +SamplerState LinearSampler { Filter = MIN_MAG_LINEAR_MIP_POINT; AddressU = Clamp; AddressV = Clamp; }; +SamplerState PointSampler { Filter = MIN_MAG_MIP_POINT; AddressU = Clamp; AddressV = Clamp; }; +#define SMAATexture2D(tex) Texture2D tex +#define SMAATexturePass2D(tex) tex +#define SMAASampleLevelZero(tex, coord) tex.SampleLevel(LinearSampler, coord, 0) +#define SMAASampleLevelZeroPoint(tex, coord) tex.SampleLevel(PointSampler, coord, 0) +#define SMAASampleLevelZeroOffset(tex, coord, offset) tex.SampleLevel(LinearSampler, coord, 0, offset) +#define SMAASample(tex, coord) tex.Sample(LinearSampler, coord) +#define SMAASamplePoint(tex, coord) tex.Sample(PointSampler, coord) +#define SMAASampleOffset(tex, coord, offset) tex.Sample(LinearSampler, coord, offset) +#define SMAA_FLATTEN [flatten] +#define SMAA_BRANCH [branch] +#define SMAATexture2DMS2(tex) Texture2DMS tex +#define SMAALoad(tex, pos, sample) tex.Load(pos, sample) +#if defined(SMAA_HLSL_4_1) +#define SMAAGather(tex, coord) tex.Gather(LinearSampler, coord, 0) +#endif +#endif +#if defined(SMAA_GLSL_3) || defined(SMAA_GLSL_4) +#define SMAATexture2D(tex) sampler2D tex +#define SMAATexturePass2D(tex) tex +#define SMAASampleLevelZero(tex, coord) textureLod(tex, coord, 0.0) +#define SMAASampleLevelZeroPoint(tex, coord) textureLod(tex, coord, 0.0) +#define SMAASampleLevelZeroOffset(tex, coord, offset) textureLodOffset(tex, coord, 0.0, offset) +#define SMAASample(tex, coord) texture(tex, coord) +#define SMAASamplePoint(tex, coord) texture(tex, coord) +#define SMAASampleOffset(tex, coord, offset) texture(tex, coord, offset) +#define SMAA_FLATTEN +#define SMAA_BRANCH +#define lerp(a, b, t) mix(a, b, t) +#define saturate(a) clamp(a, 0.0, 1.0) +#if defined(SMAA_GLSL_4) +#define mad(a, b, c) fma(a, b, c) +#define SMAAGather(tex, coord) textureGather(tex, coord) +#else +#define mad(a, b, c) (a * b + c) +#endif +#define float2 vec2 +#define float3 vec3 +#define float4 vec4 +#define int2 ivec2 +#define int3 ivec3 +#define int4 ivec4 +#define bool2 bvec2 +#define bool3 bvec3 +#define bool4 bvec4 +#endif + +#if !defined(SMAA_HLSL_3) && !defined(SMAA_HLSL_4) && !defined(SMAA_HLSL_4_1) && !defined(SMAA_GLSL_3) && !defined(SMAA_GLSL_4) && !defined(SMAA_CUSTOM_SL) +#error you must define the shading language: SMAA_HLSL_*, SMAA_GLSL_* or SMAA_CUSTOM_SL +#endif + +//----------------------------------------------------------------------------- +// Misc functions + +/** + * Gathers current pixel, and the top-left neighbors. + */ +float3 SMAAGatherNeighbours(float2 texcoord, + float4 offset[3], + SMAATexture2D(tex)) { + #ifdef SMAAGather + return SMAAGather(tex, texcoord + SMAA_RT_METRICS.xy * float2(-0.5, -0.5)).grb; + #else + float P = SMAASamplePoint(tex, texcoord).r; + float Pleft = SMAASamplePoint(tex, offset[0].xy).r; + float Ptop = SMAASamplePoint(tex, offset[0].zw).r; + return float3(P, Pleft, Ptop); + #endif +} + +/** + * Adjusts the threshold by means of predication. + */ +float2 SMAACalculatePredicatedThreshold(float2 texcoord, + float4 offset[3], + SMAATexture2D(predicationTex)) { + float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(predicationTex)); + float2 delta = abs(neighbours.xx - neighbours.yz); + float2 edges = step(SMAA_PREDICATION_THRESHOLD, delta); + return SMAA_PREDICATION_SCALE * SMAA_THRESHOLD * (1.0 - SMAA_PREDICATION_STRENGTH * edges); +} + +/** + * Conditional move: + */ +void SMAAMovc(bool2 cond, inout float2 variable, float2 value) { + SMAA_FLATTEN if (cond.x) variable.x = value.x; + SMAA_FLATTEN if (cond.y) variable.y = value.y; +} + +void SMAAMovc(bool4 cond, inout float4 variable, float4 value) { + SMAAMovc(cond.xy, variable.xy, value.xy); + SMAAMovc(cond.zw, variable.zw, value.zw); +} + + +#if SMAA_INCLUDE_VS +//----------------------------------------------------------------------------- +// Vertex Shaders + +/** + * Edge Detection Vertex Shader + */ +void SMAAEdgeDetectionVS(float2 texcoord, + out float4 offset[3]) { + offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-1.0, 0.0, 0.0, -1.0), texcoord.xyxy); + offset[1] = mad(SMAA_RT_METRICS.xyxy, float4( 1.0, 0.0, 0.0, 1.0), texcoord.xyxy); + offset[2] = mad(SMAA_RT_METRICS.xyxy, float4(-2.0, 0.0, 0.0, -2.0), texcoord.xyxy); +} + +/** + * Blend Weight Calculation Vertex Shader + */ +void SMAABlendingWeightCalculationVS(float2 texcoord, + out float2 pixcoord, + out float4 offset[3]) { + pixcoord = texcoord * SMAA_RT_METRICS.zw; + + // We will use these offsets for the searches later on (see @PSEUDO_GATHER4): + offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-0.25, -0.125, 1.25, -0.125), texcoord.xyxy); + offset[1] = mad(SMAA_RT_METRICS.xyxy, float4(-0.125, -0.25, -0.125, 1.25), texcoord.xyxy); + + // And these for the searches, they indicate the ends of the loops: + offset[2] = mad(SMAA_RT_METRICS.xxyy, + float4(-2.0, 2.0, -2.0, 2.0) * float(SMAA_MAX_SEARCH_STEPS), + float4(offset[0].xz, offset[1].yw)); +} + +/** + * Neighborhood Blending Vertex Shader + */ +void SMAANeighborhoodBlendingVS(float2 texcoord, + out float4 offset) { + offset = mad(SMAA_RT_METRICS.xyxy, float4( 1.0, 0.0, 0.0, 1.0), texcoord.xyxy); +} +#endif // SMAA_INCLUDE_VS + +#if SMAA_INCLUDE_PS +//----------------------------------------------------------------------------- +// Edge Detection Pixel Shaders (First Pass) + +/** + * Luma Edge Detection + * + * IMPORTANT NOTICE: luma edge detection requires gamma-corrected colors, and + * thus 'colorTex' should be a non-sRGB texture. + */ +float2 SMAALumaEdgeDetectionPS(float2 texcoord, + float4 offset[3], + SMAATexture2D(colorTex) + #if SMAA_PREDICATION + , SMAATexture2D(predicationTex) + #endif + ) { + // Calculate the threshold: + #if SMAA_PREDICATION + float2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, SMAATexturePass2D(predicationTex)); + #else + float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD); + #endif + + // Calculate lumas: + float3 weights = float3(0.2126, 0.7152, 0.0722); + float L = dot(SMAASamplePoint(colorTex, texcoord).rgb, weights); + + float Lleft = dot(SMAASamplePoint(colorTex, offset[0].xy).rgb, weights); + float Ltop = dot(SMAASamplePoint(colorTex, offset[0].zw).rgb, weights); + + // We do the usual threshold: + float4 delta; + delta.xy = abs(L - float2(Lleft, Ltop)); + float2 edges = step(threshold, delta.xy); + + // Then discard if there is no edge: + if (dot(edges, float2(1.0, 1.0)) == 0.0) + discard; + + // Calculate right and bottom deltas: + float Lright = dot(SMAASamplePoint(colorTex, offset[1].xy).rgb, weights); + float Lbottom = dot(SMAASamplePoint(colorTex, offset[1].zw).rgb, weights); + delta.zw = abs(L - float2(Lright, Lbottom)); + + // Calculate the maximum delta in the direct neighborhood: + float2 maxDelta = max(delta.xy, delta.zw); + + // Calculate left-left and top-top deltas: + float Lleftleft = dot(SMAASamplePoint(colorTex, offset[2].xy).rgb, weights); + float Ltoptop = dot(SMAASamplePoint(colorTex, offset[2].zw).rgb, weights); + delta.zw = abs(float2(Lleft, Ltop) - float2(Lleftleft, Ltoptop)); + + // Calculate the final maximum delta: + maxDelta = max(maxDelta.xy, delta.zw); + float finalDelta = max(maxDelta.x, maxDelta.y); + + // Local contrast adaptation: + edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy); + + return edges; +} + +/** + * Color Edge Detection + * + * IMPORTANT NOTICE: color edge detection requires gamma-corrected colors, and + * thus 'colorTex' should be a non-sRGB texture. + */ +float2 SMAAColorEdgeDetectionPS(float2 texcoord, + float4 offset[3], + SMAATexture2D(colorTex) + #if SMAA_PREDICATION + , SMAATexture2D(predicationTex) + #endif + ) { + // Calculate the threshold: + #if SMAA_PREDICATION + float2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, predicationTex); + #else + float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD); + #endif + + // Calculate color deltas: + float4 delta; + float3 C = SMAASamplePoint(colorTex, texcoord).rgb; + + float3 Cleft = SMAASamplePoint(colorTex, offset[0].xy).rgb; + float3 t = abs(C - Cleft); + delta.x = max(max(t.r, t.g), t.b); + + float3 Ctop = SMAASamplePoint(colorTex, offset[0].zw).rgb; + t = abs(C - Ctop); + delta.y = max(max(t.r, t.g), t.b); + + // We do the usual threshold: + float2 edges = step(threshold, delta.xy); + + // Then discard if there is no edge: + if (dot(edges, float2(1.0, 1.0)) == 0.0) + discard; + + // Calculate right and bottom deltas: + float3 Cright = SMAASamplePoint(colorTex, offset[1].xy).rgb; + t = abs(C - Cright); + delta.z = max(max(t.r, t.g), t.b); + + float3 Cbottom = SMAASamplePoint(colorTex, offset[1].zw).rgb; + t = abs(C - Cbottom); + delta.w = max(max(t.r, t.g), t.b); + + // Calculate the maximum delta in the direct neighborhood: + float2 maxDelta = max(delta.xy, delta.zw); + + // Calculate left-left and top-top deltas: + float3 Cleftleft = SMAASamplePoint(colorTex, offset[2].xy).rgb; + t = abs(C - Cleftleft); + delta.z = max(max(t.r, t.g), t.b); + + float3 Ctoptop = SMAASamplePoint(colorTex, offset[2].zw).rgb; + t = abs(C - Ctoptop); + delta.w = max(max(t.r, t.g), t.b); + + // Calculate the final maximum delta: + maxDelta = max(maxDelta.xy, delta.zw); + float finalDelta = max(maxDelta.x, maxDelta.y); + + // Local contrast adaptation: + edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy); + + return edges; +} + +/** + * Depth Edge Detection + */ +float2 SMAADepthEdgeDetectionPS(float2 texcoord, + float4 offset[3], + SMAATexture2D(depthTex)) { + float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(depthTex)); + float2 delta = abs(neighbours.xx - float2(neighbours.y, neighbours.z)); + float2 edges = step(SMAA_DEPTH_THRESHOLD, delta); + + if (dot(edges, float2(1.0, 1.0)) == 0.0) + discard; + + return edges; +} + +//----------------------------------------------------------------------------- +// Diagonal Search Functions + +#if !defined(SMAA_DISABLE_DIAG_DETECTION) + +/** + * Allows to decode two binary values from a bilinear-filtered access. + */ +float2 SMAADecodeDiagBilinearAccess(float2 e) { + // Bilinear access for fetching 'e' have a 0.25 offset, and we are + // interested in the R and G edges: + // + // +---G---+-------+ + // | x o R x | + // +-------+-------+ + // + // Then, if one of these edge is enabled: + // Red: (0.75 * X + 0.25 * 1) => 0.25 or 1.0 + // Green: (0.75 * 1 + 0.25 * X) => 0.75 or 1.0 + // + // This function will unpack the values (mad + mul + round): + // wolframalpha.com: round(x * abs(5 * x - 5 * 0.75)) plot 0 to 1 + e.r = e.r * abs(5.0 * e.r - 5.0 * 0.75); + return round(e); +} + +float4 SMAADecodeDiagBilinearAccess(float4 e) { + e.rb = e.rb * abs(5.0 * e.rb - 5.0 * 0.75); + return round(e); +} + +/** + * These functions allows to perform diagonal pattern searches. + */ +float2 SMAASearchDiag1(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e) { + float4 coord = float4(texcoord, -1.0, 1.0); + float3 t = float3(SMAA_RT_METRICS.xy, 1.0); + while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) && + coord.w > 0.9) { + coord.xyz = mad(t, float3(dir, 1.0), coord.xyz); + e = SMAASampleLevelZero(edgesTex, coord.xy).rg; + coord.w = dot(e, float2(0.5, 0.5)); + } + return coord.zw; +} + +float2 SMAASearchDiag2(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e) { + float4 coord = float4(texcoord, -1.0, 1.0); + coord.x += 0.25 * SMAA_RT_METRICS.x; // See @SearchDiag2Optimization + float3 t = float3(SMAA_RT_METRICS.xy, 1.0); + while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) && + coord.w > 0.9) { + coord.xyz = mad(t, float3(dir, 1.0), coord.xyz); + + // @SearchDiag2Optimization + // Fetch both edges at once using bilinear filtering: + e = SMAASampleLevelZero(edgesTex, coord.xy).rg; + e = SMAADecodeDiagBilinearAccess(e); + + // Non-optimized version: + // e.g = SMAASampleLevelZero(edgesTex, coord.xy).g; + // e.r = SMAASampleLevelZeroOffset(edgesTex, coord.xy, int2(1, 0)).r; + + coord.w = dot(e, float2(0.5, 0.5)); + } + return coord.zw; +} + +/** + * Similar to SMAAArea, this calculates the area corresponding to a certain + * diagonal distance and crossing edges 'e'. + */ +float2 SMAAAreaDiag(SMAATexture2D(areaTex), float2 dist, float2 e, float offset) { + float2 texcoord = mad(float2(SMAA_AREATEX_MAX_DISTANCE_DIAG, SMAA_AREATEX_MAX_DISTANCE_DIAG), e, dist); + + // We do a scale and bias for mapping to texel space: + texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE); + + // Diagonal areas are on the second half of the texture: + texcoord.x += 0.5; + + // Move to proper place, according to the subpixel offset: + texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset; + + // Do it! + return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord)); +} + +/** + * This searches for diagonal patterns and returns the corresponding weights. + */ +float2 SMAACalculateDiagWeights(SMAATexture2D(edgesTex), SMAATexture2D(areaTex), float2 texcoord, float2 e, float4 subsampleIndices) { + float2 weights = float2(0.0, 0.0); + + // Search for the line ends: + float4 d; + float2 end; + if (e.r > 0.0) { + d.xz = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, 1.0), end); + d.x += float(end.y > 0.9); + } else + d.xz = float2(0.0, 0.0); + d.yw = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, -1.0), end); + + SMAA_BRANCH + if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3 + // Fetch the crossing edges: + float4 coords = mad(float4(-d.x + 0.25, d.x, d.y, -d.y - 0.25), SMAA_RT_METRICS.xyxy, texcoord.xyxy); + float4 c; + c.xy = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).rg; + c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).rg; + c.yxwz = SMAADecodeDiagBilinearAccess(c.xyzw); + + // Non-optimized version: + // float4 coords = mad(float4(-d.x, d.x, d.y, -d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy); + // float4 c; + // c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g; + // c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2( 0, 0)).r; + // c.z = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).g; + // c.w = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, -1)).r; + + // Merge crossing edges at each side into a single value: + float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw); + + // Remove the crossing edge if we didn't found the end of the line: + SMAAMovc(bool2(step(0.9, d.zw)), cc, float2(0.0, 0.0)); + + // Fetch the areas for this line: + weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.z); + } + + // Search for the line ends: + d.xz = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, -1.0), end); + if (SMAASampleLevelZeroOffset(edgesTex, texcoord, int2(1, 0)).r > 0.0) { + d.yw = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, 1.0), end); + d.y += float(end.y > 0.9); + } else + d.yw = float2(0.0, 0.0); + + SMAA_BRANCH + if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3 + // Fetch the crossing edges: + float4 coords = mad(float4(-d.x, -d.x, d.y, d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy); + float4 c; + c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g; + c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2( 0, -1)).r; + c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).gr; + float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw); + + // Remove the crossing edge if we didn't found the end of the line: + SMAAMovc(bool2(step(0.9, d.zw)), cc, float2(0.0, 0.0)); + + // Fetch the areas for this line: + weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.w).gr; + } + + return weights; +} +#endif + +//----------------------------------------------------------------------------- +// Horizontal/Vertical Search Functions + +/** + * This allows to determine how much length should we add in the last step + * of the searches. It takes the bilinearly interpolated edge (see + * @PSEUDO_GATHER4), and adds 0, 1 or 2, depending on which edges and + * crossing edges are active. + */ +float SMAASearchLength(SMAATexture2D(searchTex), float2 e, float offset) { + // The texture is flipped vertically, with left and right cases taking half + // of the space horizontally: + float2 scale = SMAA_SEARCHTEX_SIZE * float2(0.5, -1.0); + float2 bias = SMAA_SEARCHTEX_SIZE * float2(offset, 1.0); + + // Scale and bias to access texel centers: + scale += float2(-1.0, 1.0); + bias += float2( 0.5, -0.5); + + // Convert from pixel coordinates to texcoords: + // (We use SMAA_SEARCHTEX_PACKED_SIZE because the texture is cropped) + scale *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE; + bias *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE; + + // Lookup the search texture: + return SMAA_SEARCHTEX_SELECT(SMAASampleLevelZero(searchTex, mad(scale, e, bias))); +} + +/** + * Horizontal/vertical search functions for the 2nd pass. + */ +float SMAASearchXLeft(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) { + /** + * @PSEUDO_GATHER4 + * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to + * sample between edge, thus fetching four edges in a row. + * Sampling with different offsets in each direction allows to disambiguate + * which edges are active from the four fetched ones. + */ + float2 e = float2(0.0, 1.0); + while (texcoord.x > end && + e.g > 0.8281 && // Is there some edge not activated? + e.r == 0.0) { // Or is there a crossing edge that breaks the line? + e = SMAASampleLevelZero(edgesTex, texcoord).rg; + texcoord = mad(-float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord); + } + + float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0), 3.25); + return mad(SMAA_RT_METRICS.x, offset, texcoord.x); + + // Non-optimized version: + // We correct the previous (-0.25, -0.125) offset we applied: + // texcoord.x += 0.25 * SMAA_RT_METRICS.x; + + // The searches are bias by 1, so adjust the coords accordingly: + // texcoord.x += SMAA_RT_METRICS.x; + + // Disambiguate the length added by the last step: + // texcoord.x += 2.0 * SMAA_RT_METRICS.x; // Undo last step + // texcoord.x -= SMAA_RT_METRICS.x * (255.0 / 127.0) * SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0); + // return mad(SMAA_RT_METRICS.x, offset, texcoord.x); +} + +float SMAASearchXRight(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) { + float2 e = float2(0.0, 1.0); + while (texcoord.x < end && + e.g > 0.8281 && // Is there some edge not activated? + e.r == 0.0) { // Or is there a crossing edge that breaks the line? + e = SMAASampleLevelZero(edgesTex, texcoord).rg; + texcoord = mad(float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord); + } + float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.5), 3.25); + return mad(-SMAA_RT_METRICS.x, offset, texcoord.x); +} + +float SMAASearchYUp(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) { + float2 e = float2(1.0, 0.0); + while (texcoord.y > end && + e.r > 0.8281 && // Is there some edge not activated? + e.g == 0.0) { // Or is there a crossing edge that breaks the line? + e = SMAASampleLevelZero(edgesTex, texcoord).rg; + texcoord = mad(-float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord); + } + float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.0), 3.25); + return mad(SMAA_RT_METRICS.y, offset, texcoord.y); +} + +float SMAASearchYDown(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) { + float2 e = float2(1.0, 0.0); + while (texcoord.y < end && + e.r > 0.8281 && // Is there some edge not activated? + e.g == 0.0) { // Or is there a crossing edge that breaks the line? + e = SMAASampleLevelZero(edgesTex, texcoord).rg; + texcoord = mad(float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord); + } + float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.5), 3.25); + return mad(-SMAA_RT_METRICS.y, offset, texcoord.y); +} + +/** + * Ok, we have the distance and both crossing edges. So, what are the areas + * at each side of current edge? + */ +float2 SMAAArea(SMAATexture2D(areaTex), float2 dist, float e1, float e2, float offset) { + // Rounding prevents precision errors of bilinear filtering: + float2 texcoord = mad(float2(SMAA_AREATEX_MAX_DISTANCE, SMAA_AREATEX_MAX_DISTANCE), round(4.0 * float2(e1, e2)), dist); + + // We do a scale and bias for mapping to texel space: + texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE); + + // Move to proper place, according to the subpixel offset: + texcoord.y = mad(SMAA_AREATEX_SUBTEX_SIZE, offset, texcoord.y); + + // Do it! + return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord)); +} + +//----------------------------------------------------------------------------- +// Corner Detection Functions + +void SMAADetectHorizontalCornerPattern(SMAATexture2D(edgesTex), inout float2 weights, float4 texcoord, float2 d) { + #if !defined(SMAA_DISABLE_CORNER_DETECTION) + float2 leftRight = step(d.xy, d.yx); + float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight; + + rounding /= leftRight.x + leftRight.y; // Reduce blending for pixels in the center of a line. + + float2 factor = float2(1.0, 1.0); + factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, 1)).r; + factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, 1)).r; + factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, -2)).r; + factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, -2)).r; + + weights *= saturate(factor); + #endif +} + +void SMAADetectVerticalCornerPattern(SMAATexture2D(edgesTex), inout float2 weights, float4 texcoord, float2 d) { + #if !defined(SMAA_DISABLE_CORNER_DETECTION) + float2 leftRight = step(d.xy, d.yx); + float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight; + + rounding /= leftRight.x + leftRight.y; + + float2 factor = float2(1.0, 1.0); + factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2( 1, 0)).g; + factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2( 1, 1)).g; + factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(-2, 0)).g; + factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(-2, 1)).g; + + weights *= saturate(factor); + #endif +} + +//----------------------------------------------------------------------------- +// Blending Weight Calculation Pixel Shader (Second Pass) + +float4 SMAABlendingWeightCalculationPS(float2 texcoord, + float2 pixcoord, + float4 offset[3], + SMAATexture2D(edgesTex), + SMAATexture2D(areaTex), + SMAATexture2D(searchTex), + float4 subsampleIndices) { // Just pass zero for SMAA 1x, see @SUBSAMPLE_INDICES. + float4 weights = float4(0.0, 0.0, 0.0, 0.0); + + float2 e = SMAASample(edgesTex, texcoord).rg; + + SMAA_BRANCH + if (e.g > 0.0) { // Edge at north + #if !defined(SMAA_DISABLE_DIAG_DETECTION) + // Diagonals have both north and west edges, so searching for them in + // one of the boundaries is enough. + weights.rg = SMAACalculateDiagWeights(SMAATexturePass2D(edgesTex), SMAATexturePass2D(areaTex), texcoord, e, subsampleIndices); + + // We give priority to diagonals, so if we find a diagonal we skip + // horizontal/vertical processing. + SMAA_BRANCH + if (weights.r == -weights.g) { // weights.r + weights.g == 0.0 + #endif + + float2 d; + + // Find the distance to the left: + float3 coords; + coords.x = SMAASearchXLeft(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].xy, offset[2].x); + coords.y = offset[1].y; // offset[1].y = texcoord.y - 0.25 * SMAA_RT_METRICS.y (@CROSSING_OFFSET) + d.x = coords.x; + + // Now fetch the left crossing edges, two at a time using bilinear + // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to + // discern what value each edge has: + float e1 = SMAASampleLevelZero(edgesTex, coords.xy).r; + + // Find the distance to the right: + coords.z = SMAASearchXRight(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].zw, offset[2].y); + d.y = coords.z; + + // We want the distances to be in pixel units (doing this here allow to + // better interleave arithmetic and memory accesses): + d = abs(round(mad(SMAA_RT_METRICS.zz, d, -pixcoord.xx))); + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + float2 sqrt_d = sqrt(d); + + // Fetch the right crossing edges: + float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.zy, int2(1, 0)).r; + + // Ok, we know how this pattern looks like, now it is time for getting + // the actual area: + weights.rg = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.y); + + // Fix corners: + coords.y = texcoord.y; + SMAADetectHorizontalCornerPattern(SMAATexturePass2D(edgesTex), weights.rg, coords.xyzy, d); + + #if !defined(SMAA_DISABLE_DIAG_DETECTION) + } else + e.r = 0.0; // Skip vertical processing. + #endif + } + + SMAA_BRANCH + if (e.r > 0.0) { // Edge at west + float2 d; + + // Find the distance to the top: + float3 coords; + coords.y = SMAASearchYUp(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].xy, offset[2].z); + coords.x = offset[0].x; // offset[1].x = texcoord.x - 0.25 * SMAA_RT_METRICS.x; + d.x = coords.y; + + // Fetch the top crossing edges: + float e1 = SMAASampleLevelZero(edgesTex, coords.xy).g; + + // Find the distance to the bottom: + coords.z = SMAASearchYDown(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].zw, offset[2].w); + d.y = coords.z; + + // We want the distances to be in pixel units: + d = abs(round(mad(SMAA_RT_METRICS.ww, d, -pixcoord.yy))); + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + float2 sqrt_d = sqrt(d); + + // Fetch the bottom crossing edges: + float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.xz, int2(0, 1)).g; + + // Get the area for this direction: + weights.ba = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.x); + + // Fix corners: + coords.x = texcoord.x; + SMAADetectVerticalCornerPattern(SMAATexturePass2D(edgesTex), weights.ba, coords.xyxz, d); + } + + return weights; +} + +//----------------------------------------------------------------------------- +// Neighborhood Blending Pixel Shader (Third Pass) + +float4 SMAANeighborhoodBlendingPS(float2 texcoord, + float4 offset, + SMAATexture2D(colorTex), + SMAATexture2D(blendTex) + #if SMAA_REPROJECTION + , SMAATexture2D(velocityTex) + #endif + ) { + // Fetch the blending weights for current pixel: + float4 a; + a.x = SMAASample(blendTex, offset.xy).a; // Right + a.y = SMAASample(blendTex, offset.zw).g; // Top + a.wz = SMAASample(blendTex, texcoord).xz; // Bottom / Left + + // Is there any blending weight with a value greater than 0.0? + SMAA_BRANCH + if (dot(a, float4(1.0, 1.0, 1.0, 1.0)) < 1e-5) { + float4 color = SMAASampleLevelZero(colorTex, texcoord); + + #if SMAA_REPROJECTION + float2 velocity = SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, texcoord)); + + // Pack velocity into the alpha channel: + color.a = sqrt(5.0 * length(velocity)); + #endif + + return color; + } else { + bool h = max(a.x, a.z) > max(a.y, a.w); // max(horizontal) > max(vertical) + + // Calculate the blending offsets: + float4 blendingOffset = float4(0.0, a.y, 0.0, a.w); + float2 blendingWeight = a.yw; + SMAAMovc(bool4(h, h, h, h), blendingOffset, float4(a.x, 0.0, a.z, 0.0)); + SMAAMovc(bool2(h, h), blendingWeight, a.xz); + blendingWeight /= dot(blendingWeight, float2(1.0, 1.0)); + + // Calculate the texture coordinates: + float4 blendingCoord = mad(blendingOffset, float4(SMAA_RT_METRICS.xy, -SMAA_RT_METRICS.xy), texcoord.xyxy); + + // We exploit bilinear filtering to mix current pixel with the chosen + // neighbor: + float4 color = blendingWeight.x * SMAASampleLevelZero(colorTex, blendingCoord.xy); + color += blendingWeight.y * SMAASampleLevelZero(colorTex, blendingCoord.zw); + + #if SMAA_REPROJECTION + // Antialias velocity for proper reprojection in a later stage: + float2 velocity = blendingWeight.x * SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.xy)); + velocity += blendingWeight.y * SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.zw)); + + // Pack velocity into the alpha channel: + color.a = sqrt(5.0 * length(velocity)); + #endif + + return color; + } +} + +//----------------------------------------------------------------------------- +// Temporal Resolve Pixel Shader (Optional Pass) + +float4 SMAAResolvePS(float2 texcoord, + SMAATexture2D(currentColorTex), + SMAATexture2D(previousColorTex) + #if SMAA_REPROJECTION + , SMAATexture2D(velocityTex) + #endif + ) { + #if SMAA_REPROJECTION + // Velocity is assumed to be calculated for motion blur, so we need to + // inverse it for reprojection: + float2 velocity = -SMAA_DECODE_VELOCITY(SMAASamplePoint(velocityTex, texcoord).rg); + + // Fetch current pixel: + float4 current = SMAASamplePoint(currentColorTex, texcoord); + + // Reproject current coordinates and fetch previous pixel: + float4 previous = SMAASamplePoint(previousColorTex, texcoord + velocity); + + // Attenuate the previous pixel if the velocity is different: + float delta = abs(current.a * current.a - previous.a * previous.a) / 5.0; + float weight = 0.5 * saturate(1.0 - sqrt(delta) * SMAA_REPROJECTION_WEIGHT_SCALE); + + // Blend the pixels according to the calculated weight: + return lerp(current, previous, weight); + #else + // Just blend the pixels: + float4 current = SMAASamplePoint(currentColorTex, texcoord); + float4 previous = SMAASamplePoint(previousColorTex, texcoord); + return lerp(current, previous, 0.5); + #endif +} + +//----------------------------------------------------------------------------- +// Separate Multisamples Pixel Shader (Optional Pass) + +#ifdef SMAALoad +void SMAASeparatePS(float4 position, + float2 texcoord, + out float4 target0, + out float4 target1, + SMAATexture2DMS2(colorTexMS)) { + int2 pos = int2(position.xy); + target0 = SMAALoad(colorTexMS, pos, 0); + target1 = SMAALoad(colorTexMS, pos, 1); +} +#endif + +//----------------------------------------------------------------------------- +#endif // SMAA_INCLUDE_PS diff --git a/app/src/main/cpp/shaders/THIRD_PARTY_NOTICES.txt b/app/src/main/cpp/shaders/THIRD_PARTY_NOTICES.txt index 761743c464..ffbc6b370b 100644 --- a/app/src/main/cpp/shaders/THIRD_PARTY_NOTICES.txt +++ b/app/src/main/cpp/shaders/THIRD_PARTY_NOTICES.txt @@ -124,3 +124,33 @@ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +SMAA (Enhanced Subpixel Morphological Antialiasing) +--------------------------------------------------- +SMAA.hlsl and the lookup tables in smaa_tables.h are from the authors' reference +implementation (github.com/iryoku/smaa). + +Copyright (C) 2013 Jorge Jimenez (jorge@iryoku.com) +Copyright (C) 2013 Jose I. Echevarria (joseignacioechevarria@gmail.com) +Copyright (C) 2013 Belen Masia (bmasia@unizar.es) +Copyright (C) 2013 Fernando Navarro (fernandn@microsoft.com) +Copyright (C) 2013 Diego Gutierrez (diegog@unizar.es) + +Permission is hereby granted, free of charge, to any person obtaining a copy +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. As clarification, there is no +requirement that the copyright notice and permission be included in binary +distributions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 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/shaders/smaa_blend.frag b/app/src/main/cpp/shaders/smaa_blend.frag index cf4a2302a6..cd36894637 100644 --- a/app/src/main/cpp/shaders/smaa_blend.frag +++ b/app/src/main/cpp/shaders/smaa_blend.frag @@ -1,4 +1,5 @@ #version 450 +#extension GL_GOOGLE_include_directive : require layout(location = 0) in vec2 fragTexCoord; layout(location = 0) out vec4 outColor; @@ -6,25 +7,16 @@ layout(set = 0, binding = 0) uniform sampler2D InputTexture; layout(set = 1, binding = 0) uniform sampler2D WeightTexture; layout(push_constant) uniform Constants { vec4 ndc; - vec2 resolution; - float extra; - float pad; + vec4 metrics; // 1/width, 1/height, width, height } pc; +#define SMAA_RT_METRICS pc.metrics +#define SMAA_GLSL_4 +#define SMAA_PRESET_HIGH +#include "SMAA.hlsl" + void main() { - vec2 px = 1.0 / max(pc.resolution, vec2(1.0)); - vec2 uv = clamp(fragTexCoord, px * 0.5, vec2(1.0) - px * 0.5); - vec4 center = texture(InputTexture, uv); - vec4 weights = texture(WeightTexture, uv); - float weight = clamp(weights.r, 0.0, 0.42); - - if (weight <= 0.001) { - outColor = center; - return; - } - - vec2 normal = weights.gb * 2.0 - 1.0; - vec2 acrossUv = clamp(uv + normal * px, px * 0.5, vec2(1.0) - px * 0.5); - vec3 across = texture(InputTexture, acrossUv).rgb; - outColor = vec4(mix(center.rgb, across, weight), center.a); + vec4 offset; + SMAANeighborhoodBlendingVS(fragTexCoord, offset); + outColor = SMAANeighborhoodBlendingPS(fragTexCoord, offset, InputTexture, WeightTexture); } diff --git a/app/src/main/cpp/shaders/smaa_blend_frag.h b/app/src/main/cpp/shaders/smaa_blend_frag.h index bcb4749618..55ca213931 100644 --- a/app/src/main/cpp/shaders/smaa_blend_frag.h +++ b/app/src/main/cpp/shaders/smaa_blend_frag.h @@ -1,88 +1,204 @@ - // 1116.3.0 + // 1116.6.0 #pragma once const uint32_t smaa_blend_code[] = { - 0x07230203,0x00010000,0x0008000b,0x0000006b,0x00000000,0x00020011,0x00000001,0x0006000b, + 0x07230203,0x00010000,0x0008000b,0x000000f8,0x00000000,0x00020011,0x00000001,0x0006000b, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, - 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x0000001a,0x00000041,0x00030010, - 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, - 0x00000000,0x00030005,0x00000009,0x00007870,0x00050005,0x0000000c,0x736e6f43,0x746e6174, - 0x00000073,0x00040006,0x0000000c,0x00000000,0x0063646e,0x00060006,0x0000000c,0x00000001, - 0x6f736572,0x6974756c,0x00006e6f,0x00050006,0x0000000c,0x00000002,0x72747865,0x00000061, - 0x00040006,0x0000000c,0x00000003,0x00646170,0x00030005,0x0000000e,0x00006370,0x00030005, - 0x00000018,0x00007675,0x00060005,0x0000001a,0x67617266,0x43786554,0x64726f6f,0x00000000, - 0x00040005,0x00000024,0x746e6563,0x00007265,0x00060005,0x00000028,0x75706e49,0x78655474, - 0x65727574,0x00000000,0x00040005,0x0000002c,0x67696577,0x00737468,0x00060005,0x0000002d, - 0x67696557,0x65547468,0x72757478,0x00000065,0x00040005,0x00000032,0x67696577,0x00007468, - 0x00050005,0x00000041,0x4374756f,0x726f6c6f,0x00000000,0x00040005,0x00000044,0x6d726f6e, - 0x00006c61,0x00050005,0x0000004b,0x6f726361,0x76557373,0x00000000,0x00040005,0x00000059, - 0x6f726361,0x00007373,0x00030047,0x0000000c,0x00000002,0x00050048,0x0000000c,0x00000000, - 0x00000023,0x00000000,0x00050048,0x0000000c,0x00000001,0x00000023,0x00000010,0x00050048, - 0x0000000c,0x00000002,0x00000023,0x00000018,0x00050048,0x0000000c,0x00000003,0x00000023, - 0x0000001c,0x00040047,0x0000001a,0x0000001e,0x00000000,0x00040047,0x00000028,0x00000021, - 0x00000000,0x00040047,0x00000028,0x00000022,0x00000000,0x00040047,0x0000002d,0x00000021, - 0x00000000,0x00040047,0x0000002d,0x00000022,0x00000001,0x00040047,0x00000041,0x0000001e, - 0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006, - 0x00000020,0x00040017,0x00000007,0x00000006,0x00000002,0x00040020,0x00000008,0x00000007, - 0x00000007,0x0004002b,0x00000006,0x0000000a,0x3f800000,0x00040017,0x0000000b,0x00000006, - 0x00000004,0x0006001e,0x0000000c,0x0000000b,0x00000007,0x00000006,0x00000006,0x00040020, - 0x0000000d,0x00000009,0x0000000c,0x0004003b,0x0000000d,0x0000000e,0x00000009,0x00040015, - 0x0000000f,0x00000020,0x00000001,0x0004002b,0x0000000f,0x00000010,0x00000001,0x00040020, - 0x00000011,0x00000009,0x00000007,0x0005002c,0x00000007,0x00000014,0x0000000a,0x0000000a, - 0x00040020,0x00000019,0x00000001,0x00000007,0x0004003b,0x00000019,0x0000001a,0x00000001, - 0x0004002b,0x00000006,0x0000001d,0x3f000000,0x00040020,0x00000023,0x00000007,0x0000000b, - 0x00090019,0x00000025,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,0x00000001, - 0x00000000,0x0003001b,0x00000026,0x00000025,0x00040020,0x00000027,0x00000000,0x00000026, - 0x0004003b,0x00000027,0x00000028,0x00000000,0x0004003b,0x00000027,0x0000002d,0x00000000, - 0x00040020,0x00000031,0x00000007,0x00000006,0x00040015,0x00000033,0x00000020,0x00000000, - 0x0004002b,0x00000033,0x00000034,0x00000000,0x0004002b,0x00000006,0x00000037,0x00000000, - 0x0004002b,0x00000006,0x00000038,0x3ed70a3d,0x0004002b,0x00000006,0x0000003b,0x3a83126f, - 0x00020014,0x0000003c,0x00040020,0x00000040,0x00000003,0x0000000b,0x0004003b,0x00000040, - 0x00000041,0x00000003,0x0004002b,0x00000006,0x00000047,0x40000000,0x00040017,0x00000057, - 0x00000006,0x00000003,0x00040020,0x00000058,0x00000007,0x00000057,0x0004002b,0x00000033, - 0x00000064,0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8, - 0x00000005,0x0004003b,0x00000008,0x00000009,0x00000007,0x0004003b,0x00000008,0x00000018, - 0x00000007,0x0004003b,0x00000023,0x00000024,0x00000007,0x0004003b,0x00000023,0x0000002c, - 0x00000007,0x0004003b,0x00000031,0x00000032,0x00000007,0x0004003b,0x00000008,0x00000044, - 0x00000007,0x0004003b,0x00000008,0x0000004b,0x00000007,0x0004003b,0x00000058,0x00000059, - 0x00000007,0x00050041,0x00000011,0x00000012,0x0000000e,0x00000010,0x0004003d,0x00000007, - 0x00000013,0x00000012,0x0007000c,0x00000007,0x00000015,0x00000001,0x00000028,0x00000013, - 0x00000014,0x00050050,0x00000007,0x00000016,0x0000000a,0x0000000a,0x00050088,0x00000007, - 0x00000017,0x00000016,0x00000015,0x0003003e,0x00000009,0x00000017,0x0004003d,0x00000007, - 0x0000001b,0x0000001a,0x0004003d,0x00000007,0x0000001c,0x00000009,0x0005008e,0x00000007, - 0x0000001e,0x0000001c,0x0000001d,0x0004003d,0x00000007,0x0000001f,0x00000009,0x0005008e, - 0x00000007,0x00000020,0x0000001f,0x0000001d,0x00050083,0x00000007,0x00000021,0x00000014, - 0x00000020,0x0008000c,0x00000007,0x00000022,0x00000001,0x0000002b,0x0000001b,0x0000001e, - 0x00000021,0x0003003e,0x00000018,0x00000022,0x0004003d,0x00000026,0x00000029,0x00000028, - 0x0004003d,0x00000007,0x0000002a,0x00000018,0x00050057,0x0000000b,0x0000002b,0x00000029, - 0x0000002a,0x0003003e,0x00000024,0x0000002b,0x0004003d,0x00000026,0x0000002e,0x0000002d, - 0x0004003d,0x00000007,0x0000002f,0x00000018,0x00050057,0x0000000b,0x00000030,0x0000002e, - 0x0000002f,0x0003003e,0x0000002c,0x00000030,0x00050041,0x00000031,0x00000035,0x0000002c, - 0x00000034,0x0004003d,0x00000006,0x00000036,0x00000035,0x0008000c,0x00000006,0x00000039, - 0x00000001,0x0000002b,0x00000036,0x00000037,0x00000038,0x0003003e,0x00000032,0x00000039, - 0x0004003d,0x00000006,0x0000003a,0x00000032,0x000500bc,0x0000003c,0x0000003d,0x0000003a, - 0x0000003b,0x000300f7,0x0000003f,0x00000000,0x000400fa,0x0000003d,0x0000003e,0x0000003f, - 0x000200f8,0x0000003e,0x0004003d,0x0000000b,0x00000042,0x00000024,0x0003003e,0x00000041, - 0x00000042,0x000100fd,0x000200f8,0x0000003f,0x0004003d,0x0000000b,0x00000045,0x0000002c, - 0x0007004f,0x00000007,0x00000046,0x00000045,0x00000045,0x00000001,0x00000002,0x0005008e, - 0x00000007,0x00000048,0x00000046,0x00000047,0x00050050,0x00000007,0x00000049,0x0000000a, - 0x0000000a,0x00050083,0x00000007,0x0000004a,0x00000048,0x00000049,0x0003003e,0x00000044, - 0x0000004a,0x0004003d,0x00000007,0x0000004c,0x00000018,0x0004003d,0x00000007,0x0000004d, - 0x00000044,0x0004003d,0x00000007,0x0000004e,0x00000009,0x00050085,0x00000007,0x0000004f, - 0x0000004d,0x0000004e,0x00050081,0x00000007,0x00000050,0x0000004c,0x0000004f,0x0004003d, - 0x00000007,0x00000051,0x00000009,0x0005008e,0x00000007,0x00000052,0x00000051,0x0000001d, - 0x0004003d,0x00000007,0x00000053,0x00000009,0x0005008e,0x00000007,0x00000054,0x00000053, - 0x0000001d,0x00050083,0x00000007,0x00000055,0x00000014,0x00000054,0x0008000c,0x00000007, - 0x00000056,0x00000001,0x0000002b,0x00000050,0x00000052,0x00000055,0x0003003e,0x0000004b, - 0x00000056,0x0004003d,0x00000026,0x0000005a,0x00000028,0x0004003d,0x00000007,0x0000005b, - 0x0000004b,0x00050057,0x0000000b,0x0000005c,0x0000005a,0x0000005b,0x0008004f,0x00000057, - 0x0000005d,0x0000005c,0x0000005c,0x00000000,0x00000001,0x00000002,0x0003003e,0x00000059, - 0x0000005d,0x0004003d,0x0000000b,0x0000005e,0x00000024,0x0008004f,0x00000057,0x0000005f, - 0x0000005e,0x0000005e,0x00000000,0x00000001,0x00000002,0x0004003d,0x00000057,0x00000060, - 0x00000059,0x0004003d,0x00000006,0x00000061,0x00000032,0x00060050,0x00000057,0x00000062, - 0x00000061,0x00000061,0x00000061,0x0008000c,0x00000057,0x00000063,0x00000001,0x0000002e, - 0x0000005f,0x00000060,0x00000062,0x00050041,0x00000031,0x00000065,0x00000024,0x00000064, - 0x0004003d,0x00000006,0x00000066,0x00000065,0x00050051,0x00000006,0x00000067,0x00000063, - 0x00000000,0x00050051,0x00000006,0x00000068,0x00000063,0x00000001,0x00050051,0x00000006, - 0x00000069,0x00000063,0x00000002,0x00070050,0x0000000b,0x0000006a,0x00000067,0x00000068, - 0x00000069,0x00000066,0x0003003e,0x00000041,0x0000006a,0x000100fd,0x00010038 + 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x000000e8,0x000000f0,0x00030010, + 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x000a0004,0x475f4c47,0x4c474f4f, + 0x70635f45,0x74735f70,0x5f656c79,0x656e696c,0x7269645f,0x69746365,0x00006576,0x00080004, + 0x475f4c47,0x4c474f4f,0x6e695f45,0x64756c63,0x69645f65,0x74636572,0x00657669,0x00040005, + 0x00000004,0x6e69616d,0x00000000,0x00080005,0x00000010,0x41414d53,0x63766f4d,0x32627628, + 0x3266763b,0x3266763b,0x0000003b,0x00040005,0x0000000d,0x646e6f63,0x00000000,0x00050005, + 0x0000000e,0x69726176,0x656c6261,0x00000000,0x00040005,0x0000000f,0x756c6176,0x00000065, + 0x00080005,0x0000001a,0x41414d53,0x63766f4d,0x34627628,0x3466763b,0x3466763b,0x0000003b, + 0x00040005,0x00000017,0x646e6f63,0x00000000,0x00050005,0x00000018,0x69726176,0x656c6261, + 0x00000000,0x00040005,0x00000019,0x756c6176,0x00000065,0x000b0005,0x0000001f,0x41414d53, + 0x6769654e,0x726f6268,0x646f6f68,0x6e656c42,0x676e6964,0x76285356,0x763b3266,0x003b3466, + 0x00050005,0x0000001d,0x63786574,0x64726f6f,0x00000000,0x00040005,0x0000001e,0x7366666f, + 0x00007465,0x000d0005,0x00000029,0x41414d53,0x6769654e,0x726f6268,0x646f6f68,0x6e656c42, + 0x676e6964,0x76285350,0x763b3266,0x733b3466,0x733b3132,0x003b3132,0x00050005,0x00000025, + 0x63786574,0x64726f6f,0x00000000,0x00040005,0x00000026,0x7366666f,0x00007465,0x00050005, + 0x00000027,0x6f6c6f63,0x78655472,0x00000000,0x00050005,0x00000028,0x6e656c62,0x78655464, + 0x00000000,0x00040005,0x0000003e,0x61726170,0x0000006d,0x00040005,0x00000041,0x61726170, + 0x0000006d,0x00040005,0x00000044,0x61726170,0x0000006d,0x00040005,0x0000004d,0x61726170, + 0x0000006d,0x00040005,0x00000050,0x61726170,0x0000006d,0x00040005,0x00000053,0x61726170, + 0x0000006d,0x00050005,0x0000005e,0x736e6f43,0x746e6174,0x00000073,0x00040006,0x0000005e, + 0x00000000,0x0063646e,0x00050006,0x0000005e,0x00000001,0x7274656d,0x00736369,0x00030005, + 0x00000060,0x00006370,0x00030005,0x0000006d,0x00000061,0x00040005,0x00000089,0x6f6c6f63, + 0x00000072,0x00030005,0x00000090,0x00000068,0x00060005,0x0000009c,0x6e656c62,0x676e6964, + 0x7366664f,0x00007465,0x00060005,0x000000a2,0x6e656c62,0x676e6964,0x67696557,0x00007468, + 0x00040005,0x000000ac,0x61726170,0x0000006d,0x00040005,0x000000ad,0x61726170,0x0000006d, + 0x00040005,0x000000af,0x61726170,0x0000006d,0x00040005,0x000000b4,0x61726170,0x0000006d, + 0x00040005,0x000000b5,0x61726170,0x0000006d,0x00040005,0x000000b7,0x61726170,0x0000006d, + 0x00060005,0x000000c2,0x6e656c62,0x676e6964,0x726f6f43,0x00000064,0x00040005,0x000000d3, + 0x6f6c6f63,0x00000072,0x00060005,0x000000e8,0x67617266,0x43786554,0x64726f6f,0x00000000, + 0x00040005,0x000000e9,0x7366666f,0x00007465,0x00040005,0x000000ea,0x61726170,0x0000006d, + 0x00040005,0x000000ec,0x61726170,0x0000006d,0x00050005,0x000000f0,0x4374756f,0x726f6c6f, + 0x00000000,0x00060005,0x000000f1,0x75706e49,0x78655474,0x65727574,0x00000000,0x00060005, + 0x000000f2,0x67696557,0x65547468,0x72757478,0x00000065,0x00040005,0x000000f3,0x61726170, + 0x0000006d,0x00040005,0x000000f5,0x61726170,0x0000006d,0x00030047,0x0000005e,0x00000002, + 0x00050048,0x0000005e,0x00000000,0x00000023,0x00000000,0x00050048,0x0000005e,0x00000001, + 0x00000023,0x00000010,0x00040047,0x000000e8,0x0000001e,0x00000000,0x00040047,0x000000f0, + 0x0000001e,0x00000000,0x00040047,0x000000f1,0x00000021,0x00000000,0x00040047,0x000000f1, + 0x00000022,0x00000000,0x00040047,0x000000f2,0x00000021,0x00000000,0x00040047,0x000000f2, + 0x00000022,0x00000001,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00020014, + 0x00000006,0x00040017,0x00000007,0x00000006,0x00000002,0x00040020,0x00000008,0x00000007, + 0x00000007,0x00030016,0x00000009,0x00000020,0x00040017,0x0000000a,0x00000009,0x00000002, + 0x00040020,0x0000000b,0x00000007,0x0000000a,0x00060021,0x0000000c,0x00000002,0x00000008, + 0x0000000b,0x0000000b,0x00040017,0x00000012,0x00000006,0x00000004,0x00040020,0x00000013, + 0x00000007,0x00000012,0x00040017,0x00000014,0x00000009,0x00000004,0x00040020,0x00000015, + 0x00000007,0x00000014,0x00060021,0x00000016,0x00000002,0x00000013,0x00000015,0x00000015, + 0x00050021,0x0000001c,0x00000002,0x0000000b,0x00000015,0x00090019,0x00000021,0x00000009, + 0x00000001,0x00000000,0x00000000,0x00000000,0x00000001,0x00000000,0x0003001b,0x00000022, + 0x00000021,0x00040020,0x00000023,0x00000000,0x00000022,0x00070021,0x00000024,0x00000014, + 0x0000000b,0x00000015,0x00000023,0x00000023,0x00040015,0x0000002b,0x00000020,0x00000000, + 0x0004002b,0x0000002b,0x0000002c,0x00000000,0x00040020,0x0000002d,0x00000007,0x00000006, + 0x00040020,0x00000032,0x00000007,0x00000009,0x0004002b,0x0000002b,0x00000036,0x00000001, + 0x0004002b,0x0000002b,0x00000058,0x00000002,0x0004002b,0x0000002b,0x0000005b,0x00000003, + 0x0004001e,0x0000005e,0x00000014,0x00000014,0x00040020,0x0000005f,0x00000009,0x0000005e, + 0x0004003b,0x0000005f,0x00000060,0x00000009,0x00040015,0x00000061,0x00000020,0x00000001, + 0x0004002b,0x00000061,0x00000062,0x00000001,0x00040020,0x00000063,0x00000009,0x00000014, + 0x0004002b,0x00000009,0x00000067,0x3f800000,0x0004002b,0x00000009,0x00000068,0x00000000, + 0x0007002c,0x00000014,0x00000069,0x00000067,0x00000068,0x00000068,0x00000067,0x0007002c, + 0x00000014,0x00000083,0x00000067,0x00000067,0x00000067,0x00000067,0x0004002b,0x00000009, + 0x00000085,0x3727c5ac,0x0005002c,0x0000000a,0x000000bd,0x00000067,0x00000067,0x00040020, + 0x000000e7,0x00000001,0x0000000a,0x0004003b,0x000000e7,0x000000e8,0x00000001,0x00040020, + 0x000000ef,0x00000003,0x00000014,0x0004003b,0x000000ef,0x000000f0,0x00000003,0x0004003b, + 0x00000023,0x000000f1,0x00000000,0x0004003b,0x00000023,0x000000f2,0x00000000,0x00050036, + 0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x0004003b,0x00000015, + 0x000000e9,0x00000007,0x0004003b,0x0000000b,0x000000ea,0x00000007,0x0004003b,0x00000015, + 0x000000ec,0x00000007,0x0004003b,0x0000000b,0x000000f3,0x00000007,0x0004003b,0x00000015, + 0x000000f5,0x00000007,0x0004003d,0x0000000a,0x000000eb,0x000000e8,0x0003003e,0x000000ea, + 0x000000eb,0x00060039,0x00000002,0x000000ed,0x0000001f,0x000000ea,0x000000ec,0x0004003d, + 0x00000014,0x000000ee,0x000000ec,0x0003003e,0x000000e9,0x000000ee,0x0004003d,0x0000000a, + 0x000000f4,0x000000e8,0x0003003e,0x000000f3,0x000000f4,0x0004003d,0x00000014,0x000000f6, + 0x000000e9,0x0003003e,0x000000f5,0x000000f6,0x00080039,0x00000014,0x000000f7,0x00000029, + 0x000000f3,0x000000f5,0x000000f1,0x000000f2,0x0003003e,0x000000f0,0x000000f7,0x000100fd, + 0x00010038,0x00050036,0x00000002,0x00000010,0x00000000,0x0000000c,0x00030037,0x00000008, + 0x0000000d,0x00030037,0x0000000b,0x0000000e,0x00030037,0x0000000b,0x0000000f,0x000200f8, + 0x00000011,0x00050041,0x0000002d,0x0000002e,0x0000000d,0x0000002c,0x0004003d,0x00000006, + 0x0000002f,0x0000002e,0x000300f7,0x00000031,0x00000000,0x000400fa,0x0000002f,0x00000030, + 0x00000031,0x000200f8,0x00000030,0x00050041,0x00000032,0x00000033,0x0000000f,0x0000002c, + 0x0004003d,0x00000009,0x00000034,0x00000033,0x00050041,0x00000032,0x00000035,0x0000000e, + 0x0000002c,0x0003003e,0x00000035,0x00000034,0x000200f9,0x00000031,0x000200f8,0x00000031, + 0x00050041,0x0000002d,0x00000037,0x0000000d,0x00000036,0x0004003d,0x00000006,0x00000038, + 0x00000037,0x000300f7,0x0000003a,0x00000000,0x000400fa,0x00000038,0x00000039,0x0000003a, + 0x000200f8,0x00000039,0x00050041,0x00000032,0x0000003b,0x0000000f,0x00000036,0x0004003d, + 0x00000009,0x0000003c,0x0000003b,0x00050041,0x00000032,0x0000003d,0x0000000e,0x00000036, + 0x0003003e,0x0000003d,0x0000003c,0x000200f9,0x0000003a,0x000200f8,0x0000003a,0x000100fd, + 0x00010038,0x00050036,0x00000002,0x0000001a,0x00000000,0x00000016,0x00030037,0x00000013, + 0x00000017,0x00030037,0x00000015,0x00000018,0x00030037,0x00000015,0x00000019,0x000200f8, + 0x0000001b,0x0004003b,0x00000008,0x0000003e,0x00000007,0x0004003b,0x0000000b,0x00000041, + 0x00000007,0x0004003b,0x0000000b,0x00000044,0x00000007,0x0004003b,0x00000008,0x0000004d, + 0x00000007,0x0004003b,0x0000000b,0x00000050,0x00000007,0x0004003b,0x0000000b,0x00000053, + 0x00000007,0x0004003d,0x00000012,0x0000003f,0x00000017,0x0007004f,0x00000007,0x00000040, + 0x0000003f,0x0000003f,0x00000000,0x00000001,0x0003003e,0x0000003e,0x00000040,0x0004003d, + 0x00000014,0x00000042,0x00000018,0x0007004f,0x0000000a,0x00000043,0x00000042,0x00000042, + 0x00000000,0x00000001,0x0003003e,0x00000041,0x00000043,0x0004003d,0x00000014,0x00000045, + 0x00000019,0x0007004f,0x0000000a,0x00000046,0x00000045,0x00000045,0x00000000,0x00000001, + 0x0003003e,0x00000044,0x00000046,0x00070039,0x00000002,0x00000047,0x00000010,0x0000003e, + 0x00000041,0x00000044,0x0004003d,0x0000000a,0x00000048,0x00000041,0x00050041,0x00000032, + 0x00000049,0x00000018,0x0000002c,0x00050051,0x00000009,0x0000004a,0x00000048,0x00000000, + 0x0003003e,0x00000049,0x0000004a,0x00050041,0x00000032,0x0000004b,0x00000018,0x00000036, + 0x00050051,0x00000009,0x0000004c,0x00000048,0x00000001,0x0003003e,0x0000004b,0x0000004c, + 0x0004003d,0x00000012,0x0000004e,0x00000017,0x0007004f,0x00000007,0x0000004f,0x0000004e, + 0x0000004e,0x00000002,0x00000003,0x0003003e,0x0000004d,0x0000004f,0x0004003d,0x00000014, + 0x00000051,0x00000018,0x0007004f,0x0000000a,0x00000052,0x00000051,0x00000051,0x00000002, + 0x00000003,0x0003003e,0x00000050,0x00000052,0x0004003d,0x00000014,0x00000054,0x00000019, + 0x0007004f,0x0000000a,0x00000055,0x00000054,0x00000054,0x00000002,0x00000003,0x0003003e, + 0x00000053,0x00000055,0x00070039,0x00000002,0x00000056,0x00000010,0x0000004d,0x00000050, + 0x00000053,0x0004003d,0x0000000a,0x00000057,0x00000050,0x00050041,0x00000032,0x00000059, + 0x00000018,0x00000058,0x00050051,0x00000009,0x0000005a,0x00000057,0x00000000,0x0003003e, + 0x00000059,0x0000005a,0x00050041,0x00000032,0x0000005c,0x00000018,0x0000005b,0x00050051, + 0x00000009,0x0000005d,0x00000057,0x00000001,0x0003003e,0x0000005c,0x0000005d,0x000100fd, + 0x00010038,0x00050036,0x00000002,0x0000001f,0x00000000,0x0000001c,0x00030037,0x0000000b, + 0x0000001d,0x00030037,0x00000015,0x0000001e,0x000200f8,0x00000020,0x00050041,0x00000063, + 0x00000064,0x00000060,0x00000062,0x0004003d,0x00000014,0x00000065,0x00000064,0x0009004f, + 0x00000014,0x00000066,0x00000065,0x00000065,0x00000000,0x00000001,0x00000000,0x00000001, + 0x0004003d,0x0000000a,0x0000006a,0x0000001d,0x0009004f,0x00000014,0x0000006b,0x0000006a, + 0x0000006a,0x00000000,0x00000001,0x00000000,0x00000001,0x0008000c,0x00000014,0x0000006c, + 0x00000001,0x00000032,0x00000066,0x00000069,0x0000006b,0x0003003e,0x0000001e,0x0000006c, + 0x000100fd,0x00010038,0x00050036,0x00000014,0x00000029,0x00000000,0x00000024,0x00030037, + 0x0000000b,0x00000025,0x00030037,0x00000015,0x00000026,0x00030037,0x00000023,0x00000027, + 0x00030037,0x00000023,0x00000028,0x000200f8,0x0000002a,0x0004003b,0x00000015,0x0000006d, + 0x00000007,0x0004003b,0x00000015,0x00000089,0x00000007,0x0004003b,0x0000002d,0x00000090, + 0x00000007,0x0004003b,0x00000015,0x0000009c,0x00000007,0x0004003b,0x0000000b,0x000000a2, + 0x00000007,0x0004003b,0x00000013,0x000000ac,0x00000007,0x0004003b,0x00000015,0x000000ad, + 0x00000007,0x0004003b,0x00000015,0x000000af,0x00000007,0x0004003b,0x00000008,0x000000b4, + 0x00000007,0x0004003b,0x0000000b,0x000000b5,0x00000007,0x0004003b,0x0000000b,0x000000b7, + 0x00000007,0x0004003b,0x00000015,0x000000c2,0x00000007,0x0004003b,0x00000015,0x000000d3, + 0x00000007,0x0004003d,0x00000022,0x0000006e,0x00000028,0x0004003d,0x00000014,0x0000006f, + 0x00000026,0x0007004f,0x0000000a,0x00000070,0x0000006f,0x0000006f,0x00000000,0x00000001, + 0x00050057,0x00000014,0x00000071,0x0000006e,0x00000070,0x00050051,0x00000009,0x00000072, + 0x00000071,0x00000003,0x00050041,0x00000032,0x00000073,0x0000006d,0x0000002c,0x0003003e, + 0x00000073,0x00000072,0x0004003d,0x00000022,0x00000074,0x00000028,0x0004003d,0x00000014, + 0x00000075,0x00000026,0x0007004f,0x0000000a,0x00000076,0x00000075,0x00000075,0x00000002, + 0x00000003,0x00050057,0x00000014,0x00000077,0x00000074,0x00000076,0x00050051,0x00000009, + 0x00000078,0x00000077,0x00000001,0x00050041,0x00000032,0x00000079,0x0000006d,0x00000036, + 0x0003003e,0x00000079,0x00000078,0x0004003d,0x00000022,0x0000007a,0x00000028,0x0004003d, + 0x0000000a,0x0000007b,0x00000025,0x00050057,0x00000014,0x0000007c,0x0000007a,0x0000007b, + 0x0007004f,0x0000000a,0x0000007d,0x0000007c,0x0000007c,0x00000000,0x00000002,0x00050041, + 0x00000032,0x0000007e,0x0000006d,0x0000005b,0x00050051,0x00000009,0x0000007f,0x0000007d, + 0x00000000,0x0003003e,0x0000007e,0x0000007f,0x00050041,0x00000032,0x00000080,0x0000006d, + 0x00000058,0x00050051,0x00000009,0x00000081,0x0000007d,0x00000001,0x0003003e,0x00000080, + 0x00000081,0x0004003d,0x00000014,0x00000082,0x0000006d,0x00050094,0x00000009,0x00000084, + 0x00000082,0x00000083,0x000500b8,0x00000006,0x00000086,0x00000084,0x00000085,0x000300f7, + 0x00000088,0x00000000,0x000400fa,0x00000086,0x00000087,0x0000008f,0x000200f8,0x00000087, + 0x0004003d,0x00000022,0x0000008a,0x00000027,0x0004003d,0x0000000a,0x0000008b,0x00000025, + 0x00070058,0x00000014,0x0000008c,0x0000008a,0x0000008b,0x00000002,0x00000068,0x0003003e, + 0x00000089,0x0000008c,0x0004003d,0x00000014,0x0000008d,0x00000089,0x000200fe,0x0000008d, + 0x000200f8,0x0000008f,0x00050041,0x00000032,0x00000091,0x0000006d,0x0000002c,0x0004003d, + 0x00000009,0x00000092,0x00000091,0x00050041,0x00000032,0x00000093,0x0000006d,0x00000058, + 0x0004003d,0x00000009,0x00000094,0x00000093,0x0007000c,0x00000009,0x00000095,0x00000001, + 0x00000028,0x00000092,0x00000094,0x00050041,0x00000032,0x00000096,0x0000006d,0x00000036, + 0x0004003d,0x00000009,0x00000097,0x00000096,0x00050041,0x00000032,0x00000098,0x0000006d, + 0x0000005b,0x0004003d,0x00000009,0x00000099,0x00000098,0x0007000c,0x00000009,0x0000009a, + 0x00000001,0x00000028,0x00000097,0x00000099,0x000500ba,0x00000006,0x0000009b,0x00000095, + 0x0000009a,0x0003003e,0x00000090,0x0000009b,0x00050041,0x00000032,0x0000009d,0x0000006d, + 0x00000036,0x0004003d,0x00000009,0x0000009e,0x0000009d,0x00050041,0x00000032,0x0000009f, + 0x0000006d,0x0000005b,0x0004003d,0x00000009,0x000000a0,0x0000009f,0x00070050,0x00000014, + 0x000000a1,0x00000068,0x0000009e,0x00000068,0x000000a0,0x0003003e,0x0000009c,0x000000a1, + 0x0004003d,0x00000014,0x000000a3,0x0000006d,0x0007004f,0x0000000a,0x000000a4,0x000000a3, + 0x000000a3,0x00000001,0x00000003,0x0003003e,0x000000a2,0x000000a4,0x0004003d,0x00000006, + 0x000000a5,0x00000090,0x00070050,0x00000012,0x000000a6,0x000000a5,0x000000a5,0x000000a5, + 0x000000a5,0x00050041,0x00000032,0x000000a7,0x0000006d,0x0000002c,0x0004003d,0x00000009, + 0x000000a8,0x000000a7,0x00050041,0x00000032,0x000000a9,0x0000006d,0x00000058,0x0004003d, + 0x00000009,0x000000aa,0x000000a9,0x00070050,0x00000014,0x000000ab,0x000000a8,0x00000068, + 0x000000aa,0x00000068,0x0003003e,0x000000ac,0x000000a6,0x0004003d,0x00000014,0x000000ae, + 0x0000009c,0x0003003e,0x000000ad,0x000000ae,0x0003003e,0x000000af,0x000000ab,0x00070039, + 0x00000002,0x000000b0,0x0000001a,0x000000ac,0x000000ad,0x000000af,0x0004003d,0x00000014, + 0x000000b1,0x000000ad,0x0003003e,0x0000009c,0x000000b1,0x0004003d,0x00000006,0x000000b2, + 0x00000090,0x00050050,0x00000007,0x000000b3,0x000000b2,0x000000b2,0x0003003e,0x000000b4, + 0x000000b3,0x0004003d,0x0000000a,0x000000b6,0x000000a2,0x0003003e,0x000000b5,0x000000b6, + 0x0004003d,0x00000014,0x000000b8,0x0000006d,0x0007004f,0x0000000a,0x000000b9,0x000000b8, + 0x000000b8,0x00000000,0x00000002,0x0003003e,0x000000b7,0x000000b9,0x00070039,0x00000002, + 0x000000ba,0x00000010,0x000000b4,0x000000b5,0x000000b7,0x0004003d,0x0000000a,0x000000bb, + 0x000000b5,0x0003003e,0x000000a2,0x000000bb,0x0004003d,0x0000000a,0x000000bc,0x000000a2, + 0x00050094,0x00000009,0x000000be,0x000000bc,0x000000bd,0x0004003d,0x0000000a,0x000000bf, + 0x000000a2,0x00050050,0x0000000a,0x000000c0,0x000000be,0x000000be,0x00050088,0x0000000a, + 0x000000c1,0x000000bf,0x000000c0,0x0003003e,0x000000a2,0x000000c1,0x0004003d,0x00000014, + 0x000000c3,0x0000009c,0x00050041,0x00000063,0x000000c4,0x00000060,0x00000062,0x0004003d, + 0x00000014,0x000000c5,0x000000c4,0x0007004f,0x0000000a,0x000000c6,0x000000c5,0x000000c5, + 0x00000000,0x00000001,0x00050041,0x00000063,0x000000c7,0x00000060,0x00000062,0x0004003d, + 0x00000014,0x000000c8,0x000000c7,0x0007004f,0x0000000a,0x000000c9,0x000000c8,0x000000c8, + 0x00000000,0x00000001,0x0004007f,0x0000000a,0x000000ca,0x000000c9,0x00050051,0x00000009, + 0x000000cb,0x000000c6,0x00000000,0x00050051,0x00000009,0x000000cc,0x000000c6,0x00000001, + 0x00050051,0x00000009,0x000000cd,0x000000ca,0x00000000,0x00050051,0x00000009,0x000000ce, + 0x000000ca,0x00000001,0x00070050,0x00000014,0x000000cf,0x000000cb,0x000000cc,0x000000cd, + 0x000000ce,0x0004003d,0x0000000a,0x000000d0,0x00000025,0x0009004f,0x00000014,0x000000d1, + 0x000000d0,0x000000d0,0x00000000,0x00000001,0x00000000,0x00000001,0x0008000c,0x00000014, + 0x000000d2,0x00000001,0x00000032,0x000000c3,0x000000cf,0x000000d1,0x0003003e,0x000000c2, + 0x000000d2,0x00050041,0x00000032,0x000000d4,0x000000a2,0x0000002c,0x0004003d,0x00000009, + 0x000000d5,0x000000d4,0x0004003d,0x00000022,0x000000d6,0x00000027,0x0004003d,0x00000014, + 0x000000d7,0x000000c2,0x0007004f,0x0000000a,0x000000d8,0x000000d7,0x000000d7,0x00000000, + 0x00000001,0x00070058,0x00000014,0x000000d9,0x000000d6,0x000000d8,0x00000002,0x00000068, + 0x0005008e,0x00000014,0x000000da,0x000000d9,0x000000d5,0x0003003e,0x000000d3,0x000000da, + 0x00050041,0x00000032,0x000000db,0x000000a2,0x00000036,0x0004003d,0x00000009,0x000000dc, + 0x000000db,0x0004003d,0x00000022,0x000000dd,0x00000027,0x0004003d,0x00000014,0x000000de, + 0x000000c2,0x0007004f,0x0000000a,0x000000df,0x000000de,0x000000de,0x00000002,0x00000003, + 0x00070058,0x00000014,0x000000e0,0x000000dd,0x000000df,0x00000002,0x00000068,0x0005008e, + 0x00000014,0x000000e1,0x000000e0,0x000000dc,0x0004003d,0x00000014,0x000000e2,0x000000d3, + 0x00050081,0x00000014,0x000000e3,0x000000e2,0x000000e1,0x0003003e,0x000000d3,0x000000e3, + 0x0004003d,0x00000014,0x000000e4,0x000000d3,0x000200fe,0x000000e4,0x000200f8,0x00000088, + 0x000100ff,0x00010038 }; diff --git a/app/src/main/cpp/shaders/smaa_edge.frag b/app/src/main/cpp/shaders/smaa_edge.frag index 44073b00c4..b4e40a9dad 100644 --- a/app/src/main/cpp/shaders/smaa_edge.frag +++ b/app/src/main/cpp/shaders/smaa_edge.frag @@ -1,29 +1,21 @@ #version 450 +#extension GL_GOOGLE_include_directive : require layout(location = 0) in vec2 fragTexCoord; layout(location = 0) out vec4 outColor; layout(set = 0, binding = 0) uniform sampler2D InputTexture; layout(push_constant) uniform Constants { vec4 ndc; - vec2 resolution; - float extra; - float pad; + vec4 metrics; // 1/width, 1/height, width, height } pc; -float luma(vec3 c) { - return dot(c, vec3(0.2126, 0.7152, 0.0722)); -} +#define SMAA_RT_METRICS pc.metrics +#define SMAA_GLSL_4 +#define SMAA_PRESET_HIGH +#include "SMAA.hlsl" void main() { - vec2 px = 1.0 / max(pc.resolution, vec2(1.0)); - vec2 uv = clamp(fragTexCoord, px * 0.5, vec2(1.0) - px * 0.5); - float center = luma(texture(InputTexture, uv).rgb); - float left = luma(texture(InputTexture, uv - vec2(px.x, 0.0)).rgb); - float right = luma(texture(InputTexture, uv + vec2(px.x, 0.0)).rgb); - float up = luma(texture(InputTexture, uv - vec2(0.0, px.y)).rgb); - float down = luma(texture(InputTexture, uv + vec2(0.0, px.y)).rgb); - - // Store directional edge strengths for the weight pass. - outColor = vec4(abs(center - left), abs(center - right), - abs(center - up), abs(center - down)); + vec4 offset[3]; + SMAAEdgeDetectionVS(fragTexCoord, offset); + outColor = vec4(SMAALumaEdgeDetectionPS(fragTexCoord, offset, InputTexture), 0.0, 0.0); } diff --git a/app/src/main/cpp/shaders/smaa_edge_frag.h b/app/src/main/cpp/shaders/smaa_edge_frag.h index 7d133264c9..300a5ca064 100644 --- a/app/src/main/cpp/shaders/smaa_edge_frag.h +++ b/app/src/main/cpp/shaders/smaa_edge_frag.h @@ -1,102 +1,185 @@ - // 1116.3.0 + // 1116.6.0 #pragma once const uint32_t smaa_edge_code[] = { - 0x07230203,0x00010000,0x0008000b,0x00000080,0x00000000,0x00020011,0x00000001,0x0006000b, + 0x07230203,0x00010000,0x0008000b,0x000000eb,0x00000000,0x00020011,0x00000001,0x0006000b, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, - 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000028,0x0000006e,0x00030010, - 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, - 0x00000000,0x00050005,0x0000000b,0x616d756c,0x33667628,0x0000003b,0x00030005,0x0000000a, - 0x00000063,0x00030005,0x00000017,0x00007870,0x00050005,0x0000001a,0x736e6f43,0x746e6174, - 0x00000073,0x00040006,0x0000001a,0x00000000,0x0063646e,0x00060006,0x0000001a,0x00000001, - 0x6f736572,0x6974756c,0x00006e6f,0x00050006,0x0000001a,0x00000002,0x72747865,0x00000061, - 0x00040006,0x0000001a,0x00000003,0x00646170,0x00030005,0x0000001c,0x00006370,0x00030005, - 0x00000026,0x00007675,0x00060005,0x00000028,0x67617266,0x43786554,0x64726f6f,0x00000000, - 0x00040005,0x00000032,0x746e6563,0x00007265,0x00060005,0x00000036,0x75706e49,0x78655474, - 0x65727574,0x00000000,0x00040005,0x0000003a,0x61726170,0x0000006d,0x00040005,0x0000003d, - 0x7466656c,0x00000000,0x00040005,0x00000048,0x61726170,0x0000006d,0x00040005,0x0000004b, - 0x68676972,0x00000074,0x00040005,0x00000053,0x61726170,0x0000006d,0x00030005,0x00000056, - 0x00007075,0x00040005,0x0000005f,0x61726170,0x0000006d,0x00040005,0x00000062,0x6e776f64, - 0x00000000,0x00040005,0x0000006a,0x61726170,0x0000006d,0x00050005,0x0000006e,0x4374756f, - 0x726f6c6f,0x00000000,0x00030047,0x0000001a,0x00000002,0x00050048,0x0000001a,0x00000000, - 0x00000023,0x00000000,0x00050048,0x0000001a,0x00000001,0x00000023,0x00000010,0x00050048, - 0x0000001a,0x00000002,0x00000023,0x00000018,0x00050048,0x0000001a,0x00000003,0x00000023, - 0x0000001c,0x00040047,0x00000028,0x0000001e,0x00000000,0x00040047,0x00000036,0x00000021, - 0x00000000,0x00040047,0x00000036,0x00000022,0x00000000,0x00040047,0x0000006e,0x0000001e, - 0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006, - 0x00000020,0x00040017,0x00000007,0x00000006,0x00000003,0x00040020,0x00000008,0x00000007, - 0x00000007,0x00040021,0x00000009,0x00000006,0x00000008,0x0004002b,0x00000006,0x0000000e, - 0x3e59b3d0,0x0004002b,0x00000006,0x0000000f,0x3f371759,0x0004002b,0x00000006,0x00000010, - 0x3d93dd98,0x0006002c,0x00000007,0x00000011,0x0000000e,0x0000000f,0x00000010,0x00040017, - 0x00000015,0x00000006,0x00000002,0x00040020,0x00000016,0x00000007,0x00000015,0x0004002b, - 0x00000006,0x00000018,0x3f800000,0x00040017,0x00000019,0x00000006,0x00000004,0x0006001e, - 0x0000001a,0x00000019,0x00000015,0x00000006,0x00000006,0x00040020,0x0000001b,0x00000009, - 0x0000001a,0x0004003b,0x0000001b,0x0000001c,0x00000009,0x00040015,0x0000001d,0x00000020, - 0x00000001,0x0004002b,0x0000001d,0x0000001e,0x00000001,0x00040020,0x0000001f,0x00000009, - 0x00000015,0x0005002c,0x00000015,0x00000022,0x00000018,0x00000018,0x00040020,0x00000027, - 0x00000001,0x00000015,0x0004003b,0x00000027,0x00000028,0x00000001,0x0004002b,0x00000006, - 0x0000002b,0x3f000000,0x00040020,0x00000031,0x00000007,0x00000006,0x00090019,0x00000033, - 0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,0x00000001,0x00000000,0x0003001b, - 0x00000034,0x00000033,0x00040020,0x00000035,0x00000000,0x00000034,0x0004003b,0x00000035, - 0x00000036,0x00000000,0x00040015,0x00000040,0x00000020,0x00000000,0x0004002b,0x00000040, - 0x00000041,0x00000000,0x0004002b,0x00000006,0x00000044,0x00000000,0x0004002b,0x00000040, - 0x00000059,0x00000001,0x00040020,0x0000006d,0x00000003,0x00000019,0x0004003b,0x0000006d, - 0x0000006e,0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8, - 0x00000005,0x0004003b,0x00000016,0x00000017,0x00000007,0x0004003b,0x00000016,0x00000026, - 0x00000007,0x0004003b,0x00000031,0x00000032,0x00000007,0x0004003b,0x00000008,0x0000003a, - 0x00000007,0x0004003b,0x00000031,0x0000003d,0x00000007,0x0004003b,0x00000008,0x00000048, - 0x00000007,0x0004003b,0x00000031,0x0000004b,0x00000007,0x0004003b,0x00000008,0x00000053, - 0x00000007,0x0004003b,0x00000031,0x00000056,0x00000007,0x0004003b,0x00000008,0x0000005f, - 0x00000007,0x0004003b,0x00000031,0x00000062,0x00000007,0x0004003b,0x00000008,0x0000006a, - 0x00000007,0x00050041,0x0000001f,0x00000020,0x0000001c,0x0000001e,0x0004003d,0x00000015, - 0x00000021,0x00000020,0x0007000c,0x00000015,0x00000023,0x00000001,0x00000028,0x00000021, - 0x00000022,0x00050050,0x00000015,0x00000024,0x00000018,0x00000018,0x00050088,0x00000015, - 0x00000025,0x00000024,0x00000023,0x0003003e,0x00000017,0x00000025,0x0004003d,0x00000015, - 0x00000029,0x00000028,0x0004003d,0x00000015,0x0000002a,0x00000017,0x0005008e,0x00000015, - 0x0000002c,0x0000002a,0x0000002b,0x0004003d,0x00000015,0x0000002d,0x00000017,0x0005008e, - 0x00000015,0x0000002e,0x0000002d,0x0000002b,0x00050083,0x00000015,0x0000002f,0x00000022, - 0x0000002e,0x0008000c,0x00000015,0x00000030,0x00000001,0x0000002b,0x00000029,0x0000002c, - 0x0000002f,0x0003003e,0x00000026,0x00000030,0x0004003d,0x00000034,0x00000037,0x00000036, - 0x0004003d,0x00000015,0x00000038,0x00000026,0x00050057,0x00000019,0x00000039,0x00000037, - 0x00000038,0x0008004f,0x00000007,0x0000003b,0x00000039,0x00000039,0x00000000,0x00000001, - 0x00000002,0x0003003e,0x0000003a,0x0000003b,0x00050039,0x00000006,0x0000003c,0x0000000b, - 0x0000003a,0x0003003e,0x00000032,0x0000003c,0x0004003d,0x00000034,0x0000003e,0x00000036, - 0x0004003d,0x00000015,0x0000003f,0x00000026,0x00050041,0x00000031,0x00000042,0x00000017, - 0x00000041,0x0004003d,0x00000006,0x00000043,0x00000042,0x00050050,0x00000015,0x00000045, - 0x00000043,0x00000044,0x00050083,0x00000015,0x00000046,0x0000003f,0x00000045,0x00050057, - 0x00000019,0x00000047,0x0000003e,0x00000046,0x0008004f,0x00000007,0x00000049,0x00000047, - 0x00000047,0x00000000,0x00000001,0x00000002,0x0003003e,0x00000048,0x00000049,0x00050039, - 0x00000006,0x0000004a,0x0000000b,0x00000048,0x0003003e,0x0000003d,0x0000004a,0x0004003d, - 0x00000034,0x0000004c,0x00000036,0x0004003d,0x00000015,0x0000004d,0x00000026,0x00050041, - 0x00000031,0x0000004e,0x00000017,0x00000041,0x0004003d,0x00000006,0x0000004f,0x0000004e, - 0x00050050,0x00000015,0x00000050,0x0000004f,0x00000044,0x00050081,0x00000015,0x00000051, - 0x0000004d,0x00000050,0x00050057,0x00000019,0x00000052,0x0000004c,0x00000051,0x0008004f, - 0x00000007,0x00000054,0x00000052,0x00000052,0x00000000,0x00000001,0x00000002,0x0003003e, - 0x00000053,0x00000054,0x00050039,0x00000006,0x00000055,0x0000000b,0x00000053,0x0003003e, - 0x0000004b,0x00000055,0x0004003d,0x00000034,0x00000057,0x00000036,0x0004003d,0x00000015, - 0x00000058,0x00000026,0x00050041,0x00000031,0x0000005a,0x00000017,0x00000059,0x0004003d, - 0x00000006,0x0000005b,0x0000005a,0x00050050,0x00000015,0x0000005c,0x00000044,0x0000005b, - 0x00050083,0x00000015,0x0000005d,0x00000058,0x0000005c,0x00050057,0x00000019,0x0000005e, - 0x00000057,0x0000005d,0x0008004f,0x00000007,0x00000060,0x0000005e,0x0000005e,0x00000000, - 0x00000001,0x00000002,0x0003003e,0x0000005f,0x00000060,0x00050039,0x00000006,0x00000061, - 0x0000000b,0x0000005f,0x0003003e,0x00000056,0x00000061,0x0004003d,0x00000034,0x00000063, - 0x00000036,0x0004003d,0x00000015,0x00000064,0x00000026,0x00050041,0x00000031,0x00000065, - 0x00000017,0x00000059,0x0004003d,0x00000006,0x00000066,0x00000065,0x00050050,0x00000015, - 0x00000067,0x00000044,0x00000066,0x00050081,0x00000015,0x00000068,0x00000064,0x00000067, - 0x00050057,0x00000019,0x00000069,0x00000063,0x00000068,0x0008004f,0x00000007,0x0000006b, - 0x00000069,0x00000069,0x00000000,0x00000001,0x00000002,0x0003003e,0x0000006a,0x0000006b, - 0x00050039,0x00000006,0x0000006c,0x0000000b,0x0000006a,0x0003003e,0x00000062,0x0000006c, - 0x0004003d,0x00000006,0x0000006f,0x00000032,0x0004003d,0x00000006,0x00000070,0x0000003d, - 0x00050083,0x00000006,0x00000071,0x0000006f,0x00000070,0x0006000c,0x00000006,0x00000072, - 0x00000001,0x00000004,0x00000071,0x0004003d,0x00000006,0x00000073,0x00000032,0x0004003d, - 0x00000006,0x00000074,0x0000004b,0x00050083,0x00000006,0x00000075,0x00000073,0x00000074, - 0x0006000c,0x00000006,0x00000076,0x00000001,0x00000004,0x00000075,0x0004003d,0x00000006, - 0x00000077,0x00000032,0x0004003d,0x00000006,0x00000078,0x00000056,0x00050083,0x00000006, - 0x00000079,0x00000077,0x00000078,0x0006000c,0x00000006,0x0000007a,0x00000001,0x00000004, - 0x00000079,0x0004003d,0x00000006,0x0000007b,0x00000032,0x0004003d,0x00000006,0x0000007c, - 0x00000062,0x00050083,0x00000006,0x0000007d,0x0000007b,0x0000007c,0x0006000c,0x00000006, - 0x0000007e,0x00000001,0x00000004,0x0000007d,0x00070050,0x00000019,0x0000007f,0x00000072, - 0x00000076,0x0000007a,0x0000007e,0x0003003e,0x0000006e,0x0000007f,0x000100fd,0x00010038, - 0x00050036,0x00000006,0x0000000b,0x00000000,0x00000009,0x00030037,0x00000008,0x0000000a, - 0x000200f8,0x0000000c,0x0004003d,0x00000007,0x0000000d,0x0000000a,0x00050094,0x00000006, - 0x00000012,0x0000000d,0x00000011,0x000200fe,0x00000012,0x00010038 + 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x000000d9,0x000000e1,0x00030010, + 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x000a0004,0x475f4c47,0x4c474f4f, + 0x70635f45,0x74735f70,0x5f656c79,0x656e696c,0x7269645f,0x69746365,0x00006576,0x00080004, + 0x475f4c47,0x4c474f4f,0x6e695f45,0x64756c63,0x69645f65,0x74636572,0x00657669,0x00040005, + 0x00000004,0x6e69616d,0x00000000,0x000a0005,0x00000011,0x41414d53,0x65676445,0x65746544, + 0x6f697463,0x2853566e,0x3b326676,0x5b346676,0x003b5d33,0x00050005,0x0000000f,0x63786574, + 0x64726f6f,0x00000000,0x00040005,0x00000010,0x7366666f,0x00007465,0x000c0005,0x0000001a, + 0x41414d53,0x616d754c,0x65676445,0x65746544,0x6f697463,0x2853506e,0x3b326676,0x5b346676, + 0x733b5d33,0x003b3132,0x00050005,0x00000017,0x63786574,0x64726f6f,0x00000000,0x00040005, + 0x00000018,0x7366666f,0x00007465,0x00050005,0x00000019,0x6f6c6f63,0x78655472,0x00000000, + 0x00050005,0x0000001e,0x736e6f43,0x746e6174,0x00000073,0x00040006,0x0000001e,0x00000000, + 0x0063646e,0x00050006,0x0000001e,0x00000001,0x7274656d,0x00736369,0x00030005,0x00000020, + 0x00006370,0x00050005,0x00000041,0x65726874,0x6c6f6873,0x00000064,0x00040005,0x00000046, + 0x67696577,0x00737468,0x00030005,0x0000004c,0x0000004c,0x00040005,0x00000053,0x66656c4c, + 0x00000074,0x00040005,0x0000005c,0x706f744c,0x00000000,0x00040005,0x00000065,0x746c6564, + 0x00000061,0x00040005,0x00000073,0x65676465,0x00000073,0x00040005,0x00000080,0x6769724c, + 0x00007468,0x00040005,0x00000089,0x746f624c,0x006d6f74,0x00050005,0x0000009e,0x4478616d, + 0x61746c65,0x00000000,0x00050005,0x000000a4,0x66656c4c,0x66656c74,0x00000074,0x00040005, + 0x000000ad,0x706f744c,0x00706f74,0x00050005,0x000000c6,0x616e6966,0x6c65446c,0x00006174, + 0x00060005,0x000000d9,0x67617266,0x43786554,0x64726f6f,0x00000000,0x00040005,0x000000da, + 0x7366666f,0x00007465,0x00040005,0x000000db,0x61726170,0x0000006d,0x00040005,0x000000dd, + 0x61726170,0x0000006d,0x00050005,0x000000e1,0x4374756f,0x726f6c6f,0x00000000,0x00060005, + 0x000000e2,0x75706e49,0x78655474,0x65727574,0x00000000,0x00040005,0x000000e3,0x61726170, + 0x0000006d,0x00040005,0x000000e5,0x61726170,0x0000006d,0x00030047,0x0000001e,0x00000002, + 0x00050048,0x0000001e,0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,0x00000001, + 0x00000023,0x00000010,0x00040047,0x000000d9,0x0000001e,0x00000000,0x00040047,0x000000e1, + 0x0000001e,0x00000000,0x00040047,0x000000e2,0x00000021,0x00000000,0x00040047,0x000000e2, + 0x00000022,0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016, + 0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000002,0x00040020,0x00000008, + 0x00000007,0x00000007,0x00040017,0x00000009,0x00000006,0x00000004,0x00040015,0x0000000a, + 0x00000020,0x00000000,0x0004002b,0x0000000a,0x0000000b,0x00000003,0x0004001c,0x0000000c, + 0x00000009,0x0000000b,0x00040020,0x0000000d,0x00000007,0x0000000c,0x00050021,0x0000000e, + 0x00000002,0x00000008,0x0000000d,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000, + 0x00000000,0x00000000,0x00000001,0x00000000,0x0003001b,0x00000014,0x00000013,0x00040020, + 0x00000015,0x00000000,0x00000014,0x00060021,0x00000016,0x00000007,0x00000008,0x0000000d, + 0x00000015,0x00040015,0x0000001c,0x00000020,0x00000001,0x0004002b,0x0000001c,0x0000001d, + 0x00000000,0x0004001e,0x0000001e,0x00000009,0x00000009,0x00040020,0x0000001f,0x00000009, + 0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,0x0004002b,0x0000001c,0x00000021, + 0x00000001,0x00040020,0x00000022,0x00000009,0x00000009,0x0004002b,0x00000006,0x00000026, + 0xbf800000,0x0004002b,0x00000006,0x00000027,0x00000000,0x0007002c,0x00000009,0x00000028, + 0x00000026,0x00000027,0x00000027,0x00000026,0x00040020,0x0000002c,0x00000007,0x00000009, + 0x0004002b,0x00000006,0x00000031,0x3f800000,0x0007002c,0x00000009,0x00000032,0x00000031, + 0x00000027,0x00000027,0x00000031,0x0004002b,0x0000001c,0x00000037,0x00000002,0x0004002b, + 0x00000006,0x0000003b,0xc0000000,0x0007002c,0x00000009,0x0000003c,0x0000003b,0x00000027, + 0x00000027,0x0000003b,0x0004002b,0x00000006,0x00000042,0x3dcccccd,0x0005002c,0x00000007, + 0x00000043,0x00000042,0x00000042,0x00040017,0x00000044,0x00000006,0x00000003,0x00040020, + 0x00000045,0x00000007,0x00000044,0x0004002b,0x00000006,0x00000047,0x3e59b3d0,0x0004002b, + 0x00000006,0x00000048,0x3f371759,0x0004002b,0x00000006,0x00000049,0x3d93dd98,0x0006002c, + 0x00000044,0x0000004a,0x00000047,0x00000048,0x00000049,0x00040020,0x0000004b,0x00000007, + 0x00000006,0x0004002b,0x0000000a,0x0000006d,0x00000000,0x0004002b,0x0000000a,0x00000070, + 0x00000001,0x0005002c,0x00000007,0x00000079,0x00000031,0x00000031,0x00020014,0x0000007b, + 0x0004002b,0x0000000a,0x00000099,0x00000002,0x0004002b,0x00000006,0x000000cd,0x40000000, + 0x00040020,0x000000d8,0x00000001,0x00000007,0x0004003b,0x000000d8,0x000000d9,0x00000001, + 0x00040020,0x000000e0,0x00000003,0x00000009,0x0004003b,0x000000e0,0x000000e1,0x00000003, + 0x0004003b,0x00000015,0x000000e2,0x00000000,0x00050036,0x00000002,0x00000004,0x00000000, + 0x00000003,0x000200f8,0x00000005,0x0004003b,0x0000000d,0x000000da,0x00000007,0x0004003b, + 0x00000008,0x000000db,0x00000007,0x0004003b,0x0000000d,0x000000dd,0x00000007,0x0004003b, + 0x00000008,0x000000e3,0x00000007,0x0004003b,0x0000000d,0x000000e5,0x00000007,0x0004003d, + 0x00000007,0x000000dc,0x000000d9,0x0003003e,0x000000db,0x000000dc,0x00060039,0x00000002, + 0x000000de,0x00000011,0x000000db,0x000000dd,0x0004003d,0x0000000c,0x000000df,0x000000dd, + 0x0003003e,0x000000da,0x000000df,0x0004003d,0x00000007,0x000000e4,0x000000d9,0x0003003e, + 0x000000e3,0x000000e4,0x0004003d,0x0000000c,0x000000e6,0x000000da,0x0003003e,0x000000e5, + 0x000000e6,0x00070039,0x00000007,0x000000e7,0x0000001a,0x000000e3,0x000000e5,0x000000e2, + 0x00050051,0x00000006,0x000000e8,0x000000e7,0x00000000,0x00050051,0x00000006,0x000000e9, + 0x000000e7,0x00000001,0x00070050,0x00000009,0x000000ea,0x000000e8,0x000000e9,0x00000027, + 0x00000027,0x0003003e,0x000000e1,0x000000ea,0x000100fd,0x00010038,0x00050036,0x00000002, + 0x00000011,0x00000000,0x0000000e,0x00030037,0x00000008,0x0000000f,0x00030037,0x0000000d, + 0x00000010,0x000200f8,0x00000012,0x00050041,0x00000022,0x00000023,0x00000020,0x00000021, + 0x0004003d,0x00000009,0x00000024,0x00000023,0x0009004f,0x00000009,0x00000025,0x00000024, + 0x00000024,0x00000000,0x00000001,0x00000000,0x00000001,0x0004003d,0x00000007,0x00000029, + 0x0000000f,0x0009004f,0x00000009,0x0000002a,0x00000029,0x00000029,0x00000000,0x00000001, + 0x00000000,0x00000001,0x0008000c,0x00000009,0x0000002b,0x00000001,0x00000032,0x00000025, + 0x00000028,0x0000002a,0x00050041,0x0000002c,0x0000002d,0x00000010,0x0000001d,0x0003003e, + 0x0000002d,0x0000002b,0x00050041,0x00000022,0x0000002e,0x00000020,0x00000021,0x0004003d, + 0x00000009,0x0000002f,0x0000002e,0x0009004f,0x00000009,0x00000030,0x0000002f,0x0000002f, + 0x00000000,0x00000001,0x00000000,0x00000001,0x0004003d,0x00000007,0x00000033,0x0000000f, + 0x0009004f,0x00000009,0x00000034,0x00000033,0x00000033,0x00000000,0x00000001,0x00000000, + 0x00000001,0x0008000c,0x00000009,0x00000035,0x00000001,0x00000032,0x00000030,0x00000032, + 0x00000034,0x00050041,0x0000002c,0x00000036,0x00000010,0x00000021,0x0003003e,0x00000036, + 0x00000035,0x00050041,0x00000022,0x00000038,0x00000020,0x00000021,0x0004003d,0x00000009, + 0x00000039,0x00000038,0x0009004f,0x00000009,0x0000003a,0x00000039,0x00000039,0x00000000, + 0x00000001,0x00000000,0x00000001,0x0004003d,0x00000007,0x0000003d,0x0000000f,0x0009004f, + 0x00000009,0x0000003e,0x0000003d,0x0000003d,0x00000000,0x00000001,0x00000000,0x00000001, + 0x0008000c,0x00000009,0x0000003f,0x00000001,0x00000032,0x0000003a,0x0000003c,0x0000003e, + 0x00050041,0x0000002c,0x00000040,0x00000010,0x00000037,0x0003003e,0x00000040,0x0000003f, + 0x000100fd,0x00010038,0x00050036,0x00000007,0x0000001a,0x00000000,0x00000016,0x00030037, + 0x00000008,0x00000017,0x00030037,0x0000000d,0x00000018,0x00030037,0x00000015,0x00000019, + 0x000200f8,0x0000001b,0x0004003b,0x00000008,0x00000041,0x00000007,0x0004003b,0x00000045, + 0x00000046,0x00000007,0x0004003b,0x0000004b,0x0000004c,0x00000007,0x0004003b,0x0000004b, + 0x00000053,0x00000007,0x0004003b,0x0000004b,0x0000005c,0x00000007,0x0004003b,0x0000002c, + 0x00000065,0x00000007,0x0004003b,0x00000008,0x00000073,0x00000007,0x0004003b,0x0000004b, + 0x00000080,0x00000007,0x0004003b,0x0000004b,0x00000089,0x00000007,0x0004003b,0x00000008, + 0x0000009e,0x00000007,0x0004003b,0x0000004b,0x000000a4,0x00000007,0x0004003b,0x0000004b, + 0x000000ad,0x00000007,0x0004003b,0x0000004b,0x000000c6,0x00000007,0x0003003e,0x00000041, + 0x00000043,0x0003003e,0x00000046,0x0000004a,0x0004003d,0x00000014,0x0000004d,0x00000019, + 0x0004003d,0x00000007,0x0000004e,0x00000017,0x00050057,0x00000009,0x0000004f,0x0000004d, + 0x0000004e,0x0008004f,0x00000044,0x00000050,0x0000004f,0x0000004f,0x00000000,0x00000001, + 0x00000002,0x0004003d,0x00000044,0x00000051,0x00000046,0x00050094,0x00000006,0x00000052, + 0x00000050,0x00000051,0x0003003e,0x0000004c,0x00000052,0x0004003d,0x00000014,0x00000054, + 0x00000019,0x00050041,0x0000002c,0x00000055,0x00000018,0x0000001d,0x0004003d,0x00000009, + 0x00000056,0x00000055,0x0007004f,0x00000007,0x00000057,0x00000056,0x00000056,0x00000000, + 0x00000001,0x00050057,0x00000009,0x00000058,0x00000054,0x00000057,0x0008004f,0x00000044, + 0x00000059,0x00000058,0x00000058,0x00000000,0x00000001,0x00000002,0x0004003d,0x00000044, + 0x0000005a,0x00000046,0x00050094,0x00000006,0x0000005b,0x00000059,0x0000005a,0x0003003e, + 0x00000053,0x0000005b,0x0004003d,0x00000014,0x0000005d,0x00000019,0x00050041,0x0000002c, + 0x0000005e,0x00000018,0x0000001d,0x0004003d,0x00000009,0x0000005f,0x0000005e,0x0007004f, + 0x00000007,0x00000060,0x0000005f,0x0000005f,0x00000002,0x00000003,0x00050057,0x00000009, + 0x00000061,0x0000005d,0x00000060,0x0008004f,0x00000044,0x00000062,0x00000061,0x00000061, + 0x00000000,0x00000001,0x00000002,0x0004003d,0x00000044,0x00000063,0x00000046,0x00050094, + 0x00000006,0x00000064,0x00000062,0x00000063,0x0003003e,0x0000005c,0x00000064,0x0004003d, + 0x00000006,0x00000066,0x0000004c,0x0004003d,0x00000006,0x00000067,0x00000053,0x0004003d, + 0x00000006,0x00000068,0x0000005c,0x00050050,0x00000007,0x00000069,0x00000067,0x00000068, + 0x00050050,0x00000007,0x0000006a,0x00000066,0x00000066,0x00050083,0x00000007,0x0000006b, + 0x0000006a,0x00000069,0x0006000c,0x00000007,0x0000006c,0x00000001,0x00000004,0x0000006b, + 0x00050041,0x0000004b,0x0000006e,0x00000065,0x0000006d,0x00050051,0x00000006,0x0000006f, + 0x0000006c,0x00000000,0x0003003e,0x0000006e,0x0000006f,0x00050041,0x0000004b,0x00000071, + 0x00000065,0x00000070,0x00050051,0x00000006,0x00000072,0x0000006c,0x00000001,0x0003003e, + 0x00000071,0x00000072,0x0004003d,0x00000007,0x00000074,0x00000041,0x0004003d,0x00000009, + 0x00000075,0x00000065,0x0007004f,0x00000007,0x00000076,0x00000075,0x00000075,0x00000000, + 0x00000001,0x0007000c,0x00000007,0x00000077,0x00000001,0x00000030,0x00000074,0x00000076, + 0x0003003e,0x00000073,0x00000077,0x0004003d,0x00000007,0x00000078,0x00000073,0x00050094, + 0x00000006,0x0000007a,0x00000078,0x00000079,0x000500b4,0x0000007b,0x0000007c,0x0000007a, + 0x00000027,0x000300f7,0x0000007e,0x00000000,0x000400fa,0x0000007c,0x0000007d,0x0000007e, + 0x000200f8,0x0000007d,0x000100fc,0x000200f8,0x0000007e,0x0004003d,0x00000014,0x00000081, + 0x00000019,0x00050041,0x0000002c,0x00000082,0x00000018,0x00000021,0x0004003d,0x00000009, + 0x00000083,0x00000082,0x0007004f,0x00000007,0x00000084,0x00000083,0x00000083,0x00000000, + 0x00000001,0x00050057,0x00000009,0x00000085,0x00000081,0x00000084,0x0008004f,0x00000044, + 0x00000086,0x00000085,0x00000085,0x00000000,0x00000001,0x00000002,0x0004003d,0x00000044, + 0x00000087,0x00000046,0x00050094,0x00000006,0x00000088,0x00000086,0x00000087,0x0003003e, + 0x00000080,0x00000088,0x0004003d,0x00000014,0x0000008a,0x00000019,0x00050041,0x0000002c, + 0x0000008b,0x00000018,0x00000021,0x0004003d,0x00000009,0x0000008c,0x0000008b,0x0007004f, + 0x00000007,0x0000008d,0x0000008c,0x0000008c,0x00000002,0x00000003,0x00050057,0x00000009, + 0x0000008e,0x0000008a,0x0000008d,0x0008004f,0x00000044,0x0000008f,0x0000008e,0x0000008e, + 0x00000000,0x00000001,0x00000002,0x0004003d,0x00000044,0x00000090,0x00000046,0x00050094, + 0x00000006,0x00000091,0x0000008f,0x00000090,0x0003003e,0x00000089,0x00000091,0x0004003d, + 0x00000006,0x00000092,0x0000004c,0x0004003d,0x00000006,0x00000093,0x00000080,0x0004003d, + 0x00000006,0x00000094,0x00000089,0x00050050,0x00000007,0x00000095,0x00000093,0x00000094, + 0x00050050,0x00000007,0x00000096,0x00000092,0x00000092,0x00050083,0x00000007,0x00000097, + 0x00000096,0x00000095,0x0006000c,0x00000007,0x00000098,0x00000001,0x00000004,0x00000097, + 0x00050041,0x0000004b,0x0000009a,0x00000065,0x00000099,0x00050051,0x00000006,0x0000009b, + 0x00000098,0x00000000,0x0003003e,0x0000009a,0x0000009b,0x00050041,0x0000004b,0x0000009c, + 0x00000065,0x0000000b,0x00050051,0x00000006,0x0000009d,0x00000098,0x00000001,0x0003003e, + 0x0000009c,0x0000009d,0x0004003d,0x00000009,0x0000009f,0x00000065,0x0007004f,0x00000007, + 0x000000a0,0x0000009f,0x0000009f,0x00000000,0x00000001,0x0004003d,0x00000009,0x000000a1, + 0x00000065,0x0007004f,0x00000007,0x000000a2,0x000000a1,0x000000a1,0x00000002,0x00000003, + 0x0007000c,0x00000007,0x000000a3,0x00000001,0x00000028,0x000000a0,0x000000a2,0x0003003e, + 0x0000009e,0x000000a3,0x0004003d,0x00000014,0x000000a5,0x00000019,0x00050041,0x0000002c, + 0x000000a6,0x00000018,0x00000037,0x0004003d,0x00000009,0x000000a7,0x000000a6,0x0007004f, + 0x00000007,0x000000a8,0x000000a7,0x000000a7,0x00000000,0x00000001,0x00050057,0x00000009, + 0x000000a9,0x000000a5,0x000000a8,0x0008004f,0x00000044,0x000000aa,0x000000a9,0x000000a9, + 0x00000000,0x00000001,0x00000002,0x0004003d,0x00000044,0x000000ab,0x00000046,0x00050094, + 0x00000006,0x000000ac,0x000000aa,0x000000ab,0x0003003e,0x000000a4,0x000000ac,0x0004003d, + 0x00000014,0x000000ae,0x00000019,0x00050041,0x0000002c,0x000000af,0x00000018,0x00000037, + 0x0004003d,0x00000009,0x000000b0,0x000000af,0x0007004f,0x00000007,0x000000b1,0x000000b0, + 0x000000b0,0x00000002,0x00000003,0x00050057,0x00000009,0x000000b2,0x000000ae,0x000000b1, + 0x0008004f,0x00000044,0x000000b3,0x000000b2,0x000000b2,0x00000000,0x00000001,0x00000002, + 0x0004003d,0x00000044,0x000000b4,0x00000046,0x00050094,0x00000006,0x000000b5,0x000000b3, + 0x000000b4,0x0003003e,0x000000ad,0x000000b5,0x0004003d,0x00000006,0x000000b6,0x00000053, + 0x0004003d,0x00000006,0x000000b7,0x0000005c,0x00050050,0x00000007,0x000000b8,0x000000b6, + 0x000000b7,0x0004003d,0x00000006,0x000000b9,0x000000a4,0x0004003d,0x00000006,0x000000ba, + 0x000000ad,0x00050050,0x00000007,0x000000bb,0x000000b9,0x000000ba,0x00050083,0x00000007, + 0x000000bc,0x000000b8,0x000000bb,0x0006000c,0x00000007,0x000000bd,0x00000001,0x00000004, + 0x000000bc,0x00050041,0x0000004b,0x000000be,0x00000065,0x00000099,0x00050051,0x00000006, + 0x000000bf,0x000000bd,0x00000000,0x0003003e,0x000000be,0x000000bf,0x00050041,0x0000004b, + 0x000000c0,0x00000065,0x0000000b,0x00050051,0x00000006,0x000000c1,0x000000bd,0x00000001, + 0x0003003e,0x000000c0,0x000000c1,0x0004003d,0x00000007,0x000000c2,0x0000009e,0x0004003d, + 0x00000009,0x000000c3,0x00000065,0x0007004f,0x00000007,0x000000c4,0x000000c3,0x000000c3, + 0x00000002,0x00000003,0x0007000c,0x00000007,0x000000c5,0x00000001,0x00000028,0x000000c2, + 0x000000c4,0x0003003e,0x0000009e,0x000000c5,0x00050041,0x0000004b,0x000000c7,0x0000009e, + 0x0000006d,0x0004003d,0x00000006,0x000000c8,0x000000c7,0x00050041,0x0000004b,0x000000c9, + 0x0000009e,0x00000070,0x0004003d,0x00000006,0x000000ca,0x000000c9,0x0007000c,0x00000006, + 0x000000cb,0x00000001,0x00000028,0x000000c8,0x000000ca,0x0003003e,0x000000c6,0x000000cb, + 0x0004003d,0x00000006,0x000000cc,0x000000c6,0x0004003d,0x00000009,0x000000ce,0x00000065, + 0x0007004f,0x00000007,0x000000cf,0x000000ce,0x000000ce,0x00000000,0x00000001,0x0005008e, + 0x00000007,0x000000d0,0x000000cf,0x000000cd,0x00050050,0x00000007,0x000000d1,0x000000cc, + 0x000000cc,0x0007000c,0x00000007,0x000000d2,0x00000001,0x00000030,0x000000d1,0x000000d0, + 0x0004003d,0x00000007,0x000000d3,0x00000073,0x00050085,0x00000007,0x000000d4,0x000000d3, + 0x000000d2,0x0003003e,0x00000073,0x000000d4,0x0004003d,0x00000007,0x000000d5,0x00000073, + 0x000200fe,0x000000d5,0x00010038 }; diff --git a/app/src/main/cpp/shaders/smaa_tables.h b/app/src/main/cpp/shaders/smaa_tables.h new file mode 100644 index 0000000000..ebc28d815b --- /dev/null +++ b/app/src/main/cpp/shaders/smaa_tables.h @@ -0,0 +1,1375 @@ +/** + * Copyright (C) 2013 Jorge Jimenez (jorge@iryoku.com) + * Copyright (C) 2013 Jose I. Echevarria (joseignacioechevarria@gmail.com) + * Copyright (C) 2013 Belen Masia (bmasia@unizar.es) + * Copyright (C) 2013 Fernando Navarro (fernandn@microsoft.com) + * Copyright (C) 2013 Diego Gutierrez (diegog@unizar.es) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to + * do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. As clarification, there + * is no requirement that the copyright notice and permission be included in + * binary distributions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* SMAA's lookup tables, from Textures/AreaTex.h and Textures/SearchTex.h of github.com/iryoku/smaa. + * SMAA 1x reads only the first 80 of the area table's 560 rows; the other rows are not included. */ +#pragma once + +#define SMAA_AREA_W 160 +#define SMAA_AREA_H 560 +#define SMAA_AREA_ROWS 80 +#define SMAA_SEARCH_W 64 +#define SMAA_SEARCH_H 16 + +static const unsigned char kSmaaArea[SMAA_AREA_W * SMAA_AREA_ROWS * 2] = { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x40,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x44,0x7b,0x41,0x5d,0x42,0x54,0x41,0x4f,0x42,0x4b,0x42,0x49,0x42,0x48,0x41,0x47,0x42,0x46,0x42,0x45, + 0x42,0x45,0x42,0x44,0x42,0x44,0x42,0x44,0x42,0x43,0x41,0x43,0x42,0x43,0x42,0x43,0x42,0x43,0x42,0x43, + 0x04,0x7f,0x22,0x3d,0x2b,0x3d,0x30,0x3d,0x33,0x3d,0x35,0x3d,0x37,0x3d,0x38,0x3d,0x39,0x3d,0x39,0x3d, + 0x3a,0x3d,0x3a,0x3d,0x3b,0x3d,0x3b,0x3d,0x3b,0x3d,0x3c,0x3d,0x3c,0x3d,0x3c,0x3d,0x3c,0x3d,0x3c,0x3d, + 0x40,0x7f,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3f,0x00,0x0a,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3f,0x00,0x0a,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x62,0x20,0x4d,0x2a,0x48,0x30,0x44,0x33,0x44,0x35,0x44,0x36,0x43,0x37,0x42,0x38,0x43,0x39,0x42,0x39, + 0x42,0x3a,0x42,0x3a,0x42,0x3b,0x42,0x3b,0x42,0x3b,0x41,0x3b,0x42,0x3c,0x42,0x3c,0x42,0x3c,0x42,0x3c, + 0x00,0x5d,0x0c,0x49,0x16,0x43,0x1d,0x41,0x22,0x40,0x26,0x3f,0x29,0x3f,0x2c,0x3f,0x2e,0x3e,0x2f,0x3e, + 0x31,0x3e,0x32,0x3e,0x33,0x3e,0x33,0x3e,0x34,0x3e,0x35,0x3e,0x35,0x3e,0x36,0x3e,0x37,0x3e,0x37,0x3e, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x66,0x00,0x3f,0x00,0x03,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x66,0x00,0x3f,0x00, + 0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x6d,0x0b,0x57,0x16,0x4f,0x1d,0x4a,0x22,0x48,0x26,0x47,0x29,0x46,0x2b,0x44,0x2d,0x44,0x2f,0x44,0x30, + 0x44,0x31,0x44,0x32,0x43,0x33,0x43,0x34,0x43,0x34,0x42,0x35,0x43,0x36,0x42,0x36,0x42,0x37,0x42,0x37, + 0x00,0x68,0x06,0x54,0x0d,0x4b,0x14,0x47,0x19,0x44,0x1d,0x43,0x20,0x41,0x23,0x41,0x26,0x40,0x27,0x40, + 0x29,0x3f,0x2b,0x3f,0x2c,0x3f,0x2d,0x3f,0x2e,0x3f,0x2f,0x3f,0x30,0x3f,0x30,0x3e,0x31,0x3e,0x32,0x3e, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x72,0x00,0x5c,0x00,0x2d,0x00,0x01, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x72,0x00,0x5c,0x00, + 0x2d,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x42,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x72,0x06,0x5f,0x0d,0x56,0x14,0x4f,0x19,0x4d,0x1d,0x4a,0x20,0x49,0x23,0x47,0x25,0x46,0x27,0x46,0x29, + 0x45,0x2a,0x45,0x2c,0x44,0x2d,0x44,0x2e,0x44,0x2f,0x43,0x30,0x44,0x30,0x44,0x31,0x43,0x32,0x43,0x33, + 0x00,0x6d,0x04,0x5b,0x09,0x51,0x0e,0x4c,0x13,0x48,0x17,0x46,0x1a,0x44,0x1d,0x43,0x1f,0x42,0x22,0x42, + 0x24,0x41,0x25,0x41,0x27,0x40,0x28,0x40,0x29,0x40,0x2a,0x3f,0x2b,0x3f,0x2c,0x3f,0x2d,0x3f,0x2e,0x3f, + 0x42,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x78,0x00,0x6a,0x00,0x48,0x00,0x22, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x78,0x00,0x6a,0x00, + 0x48,0x00,0x22,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x75,0x03,0x64,0x09,0x5a,0x0e,0x54,0x13,0x51,0x17,0x4e,0x1a,0x4c,0x1d,0x49,0x1f,0x49,0x22,0x48,0x23, + 0x47,0x25,0x46,0x26,0x46,0x28,0x45,0x29,0x45,0x2a,0x44,0x2b,0x44,0x2c,0x44,0x2d,0x44,0x2e,0x44,0x2e, + 0x00,0x70,0x02,0x60,0x07,0x56,0x0b,0x50,0x0f,0x4c,0x12,0x49,0x16,0x47,0x18,0x46,0x1b,0x45,0x1d,0x44, + 0x1f,0x43,0x21,0x42,0x22,0x42,0x24,0x41,0x25,0x41,0x26,0x40,0x27,0x40,0x28,0x40,0x29,0x40,0x2a,0x3f, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7a,0x00,0x71,0x00,0x59,0x00,0x3a, + 0x00,0x1b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7a,0x00,0x71,0x00, + 0x59,0x00,0x3a,0x00,0x1b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x77,0x02,0x68,0x06,0x5f,0x0b,0x58,0x0f,0x54,0x12,0x51,0x15,0x4f,0x18,0x4c,0x1b,0x4b,0x1d,0x4a,0x1f, + 0x49,0x21,0x48,0x22,0x48,0x23,0x47,0x25,0x46,0x26,0x45,0x27,0x45,0x28,0x45,0x29,0x45,0x2a,0x44,0x2b, + 0x00,0x72,0x02,0x64,0x05,0x5b,0x08,0x54,0x0c,0x50,0x0f,0x4d,0x12,0x4a,0x14,0x48,0x17,0x47,0x19,0x46, + 0x1b,0x45,0x1d,0x44,0x1f,0x44,0x20,0x42,0x21,0x42,0x22,0x42,0x24,0x41,0x25,0x41,0x26,0x41,0x27,0x40, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x75,0x00,0x63,0x00,0x4a, + 0x00,0x30,0x00,0x16,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x75,0x00, + 0x63,0x00,0x4a,0x00,0x30,0x00,0x16,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x78,0x02,0x6b,0x05,0x62,0x08,0x5b,0x0c,0x57,0x0f,0x54,0x12,0x51,0x14,0x4e,0x17,0x4d,0x19,0x4c,0x1b, + 0x4b,0x1d,0x4a,0x1e,0x49,0x20,0x48,0x21,0x48,0x22,0x46,0x24,0x46,0x25,0x46,0x26,0x46,0x27,0x45,0x27, + 0x00,0x74,0x01,0x66,0x04,0x5e,0x07,0x57,0x0a,0x53,0x0d,0x4f,0x10,0x4d,0x12,0x4b,0x14,0x49,0x16,0x48, + 0x18,0x46,0x1a,0x45,0x1b,0x45,0x1d,0x44,0x1e,0x44,0x20,0x43,0x21,0x42,0x22,0x42,0x23,0x42,0x24,0x41, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x78,0x00,0x6a,0x00,0x56, + 0x00,0x3f,0x00,0x28,0x00,0x13,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x78,0x00, + 0x6a,0x00,0x56,0x00,0x3f,0x00,0x28,0x00,0x13,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x79,0x01,0x6d,0x04,0x65,0x07,0x5e,0x0a,0x5a,0x0d,0x56,0x0f,0x54,0x12,0x51,0x14,0x4f,0x16,0x4e,0x18, + 0x4c,0x1a,0x4b,0x1b,0x4b,0x1d,0x4a,0x1e,0x49,0x1f,0x48,0x21,0x48,0x22,0x48,0x23,0x47,0x23,0x46,0x25, + 0x00,0x75,0x01,0x69,0x03,0x61,0x06,0x5a,0x08,0x56,0x0b,0x52,0x0d,0x4f,0x10,0x4d,0x12,0x4b,0x14,0x4a, + 0x16,0x48,0x17,0x47,0x19,0x46,0x1a,0x45,0x1c,0x45,0x1d,0x44,0x1e,0x44,0x1f,0x44,0x20,0x43,0x21,0x42, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x79,0x00,0x6e,0x00,0x5e, + 0x00,0x4b,0x00,0x37,0x00,0x23,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x79,0x00, + 0x6e,0x00,0x5e,0x00,0x4b,0x00,0x37,0x00,0x23,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7a,0x01,0x6f,0x03,0x67,0x06,0x60,0x08,0x5d,0x0b,0x59,0x0d,0x56,0x10,0x53,0x11,0x51,0x14,0x50,0x15, + 0x4e,0x17,0x4d,0x19,0x4c,0x1a,0x4b,0x1b,0x4b,0x1d,0x48,0x1e,0x49,0x1f,0x49,0x20,0x48,0x21,0x48,0x22, + 0x00,0x76,0x01,0x6b,0x03,0x63,0x05,0x5d,0x07,0x58,0x09,0x54,0x0c,0x52,0x0e,0x4f,0x10,0x4d,0x11,0x4c, + 0x13,0x4a,0x15,0x49,0x17,0x48,0x18,0x47,0x19,0x46,0x1b,0x45,0x1c,0x45,0x1d,0x44,0x1e,0x44,0x1f,0x44, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x7a,0x00,0x72,0x00,0x64, + 0x00,0x54,0x00,0x42,0x00,0x30,0x00,0x1f,0x00,0x0e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x7a,0x00, + 0x72,0x00,0x64,0x00,0x54,0x00,0x42,0x00,0x30,0x00,0x1f,0x00,0x0e,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7b,0x01,0x71,0x02,0x69,0x05,0x63,0x07,0x5f,0x09,0x5b,0x0c,0x58,0x0e,0x55,0x10,0x53,0x11,0x52,0x13, + 0x50,0x15,0x4e,0x16,0x4e,0x18,0x4c,0x19,0x4c,0x1a,0x4a,0x1c,0x4b,0x1d,0x49,0x1e,0x49,0x1f,0x49,0x20, + 0x00,0x77,0x00,0x6c,0x02,0x65,0x04,0x5f,0x06,0x5a,0x08,0x57,0x0a,0x54,0x0c,0x51,0x0e,0x4f,0x10,0x4d, + 0x11,0x4c,0x13,0x4a,0x15,0x49,0x16,0x48,0x18,0x48,0x18,0x46,0x1a,0x46,0x1b,0x45,0x1c,0x45,0x1d,0x45, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7b,0x00,0x74,0x00,0x69, + 0x00,0x5b,0x00,0x4b,0x00,0x3b,0x00,0x2b,0x00,0x1b,0x00,0x0d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7b,0x00, + 0x74,0x00,0x69,0x00,0x5b,0x00,0x4b,0x00,0x3b,0x00,0x2b,0x00,0x1b,0x00,0x0d,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7b,0x00,0x72,0x02,0x6b,0x04,0x64,0x06,0x61,0x08,0x5d,0x0a,0x5a,0x0c,0x56,0x0e,0x55,0x10,0x53,0x11, + 0x52,0x13,0x50,0x15,0x4f,0x16,0x4e,0x17,0x4d,0x18,0x4b,0x1a,0x4b,0x1a,0x4b,0x1c,0x4b,0x1d,0x49,0x1d, + 0x00,0x77,0x00,0x6e,0x02,0x66,0x04,0x61,0x05,0x5c,0x07,0x59,0x09,0x56,0x0b,0x53,0x0d,0x51,0x0f,0x4f, + 0x10,0x4e,0x11,0x4c,0x13,0x4b,0x14,0x4a,0x15,0x48,0x17,0x48,0x18,0x47,0x19,0x46,0x1b,0x46,0x1b,0x45, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00,0x76,0x00,0x6d, + 0x00,0x61,0x00,0x53,0x00,0x44,0x00,0x35,0x00,0x27,0x00,0x19,0x00,0x0c,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00, + 0x76,0x00,0x6d,0x00,0x61,0x00,0x53,0x00,0x44,0x00,0x35,0x00,0x27,0x00,0x19,0x00,0x0c,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7c,0x00,0x73,0x02,0x6c,0x03,0x66,0x05,0x63,0x07,0x5e,0x09,0x5c,0x0b,0x58,0x0c,0x57,0x0e,0x55,0x10, + 0x53,0x11,0x52,0x13,0x50,0x14,0x4f,0x15,0x4e,0x17,0x4c,0x18,0x4c,0x19,0x4c,0x1a,0x4b,0x1a,0x4b,0x1c, + 0x00,0x77,0x00,0x6f,0x02,0x68,0x03,0x63,0x05,0x5e,0x06,0x5a,0x08,0x57,0x0a,0x55,0x0b,0x53,0x0d,0x50, + 0x0f,0x4f,0x10,0x4e,0x11,0x4c,0x13,0x4b,0x14,0x4a,0x15,0x49,0x16,0x48,0x18,0x48,0x18,0x46,0x19,0x46, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00,0x77,0x00,0x6f, + 0x00,0x65,0x00,0x59,0x00,0x4c,0x00,0x3e,0x00,0x30,0x00,0x23,0x00,0x16,0x00,0x0b,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00, + 0x77,0x00,0x6f,0x00,0x65,0x00,0x59,0x00,0x4c,0x00,0x3e,0x00,0x30,0x00,0x23,0x00,0x16,0x00,0x0b,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7c,0x00,0x74,0x02,0x6e,0x03,0x68,0x05,0x64,0x06,0x60,0x08,0x5d,0x0a,0x5a,0x0b,0x58,0x0d,0x56,0x0e, + 0x55,0x10,0x53,0x11,0x52,0x13,0x50,0x14,0x50,0x15,0x4d,0x16,0x4e,0x18,0x4c,0x18,0x4c,0x19,0x4c,0x1a, + 0x00,0x78,0x00,0x70,0x01,0x69,0x03,0x64,0x04,0x60,0x06,0x5c,0x07,0x59,0x09,0x56,0x0b,0x54,0x0c,0x52, + 0x0d,0x50,0x0f,0x4f,0x10,0x4e,0x11,0x4c,0x13,0x4b,0x13,0x4a,0x15,0x4a,0x15,0x48,0x17,0x48,0x18,0x47, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00,0x78,0x00,0x71, + 0x00,0x68,0x00,0x5e,0x00,0x52,0x00,0x45,0x00,0x39,0x00,0x2c,0x00,0x20,0x00,0x15,0x00,0x0a,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x78,0x00,0x71,0x00,0x68,0x00,0x5e,0x00,0x52,0x00,0x45,0x00,0x39,0x00,0x2c,0x00,0x20,0x00,0x15,0x00, + 0x0a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7d,0x00,0x75,0x01,0x6f,0x02,0x69,0x04,0x65,0x06,0x62,0x07,0x5f,0x09,0x5b,0x0b,0x5a,0x0c,0x58,0x0d, + 0x56,0x0e,0x55,0x10,0x53,0x11,0x52,0x13,0x50,0x13,0x4f,0x15,0x4e,0x15,0x4e,0x17,0x4d,0x18,0x4c,0x18, + 0x00,0x78,0x00,0x71,0x01,0x6a,0x03,0x66,0x04,0x61,0x05,0x5d,0x06,0x5a,0x08,0x58,0x09,0x55,0x0b,0x53, + 0x0d,0x52,0x0e,0x50,0x0f,0x4e,0x10,0x4e,0x11,0x4c,0x13,0x4c,0x13,0x4a,0x15,0x4a,0x15,0x49,0x16,0x48, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00,0x79,0x00,0x73, + 0x00,0x6b,0x00,0x62,0x00,0x57,0x00,0x4c,0x00,0x40,0x00,0x34,0x00,0x29,0x00,0x1e,0x00,0x13,0x00,0x09, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x79,0x00,0x73,0x00,0x6b,0x00,0x62,0x00,0x57,0x00,0x4c,0x00,0x40,0x00,0x34,0x00,0x29,0x00,0x1e,0x00, + 0x13,0x00,0x09,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7d,0x00,0x76,0x01,0x70,0x02,0x6a,0x03,0x67,0x05,0x63,0x06,0x60,0x08,0x5d,0x09,0x5b,0x0b,0x59,0x0c, + 0x57,0x0d,0x55,0x0e,0x55,0x10,0x53,0x11,0x52,0x13,0x4f,0x13,0x50,0x15,0x4f,0x15,0x4e,0x16,0x4e,0x18, + 0x00,0x79,0x00,0x71,0x01,0x6c,0x02,0x66,0x04,0x62,0x05,0x5f,0x06,0x5c,0x07,0x59,0x09,0x57,0x0a,0x55, + 0x0b,0x53,0x0d,0x51,0x0e,0x50,0x0f,0x4e,0x11,0x4e,0x11,0x4c,0x13,0x4c,0x13,0x4b,0x14,0x4a,0x15,0x4a, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00,0x7a,0x00,0x75, + 0x00,0x6e,0x00,0x65,0x00,0x5b,0x00,0x51,0x00,0x46,0x00,0x3b,0x00,0x30,0x00,0x26,0x00,0x1b,0x00,0x12, + 0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x7a,0x00,0x75,0x00,0x6e,0x00,0x65,0x00,0x5b,0x00,0x51,0x00,0x46,0x00,0x3b,0x00,0x30,0x00,0x26,0x00, + 0x1b,0x00,0x12,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7d,0x00,0x76,0x01,0x71,0x02,0x6c,0x03,0x68,0x05,0x64,0x06,0x61,0x07,0x5e,0x09,0x5c,0x0a,0x5a,0x0b, + 0x59,0x0c,0x57,0x0e,0x55,0x0e,0x55,0x11,0x52,0x11,0x51,0x12,0x51,0x13,0x50,0x14,0x4f,0x15,0x4e,0x15, + 0x00,0x79,0x00,0x72,0x01,0x6d,0x02,0x68,0x03,0x63,0x04,0x60,0x06,0x5d,0x07,0x5b,0x08,0x58,0x09,0x56, + 0x0b,0x54,0x0c,0x53,0x0d,0x51,0x0e,0x50,0x0f,0x4e,0x11,0x4e,0x11,0x4c,0x12,0x4c,0x13,0x4b,0x14,0x4a, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x1f,0x00,0x3f,0x00,0x66,0x00,0x72,0x00,0x78,0x00,0x7a,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d, + 0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7d,0x00,0x58,0x00,0x70,0x00,0x77, + 0x00,0x79,0x00,0x7b,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e, + 0x00,0x7e,0x00,0x7e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x1f,0x00,0x3f, + 0x00,0x66,0x00,0x72,0x00,0x78,0x00,0x7a,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7e,0x00,0x7e, + 0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x1f,0x1f,0x00,0x3f,0x00,0x66,0x00,0x72,0x00,0x78,0x00,0x7a, + 0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7d,0x00,0x77,0x01,0x72,0x02,0x6d,0x03,0x69,0x04,0x66,0x06,0x63,0x07,0x5f,0x08,0x5e,0x09,0x5c,0x0b, + 0x5a,0x0c,0x58,0x0c,0x57,0x0e,0x55,0x0f,0x54,0x11,0x51,0x11,0x52,0x12,0x51,0x13,0x50,0x14,0x50,0x15, + 0x00,0x79,0x00,0x73,0x01,0x6d,0x02,0x69,0x03,0x65,0x04,0x61,0x05,0x5e,0x06,0x5c,0x07,0x59,0x09,0x57, + 0x0a,0x55,0x0b,0x54,0x0d,0x53,0x0d,0x51,0x0f,0x50,0x0f,0x4e,0x11,0x4e,0x11,0x4c,0x12,0x4c,0x13,0x4b, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x0a,0x00,0x3f,0x00,0x5c,0x00,0x6a,0x00,0x71,0x00,0x75,0x00,0x78,0x00,0x79,0x00,0x7a, + 0x00,0x7b,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7d,0x00,0x58,0x00,0x44,0x00,0x55,0x00,0x67, + 0x00,0x6e,0x00,0x72,0x00,0x75,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x7b,0x00,0x7c,0x00,0x7c,0x00,0x7d, + 0x00,0x7d,0x00,0x7d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3f,0x00,0x0a,0x0a, + 0x00,0x3f,0x00,0x5c,0x00,0x6a,0x00,0x71,0x00,0x75,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x7b,0x00,0x7c, + 0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7d,0x3f,0x00,0x0a,0x0a,0x00,0x3f,0x00,0x5c,0x00,0x6a,0x00,0x71, + 0x00,0x75,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x7b,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7d, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7d,0x00,0x78,0x01,0x72,0x02,0x6e,0x02,0x6a,0x03,0x67,0x05,0x64,0x06,0x60,0x07,0x5f,0x09,0x5c,0x0a, + 0x5b,0x0b,0x5a,0x0c,0x57,0x0c,0x56,0x0e,0x55,0x0f,0x53,0x11,0x52,0x11,0x52,0x12,0x51,0x13,0x50,0x13, + 0x00,0x79,0x00,0x73,0x01,0x6e,0x02,0x69,0x03,0x66,0x04,0x62,0x05,0x5f,0x06,0x5d,0x07,0x5b,0x08,0x58, + 0x09,0x56,0x0b,0x55,0x0b,0x53,0x0d,0x52,0x0d,0x50,0x0f,0x50,0x0f,0x4e,0x11,0x4e,0x11,0x4d,0x12,0x4c, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x2d,0x00,0x48,0x00,0x59,0x00,0x63,0x00,0x6a,0x00,0x6e,0x00,0x72, + 0x00,0x74,0x00,0x76,0x00,0x77,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x70,0x00,0x55,0x00,0x20,0x00,0x3e, + 0x00,0x50,0x00,0x5a,0x00,0x63,0x00,0x6a,0x00,0x6e,0x00,0x72,0x00,0x74,0x00,0x76,0x00,0x77,0x00,0x78, + 0x00,0x79,0x00,0x7a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x66,0x00,0x3f,0x00, + 0x03,0x03,0x00,0x2d,0x00,0x48,0x00,0x59,0x00,0x63,0x00,0x6a,0x00,0x6e,0x00,0x72,0x00,0x74,0x00,0x76, + 0x00,0x77,0x00,0x78,0x00,0x79,0x00,0x7a,0x66,0x00,0x3f,0x00,0x03,0x03,0x00,0x2d,0x00,0x48,0x00,0x59, + 0x00,0x63,0x00,0x6a,0x00,0x6e,0x00,0x72,0x00,0x74,0x00,0x76,0x00,0x77,0x00,0x78,0x00,0x79,0x00,0x7a, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7e,0x00,0x78,0x01,0x73,0x02,0x6e,0x02,0x6b,0x03,0x68,0x05,0x65,0x06,0x61,0x07,0x5f,0x07,0x5e,0x09, + 0x5c,0x0b,0x5a,0x0b,0x59,0x0c,0x57,0x0d,0x56,0x0e,0x54,0x0f,0x54,0x11,0x52,0x11,0x52,0x12,0x51,0x13, + 0x00,0x79,0x00,0x74,0x00,0x6f,0x02,0x6a,0x03,0x66,0x04,0x63,0x05,0x60,0x05,0x5e,0x06,0x5b,0x07,0x59, + 0x09,0x58,0x09,0x55,0x0b,0x55,0x0c,0x53,0x0d,0x52,0x0d,0x50,0x0f,0x50,0x0f,0x4e,0x11,0x4e,0x11,0x4d, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x22,0x00,0x3a,0x00,0x4a,0x00,0x56,0x00,0x5e,0x00,0x64, + 0x00,0x69,0x00,0x6d,0x00,0x6f,0x00,0x71,0x00,0x73,0x00,0x75,0x00,0x77,0x00,0x67,0x00,0x3e,0x00,0x0d, + 0x00,0x28,0x00,0x3a,0x00,0x4a,0x00,0x56,0x00,0x5e,0x00,0x64,0x00,0x69,0x00,0x6d,0x00,0x6f,0x00,0x71, + 0x00,0x73,0x00,0x75,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x72,0x00,0x5c,0x00, + 0x2d,0x00,0x01,0x01,0x00,0x22,0x00,0x3a,0x00,0x4a,0x00,0x56,0x00,0x5e,0x00,0x64,0x00,0x69,0x00,0x6d, + 0x00,0x6f,0x00,0x71,0x00,0x73,0x00,0x75,0x72,0x00,0x5c,0x00,0x2d,0x00,0x01,0x01,0x00,0x22,0x00,0x3a, + 0x00,0x4a,0x00,0x56,0x00,0x5e,0x00,0x64,0x00,0x69,0x00,0x6d,0x00,0x6f,0x00,0x71,0x00,0x73,0x00,0x75, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7e,0x00,0x78,0x00,0x74,0x01,0x6f,0x02,0x6c,0x03,0x68,0x04,0x65,0x05,0x62,0x06,0x61,0x07,0x5f,0x09, + 0x5c,0x09,0x5b,0x0b,0x5a,0x0b,0x58,0x0c,0x57,0x0d,0x55,0x0e,0x55,0x0f,0x54,0x11,0x52,0x11,0x52,0x12, + 0x00,0x79,0x00,0x74,0x00,0x70,0x01,0x6b,0x02,0x67,0x03,0x64,0x04,0x61,0x05,0x5f,0x06,0x5d,0x07,0x5b, + 0x08,0x58,0x09,0x57,0x0a,0x55,0x0b,0x54,0x0c,0x53,0x0d,0x51,0x0e,0x50,0x0f,0x50,0x0f,0x4e,0x11,0x4e, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1b,0x00,0x30,0x00,0x3f,0x00,0x4b,0x00,0x54, + 0x00,0x5b,0x00,0x61,0x00,0x65,0x00,0x68,0x00,0x6b,0x00,0x6e,0x00,0x79,0x00,0x6e,0x00,0x50,0x00,0x28, + 0x00,0x01,0x00,0x1b,0x00,0x30,0x00,0x3f,0x00,0x4b,0x00,0x54,0x00,0x5b,0x00,0x61,0x00,0x65,0x00,0x68, + 0x00,0x6b,0x00,0x6e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x78,0x00,0x6a,0x00, + 0x48,0x00,0x22,0x00,0x00,0x00,0x00,0x1b,0x00,0x30,0x00,0x3f,0x00,0x4b,0x00,0x54,0x00,0x5b,0x00,0x61, + 0x00,0x65,0x00,0x68,0x00,0x6b,0x00,0x6e,0x78,0x00,0x6a,0x00,0x48,0x00,0x22,0x00,0x00,0x00,0x00,0x1b, + 0x00,0x30,0x00,0x3f,0x00,0x4b,0x00,0x54,0x00,0x5b,0x00,0x61,0x00,0x65,0x00,0x68,0x00,0x6b,0x00,0x6e, + 0x21,0x5d,0x0c,0x68,0x06,0x6d,0x04,0x71,0x02,0x72,0x02,0x74,0x01,0x75,0x01,0x76,0x01,0x77,0x00,0x77, + 0x00,0x77,0x00,0x78,0x00,0x78,0x00,0x79,0x00,0x79,0x00,0x79,0x00,0x79,0x00,0x79,0x00,0x79,0x00,0x7a, + 0x42,0x40,0x17,0x55,0x0c,0x60,0x08,0x66,0x05,0x6a,0x04,0x6d,0x03,0x6f,0x02,0x71,0x02,0x73,0x01,0x73, + 0x01,0x74,0x01,0x75,0x01,0x76,0x01,0x77,0x00,0x77,0x00,0x77,0x00,0x78,0x00,0x78,0x00,0x78,0x00,0x78, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x21,0x5d,0x0c,0x68,0x06,0x6d,0x04,0x71,0x02,0x72,0x02,0x74,0x01,0x75,0x01,0x76,0x01,0x77,0x00,0x77, + 0x00,0x77,0x00,0x78,0x00,0x78,0x00,0x79,0x00,0x79,0x00,0x79,0x00,0x79,0x00,0x79,0x00,0x79,0x00,0x7a, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x16,0x00,0x28,0x00,0x37,0x00,0x42, + 0x00,0x4b,0x00,0x53,0x00,0x59,0x00,0x5e,0x00,0x62,0x00,0x65,0x00,0x7b,0x00,0x72,0x00,0x5a,0x00,0x3a, + 0x00,0x1b,0x00,0x01,0x00,0x16,0x00,0x28,0x00,0x37,0x00,0x42,0x00,0x4b,0x00,0x53,0x00,0x59,0x00,0x5e, + 0x00,0x62,0x00,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7a,0x00,0x71,0x00, + 0x59,0x00,0x3a,0x00,0x1b,0x00,0x00,0x00,0x00,0x16,0x00,0x28,0x00,0x37,0x00,0x42,0x00,0x4b,0x00,0x53, + 0x00,0x59,0x00,0x5e,0x00,0x62,0x00,0x65,0x7a,0x00,0x71,0x00,0x59,0x00,0x3a,0x00,0x1b,0x00,0x00,0x00, + 0x00,0x16,0x00,0x28,0x00,0x37,0x00,0x42,0x00,0x4b,0x00,0x53,0x00,0x59,0x00,0x5e,0x00,0x62,0x00,0x65, + 0x2b,0x49,0x16,0x53,0x0d,0x5b,0x09,0x60,0x07,0x64,0x05,0x67,0x04,0x69,0x03,0x6b,0x03,0x6c,0x02,0x6e, + 0x02,0x6f,0x02,0x70,0x01,0x71,0x01,0x71,0x01,0x72,0x01,0x73,0x01,0x73,0x01,0x74,0x00,0x74,0x00,0x75, + 0x57,0x16,0x2d,0x2c,0x1b,0x3b,0x12,0x45,0x0d,0x4d,0x0b,0x53,0x08,0x57,0x07,0x5b,0x05,0x5e,0x05,0x61, + 0x04,0x63,0x04,0x65,0x03,0x67,0x02,0x68,0x02,0x69,0x02,0x6b,0x02,0x6c,0x01,0x6d,0x01,0x6e,0x01,0x6f, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x2b,0x49,0x16,0x53,0x0d,0x5b,0x09,0x60,0x07,0x64,0x05,0x67,0x04,0x69,0x03,0x6b,0x03,0x6c,0x02,0x6e, + 0x02,0x6f,0x02,0x70,0x01,0x71,0x01,0x71,0x01,0x72,0x01,0x73,0x01,0x73,0x01,0x74,0x00,0x74,0x00,0x75, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x13,0x00,0x23,0x00,0x30, + 0x00,0x3b,0x00,0x44,0x00,0x4c,0x00,0x52,0x00,0x57,0x00,0x5b,0x00,0x7c,0x00,0x75,0x00,0x63,0x00,0x4a, + 0x00,0x30,0x00,0x16,0x00,0x00,0x00,0x13,0x00,0x23,0x00,0x30,0x00,0x3b,0x00,0x44,0x00,0x4c,0x00,0x52, + 0x00,0x57,0x00,0x5b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x75,0x00, + 0x63,0x00,0x4a,0x00,0x30,0x00,0x16,0x00,0x00,0x00,0x00,0x13,0x00,0x23,0x00,0x30,0x00,0x3b,0x00,0x44, + 0x00,0x4c,0x00,0x52,0x00,0x57,0x00,0x5b,0x7c,0x00,0x75,0x00,0x63,0x00,0x4a,0x00,0x30,0x00,0x16,0x00, + 0x00,0x00,0x00,0x13,0x00,0x23,0x00,0x30,0x00,0x3b,0x00,0x44,0x00,0x4c,0x00,0x52,0x00,0x57,0x00,0x5b, + 0x31,0x43,0x1d,0x4b,0x14,0x51,0x0e,0x56,0x0b,0x5b,0x08,0x5e,0x07,0x61,0x06,0x63,0x05,0x65,0x04,0x67, + 0x04,0x68,0x03,0x69,0x03,0x6a,0x03,0x6c,0x02,0x6d,0x02,0x6d,0x02,0x6e,0x02,0x6f,0x02,0x70,0x01,0x70, + 0x61,0x0c,0x3b,0x1b,0x28,0x28,0x1d,0x32,0x16,0x3a,0x11,0x41,0x0e,0x47,0x0c,0x4b,0x0a,0x4f,0x09,0x53, + 0x07,0x55,0x06,0x58,0x05,0x5a,0x05,0x5c,0x05,0x5e,0x04,0x60,0x04,0x61,0x04,0x63,0x03,0x64,0x02,0x66, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x31,0x43,0x1d,0x4b,0x14,0x51,0x0e,0x56,0x0b,0x5b,0x08,0x5e,0x07,0x61,0x06,0x63,0x05,0x65,0x04,0x67, + 0x04,0x68,0x03,0x69,0x03,0x6a,0x03,0x6c,0x02,0x6d,0x02,0x6d,0x02,0x6e,0x02,0x6f,0x02,0x70,0x01,0x70, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x1f, + 0x00,0x2b,0x00,0x35,0x00,0x3e,0x00,0x45,0x00,0x4c,0x00,0x51,0x00,0x7c,0x00,0x78,0x00,0x6a,0x00,0x56, + 0x00,0x3f,0x00,0x28,0x00,0x13,0x00,0x00,0x00,0x10,0x00,0x1f,0x00,0x2b,0x00,0x35,0x00,0x3e,0x00,0x45, + 0x00,0x4c,0x00,0x51,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x78,0x00, + 0x6a,0x00,0x56,0x00,0x3f,0x00,0x28,0x00,0x13,0x00,0x00,0x00,0x00,0x10,0x00,0x1f,0x00,0x2b,0x00,0x35, + 0x00,0x3e,0x00,0x45,0x00,0x4c,0x00,0x51,0x7c,0x00,0x78,0x00,0x6a,0x00,0x56,0x00,0x3f,0x00,0x28,0x00, + 0x13,0x00,0x00,0x00,0x00,0x10,0x00,0x1f,0x00,0x2b,0x00,0x35,0x00,0x3e,0x00,0x45,0x00,0x4c,0x00,0x51, + 0x33,0x41,0x22,0x46,0x19,0x4c,0x13,0x50,0x0f,0x54,0x0c,0x57,0x0a,0x5a,0x08,0x5d,0x07,0x5f,0x06,0x61, + 0x05,0x63,0x05,0x64,0x04,0x66,0x04,0x66,0x04,0x68,0x03,0x69,0x03,0x69,0x03,0x6a,0x03,0x6b,0x02,0x6c, + 0x67,0x07,0x45,0x12,0x32,0x1d,0x26,0x26,0x1e,0x2e,0x18,0x34,0x14,0x3a,0x11,0x3f,0x0f,0x44,0x0c,0x47, + 0x0b,0x4b,0x0a,0x4d,0x09,0x51,0x07,0x52,0x07,0x55,0x06,0x57,0x05,0x58,0x05,0x5a,0x05,0x5c,0x04,0x5d, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x33,0x41,0x22,0x46,0x19,0x4c,0x13,0x50,0x0f,0x54,0x0c,0x57,0x0a,0x5a,0x08,0x5d,0x07,0x5f,0x06,0x61, + 0x05,0x63,0x05,0x64,0x04,0x66,0x04,0x66,0x04,0x68,0x03,0x69,0x03,0x69,0x03,0x6a,0x03,0x6b,0x02,0x6c, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0e, + 0x00,0x1b,0x00,0x27,0x00,0x30,0x00,0x39,0x00,0x40,0x00,0x46,0x00,0x7d,0x00,0x79,0x00,0x6e,0x00,0x5e, + 0x00,0x4b,0x00,0x37,0x00,0x23,0x00,0x10,0x00,0x00,0x00,0x0e,0x00,0x1b,0x00,0x27,0x00,0x30,0x00,0x39, + 0x00,0x40,0x00,0x46,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x79,0x00, + 0x6e,0x00,0x5e,0x00,0x4b,0x00,0x37,0x00,0x23,0x00,0x10,0x00,0x00,0x00,0x00,0x0e,0x00,0x1b,0x00,0x27, + 0x00,0x30,0x00,0x39,0x00,0x40,0x00,0x46,0x7d,0x00,0x79,0x00,0x6e,0x00,0x5e,0x00,0x4b,0x00,0x37,0x00, + 0x23,0x00,0x10,0x00,0x00,0x00,0x00,0x0e,0x00,0x1b,0x00,0x27,0x00,0x30,0x00,0x39,0x00,0x40,0x00,0x46, + 0x35,0x40,0x27,0x44,0x1d,0x48,0x17,0x4c,0x12,0x50,0x0f,0x53,0x0d,0x56,0x0b,0x58,0x09,0x5a,0x08,0x5c, + 0x07,0x5e,0x06,0x60,0x06,0x61,0x05,0x62,0x05,0x63,0x04,0x65,0x04,0x66,0x04,0x66,0x04,0x67,0x03,0x68, + 0x6b,0x05,0x4d,0x0d,0x3b,0x16,0x2e,0x1e,0x25,0x25,0x1f,0x2b,0x1a,0x31,0x16,0x36,0x13,0x3a,0x10,0x3e, + 0x0f,0x42,0x0d,0x45,0x0c,0x47,0x0a,0x4a,0x0a,0x4c,0x09,0x4f,0x07,0x51,0x07,0x52,0x07,0x54,0x06,0x56, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x35,0x40,0x27,0x44,0x1d,0x48,0x17,0x4c,0x12,0x50,0x0f,0x53,0x0d,0x56,0x0b,0x58,0x09,0x5a,0x08,0x5c, + 0x07,0x5e,0x06,0x60,0x06,0x61,0x05,0x62,0x05,0x63,0x04,0x65,0x04,0x66,0x04,0x66,0x04,0x67,0x03,0x68, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x0d,0x00,0x19,0x00,0x23,0x00,0x2c,0x00,0x34,0x00,0x3b,0x00,0x7d,0x00,0x7a,0x00,0x72,0x00,0x64, + 0x00,0x54,0x00,0x42,0x00,0x30,0x00,0x1f,0x00,0x0e,0x00,0x00,0x00,0x0d,0x00,0x19,0x00,0x23,0x00,0x2c, + 0x00,0x34,0x00,0x3b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x7a,0x00, + 0x72,0x00,0x64,0x00,0x54,0x00,0x42,0x00,0x30,0x00,0x1f,0x00,0x0e,0x00,0x00,0x00,0x00,0x0d,0x00,0x19, + 0x00,0x23,0x00,0x2c,0x00,0x34,0x00,0x3b,0x7d,0x00,0x7a,0x00,0x72,0x00,0x64,0x00,0x54,0x00,0x42,0x00, + 0x30,0x00,0x1f,0x00,0x0e,0x00,0x00,0x00,0x00,0x0d,0x00,0x19,0x00,0x23,0x00,0x2c,0x00,0x34,0x00,0x3b, + 0x37,0x3f,0x29,0x43,0x21,0x46,0x1a,0x49,0x16,0x4d,0x12,0x50,0x10,0x52,0x0d,0x54,0x0c,0x57,0x0a,0x59, + 0x09,0x5a,0x08,0x5c,0x07,0x5d,0x06,0x5f,0x06,0x60,0x06,0x61,0x05,0x62,0x05,0x63,0x04,0x64,0x04,0x65, + 0x6e,0x04,0x53,0x0a,0x41,0x11,0x34,0x18,0x2b,0x1f,0x24,0x24,0x1f,0x29,0x1b,0x2e,0x17,0x33,0x15,0x37, + 0x12,0x3a,0x10,0x3d,0x0f,0x40,0x0d,0x43,0x0c,0x45,0x0c,0x48,0x0a,0x4a,0x0a,0x4c,0x09,0x4e,0x07,0x4f, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x37,0x3f,0x29,0x43,0x21,0x46,0x1a,0x49,0x16,0x4d,0x12,0x50,0x10,0x52,0x0d,0x54,0x0c,0x57,0x0a,0x59, + 0x09,0x5a,0x08,0x5c,0x07,0x5d,0x06,0x5f,0x06,0x60,0x06,0x61,0x05,0x62,0x05,0x63,0x04,0x64,0x04,0x65, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x0c,0x00,0x16,0x00,0x20,0x00,0x29,0x00,0x30,0x00,0x7e,0x00,0x7b,0x00,0x74,0x00,0x69, + 0x00,0x5b,0x00,0x4b,0x00,0x3b,0x00,0x2b,0x00,0x1b,0x00,0x0d,0x00,0x00,0x00,0x0c,0x00,0x16,0x00,0x20, + 0x00,0x29,0x00,0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7b,0x00, + 0x74,0x00,0x69,0x00,0x5b,0x00,0x4b,0x00,0x3b,0x00,0x2b,0x00,0x1b,0x00,0x0d,0x00,0x00,0x00,0x00,0x0c, + 0x00,0x16,0x00,0x20,0x00,0x29,0x00,0x30,0x7e,0x00,0x7b,0x00,0x74,0x00,0x69,0x00,0x5b,0x00,0x4b,0x00, + 0x3b,0x00,0x2b,0x00,0x1b,0x00,0x0d,0x00,0x00,0x00,0x00,0x0c,0x00,0x16,0x00,0x20,0x00,0x29,0x00,0x30, + 0x38,0x3f,0x2c,0x41,0x23,0x44,0x1d,0x47,0x19,0x4a,0x14,0x4d,0x12,0x4f,0x10,0x52,0x0e,0x54,0x0c,0x56, + 0x0b,0x57,0x0a,0x59,0x09,0x5a,0x08,0x5c,0x07,0x5d,0x07,0x5e,0x06,0x5f,0x06,0x61,0x05,0x61,0x05,0x62, + 0x70,0x03,0x58,0x08,0x47,0x0e,0x3a,0x14,0x31,0x1a,0x29,0x1f,0x24,0x24,0x20,0x28,0x1c,0x2d,0x19,0x31, + 0x16,0x34,0x14,0x37,0x12,0x3a,0x10,0x3d,0x0f,0x3f,0x0e,0x42,0x0c,0x44,0x0c,0x46,0x0b,0x47,0x0a,0x4a, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x38,0x3f,0x2c,0x41,0x23,0x44,0x1d,0x47,0x19,0x4a,0x14,0x4d,0x12,0x4f,0x10,0x52,0x0e,0x54,0x0c,0x56, + 0x0b,0x57,0x0a,0x59,0x09,0x5a,0x08,0x5c,0x07,0x5d,0x07,0x5e,0x06,0x5f,0x06,0x61,0x05,0x61,0x05,0x62, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x0b,0x00,0x15,0x00,0x1e,0x00,0x26,0x00,0x7e,0x00,0x7c,0x00,0x76,0x00,0x6d, + 0x00,0x61,0x00,0x53,0x00,0x44,0x00,0x35,0x00,0x27,0x00,0x19,0x00,0x0c,0x00,0x00,0x00,0x0b,0x00,0x15, + 0x00,0x1e,0x00,0x26,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00, + 0x76,0x00,0x6d,0x00,0x61,0x00,0x53,0x00,0x44,0x00,0x35,0x00,0x27,0x00,0x19,0x00,0x0c,0x00,0x00,0x00, + 0x00,0x0b,0x00,0x15,0x00,0x1e,0x00,0x26,0x7e,0x00,0x7c,0x00,0x76,0x00,0x6d,0x00,0x61,0x00,0x53,0x00, + 0x44,0x00,0x35,0x00,0x27,0x00,0x19,0x00,0x0c,0x00,0x00,0x00,0x00,0x0b,0x00,0x15,0x00,0x1e,0x00,0x26, + 0x39,0x3f,0x2e,0x41,0x26,0x43,0x20,0x46,0x1b,0x48,0x17,0x4b,0x14,0x4d,0x12,0x4f,0x10,0x51,0x0e,0x53, + 0x0d,0x55,0x0b,0x56,0x0b,0x58,0x09,0x59,0x09,0x5b,0x08,0x5b,0x07,0x5d,0x07,0x5e,0x06,0x5f,0x06,0x60, + 0x71,0x02,0x5b,0x07,0x4c,0x0c,0x3f,0x11,0x36,0x16,0x2e,0x1b,0x29,0x20,0x24,0x23,0x20,0x28,0x1d,0x2b, + 0x19,0x2f,0x17,0x32,0x16,0x35,0x12,0x37,0x12,0x3a,0x10,0x3c,0x0f,0x3f,0x0e,0x41,0x0c,0x42,0x0c,0x45, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x39,0x3f,0x2e,0x41,0x26,0x43,0x20,0x46,0x1b,0x48,0x17,0x4b,0x14,0x4d,0x12,0x4f,0x10,0x51,0x0e,0x53, + 0x0d,0x55,0x0b,0x56,0x0b,0x58,0x09,0x59,0x09,0x5b,0x08,0x5b,0x07,0x5d,0x07,0x5e,0x06,0x5f,0x06,0x60, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0a,0x00,0x13,0x00,0x1b,0x00,0x7e,0x00,0x7c,0x00,0x77,0x00,0x6f, + 0x00,0x65,0x00,0x59,0x00,0x4c,0x00,0x3e,0x00,0x30,0x00,0x23,0x00,0x16,0x00,0x0b,0x00,0x00,0x00,0x0a, + 0x00,0x13,0x00,0x1b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00, + 0x77,0x00,0x6f,0x00,0x65,0x00,0x59,0x00,0x4c,0x00,0x3e,0x00,0x30,0x00,0x23,0x00,0x16,0x00,0x0b,0x00, + 0x00,0x00,0x00,0x0a,0x00,0x13,0x00,0x1b,0x7e,0x00,0x7c,0x00,0x77,0x00,0x6f,0x00,0x65,0x00,0x59,0x00, + 0x4c,0x00,0x3e,0x00,0x30,0x00,0x23,0x00,0x16,0x00,0x0b,0x00,0x00,0x00,0x00,0x0a,0x00,0x13,0x00,0x1b, + 0x39,0x3e,0x2f,0x40,0x28,0x42,0x22,0x45,0x1d,0x47,0x19,0x49,0x16,0x4b,0x14,0x4d,0x11,0x4f,0x10,0x51, + 0x0f,0x53,0x0d,0x54,0x0c,0x55,0x0b,0x57,0x0a,0x58,0x09,0x59,0x09,0x5b,0x08,0x5b,0x07,0x5c,0x07,0x5e, + 0x73,0x02,0x5e,0x05,0x4f,0x0a,0x44,0x0f,0x3a,0x13,0x33,0x18,0x2d,0x1c,0x27,0x20,0x23,0x23,0x20,0x27, + 0x1d,0x2a,0x1a,0x2d,0x18,0x30,0x16,0x33,0x14,0x35,0x12,0x38,0x12,0x3a,0x10,0x3c,0x0f,0x3e,0x0f,0x41, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x39,0x3e,0x2f,0x40,0x28,0x42,0x22,0x45,0x1d,0x47,0x19,0x49,0x16,0x4b,0x14,0x4d,0x11,0x4f,0x10,0x51, + 0x0f,0x53,0x0d,0x54,0x0c,0x55,0x0b,0x57,0x0a,0x58,0x09,0x59,0x09,0x5b,0x08,0x5b,0x07,0x5c,0x07,0x5e, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x09,0x00,0x12,0x00,0x7e,0x00,0x7d,0x00,0x78,0x00,0x71, + 0x00,0x68,0x00,0x5e,0x00,0x52,0x00,0x45,0x00,0x39,0x00,0x2c,0x00,0x20,0x00,0x15,0x00,0x0a,0x00,0x00, + 0x00,0x09,0x00,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x78,0x00,0x71,0x00,0x68,0x00,0x5e,0x00,0x52,0x00,0x45,0x00,0x39,0x00,0x2c,0x00,0x20,0x00,0x15,0x00, + 0x0a,0x00,0x00,0x00,0x00,0x09,0x00,0x12,0x7e,0x00,0x7d,0x00,0x78,0x00,0x71,0x00,0x68,0x00,0x5e,0x00, + 0x52,0x00,0x45,0x00,0x39,0x00,0x2c,0x00,0x20,0x00,0x15,0x00,0x0a,0x00,0x00,0x00,0x00,0x09,0x00,0x12, + 0x3a,0x3e,0x31,0x40,0x29,0x42,0x23,0x44,0x1f,0x46,0x1b,0x48,0x18,0x4a,0x15,0x4c,0x13,0x4d,0x11,0x4f, + 0x10,0x50,0x0f,0x52,0x0d,0x53,0x0d,0x55,0x0b,0x56,0x0b,0x57,0x0a,0x58,0x09,0x59,0x09,0x5b,0x08,0x5b, + 0x74,0x01,0x62,0x05,0x53,0x08,0x47,0x0c,0x3e,0x11,0x37,0x15,0x31,0x19,0x2b,0x1d,0x27,0x20,0x23,0x23, + 0x20,0x26,0x1d,0x2a,0x1b,0x2c,0x19,0x2f,0x16,0x31,0x16,0x34,0x13,0x35,0x12,0x38,0x12,0x3b,0x0f,0x3b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3a,0x3e,0x31,0x40,0x29,0x42,0x23,0x44,0x1f,0x46,0x1b,0x48,0x18,0x4a,0x15,0x4c,0x13,0x4d,0x11,0x4f, + 0x10,0x50,0x0f,0x52,0x0d,0x53,0x0d,0x55,0x0b,0x56,0x0b,0x57,0x0a,0x58,0x09,0x59,0x09,0x5b,0x08,0x5b, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x7e,0x00,0x7d,0x00,0x79,0x00,0x73, + 0x00,0x6b,0x00,0x62,0x00,0x57,0x00,0x4c,0x00,0x40,0x00,0x34,0x00,0x29,0x00,0x1e,0x00,0x13,0x00,0x09, + 0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x79,0x00,0x73,0x00,0x6b,0x00,0x62,0x00,0x57,0x00,0x4c,0x00,0x40,0x00,0x34,0x00,0x29,0x00,0x1e,0x00, + 0x13,0x00,0x09,0x00,0x00,0x00,0x00,0x08,0x7e,0x00,0x7d,0x00,0x79,0x00,0x73,0x00,0x6b,0x00,0x62,0x00, + 0x57,0x00,0x4c,0x00,0x40,0x00,0x34,0x00,0x29,0x00,0x1e,0x00,0x13,0x00,0x09,0x00,0x00,0x00,0x00,0x08, + 0x3a,0x3e,0x32,0x3f,0x2b,0x41,0x25,0x43,0x21,0x45,0x1d,0x46,0x1a,0x48,0x17,0x4a,0x15,0x4c,0x13,0x4e, + 0x11,0x4f,0x10,0x50,0x0f,0x52,0x0e,0x53,0x0d,0x54,0x0c,0x55,0x0b,0x56,0x0b,0x58,0x09,0x58,0x09,0x59, + 0x75,0x01,0x64,0x04,0x56,0x07,0x4b,0x0b,0x42,0x0f,0x3a,0x12,0x34,0x16,0x2f,0x19,0x2a,0x1d,0x26,0x20, + 0x23,0x23,0x21,0x26,0x1d,0x29,0x1b,0x2b,0x19,0x2e,0x18,0x30,0x16,0x32,0x15,0x35,0x12,0x35,0x12,0x38, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3a,0x3e,0x32,0x3f,0x2b,0x41,0x25,0x43,0x21,0x45,0x1d,0x46,0x1a,0x48,0x17,0x4a,0x15,0x4c,0x13,0x4e, + 0x11,0x4f,0x10,0x50,0x0f,0x52,0x0e,0x53,0x0d,0x54,0x0c,0x55,0x0b,0x56,0x0b,0x58,0x09,0x58,0x09,0x59, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00,0x7a,0x00,0x75, + 0x00,0x6e,0x00,0x65,0x00,0x5b,0x00,0x51,0x00,0x46,0x00,0x3b,0x00,0x30,0x00,0x26,0x00,0x1b,0x00,0x12, + 0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x7a,0x00,0x75,0x00,0x6e,0x00,0x65,0x00,0x5b,0x00,0x51,0x00,0x46,0x00,0x3b,0x00,0x30,0x00,0x26,0x00, + 0x1b,0x00,0x12,0x00,0x08,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00,0x7a,0x00,0x75,0x00,0x6e,0x00,0x65,0x00, + 0x5b,0x00,0x51,0x00,0x46,0x00,0x3b,0x00,0x30,0x00,0x26,0x00,0x1b,0x00,0x12,0x00,0x08,0x00,0x00,0x00, + 0x3b,0x3e,0x33,0x3f,0x2c,0x41,0x27,0x42,0x22,0x44,0x1f,0x45,0x1c,0x47,0x19,0x49,0x17,0x4a,0x15,0x4c, + 0x13,0x4e,0x11,0x4f,0x10,0x50,0x0f,0x51,0x0e,0x53,0x0d,0x54,0x0c,0x55,0x0b,0x55,0x0b,0x57,0x0a,0x58, + 0x76,0x01,0x66,0x04,0x58,0x06,0x4d,0x0a,0x45,0x0d,0x3e,0x10,0x37,0x14,0x32,0x17,0x2d,0x1a,0x2a,0x1d, + 0x26,0x21,0x22,0x22,0x21,0x26,0x1d,0x28,0x1c,0x2b,0x19,0x2c,0x19,0x30,0x16,0x30,0x16,0x33,0x14,0x35, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3b,0x3e,0x33,0x3f,0x2c,0x41,0x27,0x42,0x22,0x44,0x1f,0x45,0x1c,0x47,0x19,0x49,0x17,0x4a,0x15,0x4c, + 0x13,0x4e,0x11,0x4f,0x10,0x50,0x0f,0x51,0x0e,0x53,0x0d,0x54,0x0c,0x55,0x0b,0x55,0x0b,0x57,0x0a,0x58, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x3b,0x3e,0x33,0x3f,0x2d,0x40,0x28,0x42,0x24,0x44,0x20,0x45,0x1d,0x46,0x1a,0x48,0x18,0x49,0x16,0x4b, + 0x14,0x4c,0x13,0x4e,0x11,0x4e,0x10,0x50,0x0f,0x51,0x0f,0x53,0x0d,0x53,0x0d,0x55,0x0b,0x55,0x0b,0x56, + 0x77,0x01,0x67,0x03,0x5a,0x05,0x51,0x09,0x48,0x0c,0x40,0x0f,0x3a,0x12,0x35,0x16,0x30,0x18,0x2c,0x1b, + 0x29,0x1d,0x26,0x21,0x22,0x22,0x21,0x26,0x1d,0x27,0x1d,0x2b,0x1a,0x2b,0x19,0x2e,0x17,0x30,0x16,0x31, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3b,0x3e,0x33,0x3f,0x2d,0x40,0x28,0x42,0x24,0x44,0x20,0x45,0x1d,0x46,0x1a,0x48,0x18,0x49,0x16,0x4b, + 0x14,0x4c,0x13,0x4e,0x11,0x4e,0x10,0x50,0x0f,0x51,0x0f,0x53,0x0d,0x53,0x0d,0x55,0x0b,0x55,0x0b,0x56, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x3b,0x3e,0x34,0x3f,0x2e,0x40,0x29,0x41,0x25,0x43,0x21,0x44,0x1e,0x45,0x1c,0x47,0x19,0x48,0x18,0x4a, + 0x15,0x4b,0x14,0x4c,0x13,0x4e,0x11,0x4e,0x11,0x50,0x0f,0x50,0x0f,0x52,0x0d,0x53,0x0d,0x54,0x0c,0x55, + 0x77,0x01,0x68,0x02,0x5d,0x05,0x52,0x07,0x4a,0x0a,0x43,0x0d,0x3d,0x10,0x38,0x12,0x33,0x16,0x2f,0x19, + 0x2b,0x1b,0x28,0x1d,0x26,0x21,0x22,0x22,0x21,0x26,0x1e,0x26,0x1d,0x2a,0x1a,0x2b,0x19,0x2d,0x18,0x30, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3b,0x3e,0x34,0x3f,0x2e,0x40,0x29,0x41,0x25,0x43,0x21,0x44,0x1e,0x45,0x1c,0x47,0x19,0x48,0x18,0x4a, + 0x15,0x4b,0x14,0x4c,0x13,0x4e,0x11,0x4e,0x11,0x50,0x0f,0x50,0x0f,0x52,0x0d,0x53,0x0d,0x54,0x0c,0x55, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x3c,0x3e,0x35,0x3f,0x2f,0x40,0x2a,0x41,0x26,0x42,0x22,0x44,0x20,0x45,0x1d,0x46,0x1b,0x48,0x18,0x48, + 0x17,0x4a,0x15,0x4b,0x13,0x4c,0x13,0x4e,0x11,0x4e,0x11,0x50,0x0f,0x50,0x0f,0x52,0x0d,0x53,0x0d,0x53, + 0x77,0x00,0x6a,0x02,0x5e,0x04,0x55,0x07,0x4c,0x0a,0x45,0x0c,0x40,0x0f,0x3a,0x12,0x35,0x14,0x31,0x16, + 0x2e,0x19,0x2b,0x1c,0x27,0x1d,0x26,0x22,0x21,0x22,0x21,0x25,0x1e,0x26,0x1d,0x29,0x1b,0x2b,0x19,0x2b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3c,0x3e,0x35,0x3f,0x2f,0x40,0x2a,0x41,0x26,0x42,0x22,0x44,0x20,0x45,0x1d,0x46,0x1b,0x48,0x18,0x48, + 0x17,0x4a,0x15,0x4b,0x13,0x4c,0x13,0x4e,0x11,0x4e,0x11,0x50,0x0f,0x50,0x0f,0x52,0x0d,0x53,0x0d,0x53, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x3c,0x3e,0x35,0x3f,0x30,0x3f,0x2b,0x40,0x27,0x42,0x24,0x43,0x21,0x44,0x1e,0x45,0x1c,0x46,0x1a,0x48, + 0x18,0x49,0x16,0x4a,0x15,0x4c,0x13,0x4c,0x13,0x4e,0x11,0x4e,0x11,0x50,0x0f,0x50,0x0f,0x51,0x0e,0x53, + 0x78,0x00,0x6b,0x02,0x60,0x04,0x57,0x06,0x4f,0x09,0x48,0x0c,0x42,0x0e,0x3c,0x10,0x38,0x12,0x34,0x16, + 0x30,0x18,0x2d,0x19,0x2b,0x1d,0x26,0x1e,0x25,0x22,0x21,0x22,0x21,0x25,0x1e,0x26,0x1d,0x28,0x1c,0x2b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3c,0x3e,0x35,0x3f,0x30,0x3f,0x2b,0x40,0x27,0x42,0x24,0x43,0x21,0x44,0x1e,0x45,0x1c,0x46,0x1a,0x48, + 0x18,0x49,0x16,0x4a,0x15,0x4c,0x13,0x4c,0x13,0x4e,0x11,0x4e,0x11,0x50,0x0f,0x50,0x0f,0x51,0x0e,0x53, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x3c,0x3e,0x36,0x3f,0x30,0x3f,0x2c,0x40,0x28,0x41,0x25,0x42,0x22,0x44,0x1f,0x45,0x1d,0x46,0x1b,0x47, + 0x19,0x48,0x18,0x4a,0x15,0x4a,0x15,0x4c,0x13,0x4c,0x13,0x4e,0x11,0x4e,0x11,0x50,0x0f,0x50,0x0f,0x51, + 0x78,0x00,0x6d,0x02,0x61,0x04,0x58,0x05,0x51,0x07,0x4a,0x0a,0x44,0x0c,0x3f,0x0f,0x3a,0x12,0x35,0x14, + 0x32,0x16,0x30,0x19,0x2b,0x19,0x2a,0x1d,0x26,0x1e,0x25,0x22,0x21,0x22,0x21,0x25,0x1e,0x26,0x1d,0x27, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3c,0x3e,0x36,0x3f,0x30,0x3f,0x2c,0x40,0x28,0x41,0x25,0x42,0x22,0x44,0x1f,0x45,0x1d,0x46,0x1b,0x47, + 0x19,0x48,0x18,0x4a,0x15,0x4a,0x15,0x4c,0x13,0x4c,0x13,0x4e,0x11,0x4e,0x11,0x50,0x0f,0x50,0x0f,0x51, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x3c,0x3e,0x37,0x3e,0x31,0x3f,0x2d,0x40,0x29,0x41,0x26,0x42,0x23,0x44,0x20,0x45,0x1e,0x45,0x1c,0x46, + 0x1a,0x48,0x18,0x48,0x17,0x4a,0x15,0x4a,0x14,0x4c,0x13,0x4c,0x12,0x4e,0x11,0x4e,0x11,0x50,0x0f,0x50, + 0x78,0x00,0x6d,0x02,0x63,0x04,0x5a,0x05,0x53,0x07,0x4c,0x0a,0x46,0x0c,0x41,0x0f,0x3c,0x0f,0x38,0x12, + 0x35,0x16,0x30,0x16,0x2e,0x19,0x2b,0x1a,0x29,0x1d,0x26,0x1e,0x25,0x22,0x21,0x22,0x21,0x25,0x1f,0x26, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3c,0x3e,0x37,0x3e,0x31,0x3f,0x2d,0x40,0x29,0x41,0x26,0x42,0x23,0x44,0x20,0x45,0x1e,0x45,0x1c,0x46, + 0x1a,0x48,0x18,0x48,0x17,0x4a,0x15,0x4a,0x14,0x4c,0x13,0x4c,0x12,0x4e,0x11,0x4e,0x11,0x50,0x0f,0x50, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x3c,0x3e,0x37,0x3e,0x32,0x3f,0x2e,0x40,0x2a,0x41,0x27,0x42,0x24,0x43,0x21,0x44,0x1f,0x45,0x1d,0x46, + 0x1b,0x47,0x1a,0x48,0x18,0x49,0x16,0x4a,0x15,0x4b,0x14,0x4c,0x13,0x4d,0x12,0x4e,0x11,0x4e,0x11,0x50, + 0x78,0x00,0x6e,0x01,0x65,0x03,0x5c,0x05,0x54,0x07,0x4e,0x09,0x48,0x0b,0x43,0x0c,0x3e,0x0f,0x3b,0x12, + 0x36,0x12,0x33,0x16,0x30,0x17,0x2d,0x19,0x2b,0x1b,0x28,0x1d,0x26,0x1e,0x25,0x22,0x21,0x22,0x21,0x24, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3c,0x3e,0x37,0x3e,0x32,0x3f,0x2e,0x40,0x2a,0x41,0x27,0x42,0x24,0x43,0x21,0x44,0x1f,0x45,0x1d,0x46, + 0x1b,0x47,0x1a,0x48,0x18,0x49,0x16,0x4a,0x15,0x4b,0x14,0x4c,0x13,0x4d,0x12,0x4e,0x11,0x4e,0x11,0x50, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x3c,0x3e,0x37,0x3e,0x33,0x3f,0x2e,0x3f,0x2b,0x40,0x28,0x41,0x25,0x42,0x22,0x44,0x20,0x45,0x1e,0x45, + 0x1c,0x46,0x1b,0x48,0x19,0x48,0x18,0x4a,0x16,0x4a,0x15,0x4b,0x13,0x4c,0x13,0x4d,0x12,0x4e,0x11,0x4e, + 0x79,0x00,0x6f,0x01,0x66,0x02,0x5d,0x04,0x56,0x06,0x4f,0x07,0x4a,0x0a,0x45,0x0c,0x41,0x0f,0x3b,0x0f, + 0x38,0x12,0x35,0x14,0x31,0x16,0x30,0x18,0x2b,0x19,0x2b,0x1c,0x27,0x1d,0x26,0x1f,0x24,0x22,0x21,0x22, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b,0x00,0x7b, + 0x3c,0x3e,0x37,0x3e,0x33,0x3f,0x2e,0x3f,0x2b,0x40,0x28,0x41,0x25,0x42,0x22,0x44,0x20,0x45,0x1e,0x45, + 0x1c,0x46,0x1b,0x48,0x19,0x48,0x18,0x4a,0x16,0x4a,0x15,0x4b,0x13,0x4c,0x13,0x4d,0x12,0x4e,0x11,0x4e, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x62,0x00,0x6c,0x00,0x72,0x00,0x74,0x00,0x77,0x00,0x79,0x00,0x79,0x00,0x7a,0x00,0x7b,0x00,0x7b,0x00, + 0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7d,0x00,0x7c,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00, + 0x81,0x00,0x82,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x08,0x00,0x44,0x00,0x56,0x00,0x61,0x00,0x67,0x00,0x6b,0x00,0x6e,0x00,0x70,0x00,0x71,0x00,0x73,0x00, + 0x74,0x00,0x75,0x00,0x76,0x00,0x76,0x00,0x77,0x00,0x77,0x00,0x77,0x00,0x78,0x00,0x78,0x00,0x78,0x00, + 0x44,0x00,0x63,0x00,0x6c,0x00,0x71,0x00,0x75,0x00,0x77,0x00,0x79,0x00,0x79,0x00,0x7a,0x00,0x7b,0x00, + 0x7b,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7c,0x00,0x7d,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x4c,0x0b,0x57,0x06,0x5f,0x03,0x63,0x02,0x68,0x02,0x6b,0x01,0x6d,0x01,0x6e,0x01,0x71,0x00,0x72,0x00, + 0x73,0x00,0x74,0x00,0x75,0x00,0x76,0x00,0x76,0x00,0x76,0x00,0x78,0x00,0x78,0x00,0x78,0x00,0x79,0x00, + 0x82,0x00,0x82,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x40,0x17,0x17,0x2c,0x0c,0x3b,0x07,0x45,0x05,0x4d,0x04,0x53,0x03,0x57,0x02,0x5c,0x02,0x5e,0x01, + 0x61,0x01,0x63,0x01,0x66,0x01,0x67,0x01,0x68,0x00,0x69,0x00,0x6b,0x00,0x6c,0x00,0x6d,0x00,0x6e,0x00, + 0x41,0x20,0x4d,0x0b,0x58,0x06,0x5e,0x03,0x64,0x02,0x68,0x02,0x6b,0x01,0x6c,0x01,0x6f,0x01,0x71,0x00, + 0x72,0x00,0x73,0x00,0x74,0x00,0x75,0x00,0x76,0x00,0x75,0x00,0x77,0x00,0x78,0x00,0x78,0x00,0x78,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x47,0x15,0x4f,0x0d,0x56,0x09,0x59,0x06,0x5f,0x05,0x62,0x04,0x65,0x03,0x67,0x02,0x69,0x02,0x6b,0x02, + 0x6c,0x02,0x6e,0x01,0x6f,0x01,0x70,0x01,0x71,0x01,0x70,0x01,0x72,0x00,0x73,0x00,0x74,0x00,0x74,0x00, + 0x83,0x00,0x82,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x55,0x0c,0x2c,0x1b,0x1b,0x27,0x12,0x32,0x0d,0x3a,0x0b,0x41,0x08,0x47,0x07,0x4c,0x05,0x4f,0x05, + 0x53,0x04,0x56,0x04,0x58,0x03,0x5a,0x02,0x5d,0x02,0x5e,0x02,0x60,0x02,0x61,0x01,0x63,0x01,0x64,0x01, + 0x41,0x2a,0x47,0x16,0x4f,0x0d,0x54,0x09,0x5b,0x06,0x5f,0x05,0x62,0x04,0x64,0x03,0x67,0x02,0x69,0x02, + 0x6b,0x02,0x6c,0x02,0x6e,0x01,0x6f,0x01,0x70,0x01,0x70,0x01,0x71,0x01,0x72,0x00,0x73,0x00,0x74,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x45,0x1d,0x4a,0x14,0x50,0x0e,0x54,0x0b,0x59,0x08,0x5c,0x07,0x5f,0x06,0x60,0x05,0x64,0x04,0x65,0x03, + 0x67,0x03,0x68,0x02,0x6a,0x02,0x6b,0x02,0x6c,0x02,0x6c,0x02,0x6e,0x02,0x6f,0x01,0x70,0x01,0x70,0x01, + 0x83,0x00,0x82,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x60,0x08,0x3b,0x12,0x28,0x1d,0x1d,0x26,0x16,0x2e,0x11,0x34,0x0e,0x3a,0x0c,0x3f,0x0a,0x44,0x08, + 0x47,0x07,0x4b,0x06,0x4d,0x05,0x51,0x05,0x52,0x04,0x55,0x04,0x57,0x04,0x58,0x04,0x5a,0x03,0x5c,0x02, + 0x42,0x30,0x45,0x1d,0x4b,0x14,0x4f,0x0e,0x55,0x0b,0x59,0x08,0x5c,0x07,0x5e,0x06,0x61,0x05,0x64,0x04, + 0x65,0x03,0x67,0x03,0x68,0x02,0x6a,0x02,0x6b,0x02,0x6b,0x02,0x6d,0x02,0x6e,0x02,0x6f,0x01,0x70,0x01, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x44,0x22,0x48,0x19,0x4d,0x13,0x50,0x0f,0x54,0x0c,0x57,0x0a,0x5a,0x08,0x5c,0x07,0x5f,0x06,0x61,0x05, + 0x63,0x05,0x64,0x04,0x65,0x03,0x67,0x03,0x68,0x03,0x68,0x02,0x6a,0x02,0x6b,0x02,0x6c,0x02,0x6d,0x02, + 0x83,0x00,0x82,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x66,0x05,0x45,0x0d,0x32,0x16,0x26,0x1e,0x1e,0x25,0x18,0x2b,0x14,0x31,0x11,0x36,0x0f,0x3a,0x0c, + 0x3e,0x0b,0x42,0x0a,0x45,0x09,0x47,0x07,0x4a,0x07,0x4c,0x06,0x4f,0x05,0x51,0x05,0x52,0x05,0x54,0x04, + 0x41,0x33,0x44,0x22,0x48,0x19,0x4c,0x13,0x51,0x0f,0x54,0x0c,0x57,0x0a,0x59,0x08,0x5d,0x07,0x5f,0x06, + 0x61,0x05,0x63,0x05,0x64,0x04,0x65,0x03,0x67,0x03,0x67,0x03,0x69,0x02,0x6a,0x02,0x6b,0x02,0x6c,0x02, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x43,0x26,0x47,0x1d,0x4a,0x17,0x4d,0x12,0x51,0x0f,0x54,0x0d,0x56,0x0b,0x58,0x09,0x5b,0x08,0x5d,0x07, + 0x5f,0x06,0x60,0x06,0x62,0x05,0x63,0x05,0x64,0x04,0x65,0x03,0x67,0x03,0x67,0x03,0x68,0x03,0x69,0x02, + 0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x6a,0x04,0x4d,0x0b,0x3a,0x11,0x2e,0x18,0x25,0x1f,0x1f,0x24,0x1a,0x29,0x16,0x2e,0x13,0x33,0x11, + 0x37,0x0f,0x3a,0x0d,0x3d,0x0c,0x40,0x0a,0x43,0x0a,0x45,0x09,0x48,0x07,0x4a,0x07,0x4c,0x07,0x4e,0x06, + 0x41,0x35,0x43,0x26,0x47,0x1d,0x49,0x17,0x4e,0x12,0x51,0x0f,0x54,0x0d,0x55,0x0b,0x59,0x09,0x5b,0x08, + 0x5d,0x07,0x5f,0x06,0x60,0x06,0x62,0x05,0x63,0x05,0x63,0x04,0x65,0x03,0x67,0x03,0x67,0x03,0x68,0x03, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x43,0x29,0x45,0x20,0x49,0x1a,0x4b,0x15,0x4f,0x12,0x51,0x0f,0x54,0x0d,0x55,0x0b,0x58,0x0a,0x5a,0x09, + 0x5b,0x08,0x5d,0x07,0x5f,0x06,0x60,0x06,0x61,0x05,0x62,0x05,0x64,0x05,0x65,0x04,0x65,0x03,0x66,0x03, + 0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x6d,0x03,0x52,0x08,0x41,0x0e,0x34,0x14,0x2b,0x1a,0x24,0x1f,0x1f,0x24,0x1b,0x28,0x17,0x2d,0x15, + 0x31,0x12,0x34,0x10,0x37,0x0f,0x3a,0x0d,0x3d,0x0c,0x40,0x0b,0x42,0x0a,0x44,0x0a,0x46,0x09,0x47,0x07, + 0x41,0x36,0x43,0x29,0x46,0x20,0x48,0x1a,0x4c,0x15,0x4f,0x12,0x51,0x0f,0x53,0x0d,0x56,0x0b,0x58,0x0a, + 0x5a,0x09,0x5b,0x08,0x5d,0x07,0x5f,0x06,0x60,0x06,0x60,0x05,0x62,0x05,0x64,0x05,0x65,0x04,0x65,0x03, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x43,0x2b,0x45,0x23,0x48,0x1d,0x49,0x18,0x4d,0x14,0x4f,0x12,0x51,0x10,0x53,0x0e,0x55,0x0c,0x57,0x0b, + 0x59,0x0a,0x5a,0x09,0x5c,0x08,0x5d,0x07,0x5f,0x07,0x5f,0x06,0x61,0x06,0x62,0x05,0x63,0x05,0x64,0x05, + 0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x6f,0x02,0x57,0x07,0x47,0x0c,0x3a,0x11,0x31,0x16,0x29,0x1b,0x24,0x20,0x20,0x23,0x1c,0x28,0x19, + 0x2b,0x16,0x2f,0x14,0x32,0x12,0x35,0x10,0x38,0x0f,0x3a,0x0e,0x3c,0x0c,0x3f,0x0c,0x41,0x0b,0x42,0x0a, + 0x41,0x37,0x43,0x2b,0x45,0x23,0x47,0x1d,0x4a,0x18,0x4d,0x14,0x4f,0x12,0x51,0x10,0x53,0x0e,0x55,0x0c, + 0x57,0x0b,0x59,0x0a,0x5a,0x09,0x5c,0x08,0x5d,0x07,0x5e,0x07,0x60,0x06,0x61,0x06,0x62,0x05,0x63,0x05, + 0x1f,0x00,0x3f,0x00,0x66,0x00,0x72,0x00,0x78,0x00,0x7a,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00, + 0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x1f,0x1f,0x3f,0x00,0x66,0x00,0x72,0x00, + 0x78,0x00,0x7a,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00, + 0x7e,0x00,0x7e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x58,0x00, + 0x70,0x00,0x77,0x00,0x79,0x00,0x7b,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7e,0x00,0x7e,0x00, + 0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x1f,0x1f,0x3f,0x00,0x66,0x00,0x72,0x00,0x78,0x00,0x7a,0x00, + 0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00, + 0x43,0x2d,0x44,0x25,0x46,0x1f,0x48,0x1b,0x4b,0x17,0x4d,0x14,0x50,0x12,0x51,0x10,0x53,0x0e,0x55,0x0c, + 0x57,0x0b,0x58,0x0b,0x5a,0x09,0x5b,0x09,0x5c,0x08,0x5c,0x07,0x5f,0x07,0x60,0x06,0x61,0x06,0x62,0x06, + 0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x71,0x02,0x5b,0x05,0x4b,0x0a,0x3f,0x0f,0x36,0x13,0x2e,0x18,0x29,0x1c,0x23,0x20,0x20,0x23,0x1d, + 0x27,0x19,0x2a,0x17,0x2d,0x16,0x30,0x12,0x33,0x12,0x35,0x10,0x38,0x0f,0x3b,0x0e,0x3c,0x0c,0x3e,0x0c, + 0x41,0x38,0x43,0x2d,0x44,0x25,0x45,0x1f,0x49,0x1b,0x4b,0x17,0x4d,0x14,0x4f,0x11,0x51,0x10,0x53,0x0e, + 0x55,0x0c,0x57,0x0b,0x58,0x0b,0x5a,0x09,0x5b,0x09,0x5b,0x08,0x5e,0x07,0x5f,0x07,0x60,0x06,0x61,0x06, + 0x00,0x00,0x0a,0x00,0x3f,0x00,0x5c,0x00,0x6a,0x00,0x71,0x00,0x75,0x00,0x78,0x00,0x79,0x00,0x7a,0x00, + 0x7b,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7d,0x00,0x00,0x3f,0x0a,0x0a,0x3f,0x00,0x5c,0x00, + 0x6a,0x00,0x71,0x00,0x75,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x7b,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00, + 0x7d,0x00,0x7d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x58,0x00,0x44,0x00, + 0x55,0x00,0x67,0x00,0x6e,0x00,0x72,0x00,0x75,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x7b,0x00,0x7c,0x00, + 0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7d,0x00,0x00,0x3f,0x0a,0x0a,0x3f,0x00,0x5c,0x00,0x6a,0x00,0x71,0x00, + 0x75,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x7b,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7d,0x00, + 0x42,0x2f,0x44,0x27,0x46,0x22,0x47,0x1d,0x4a,0x19,0x4c,0x16,0x4e,0x13,0x4f,0x11,0x52,0x10,0x53,0x0e, + 0x55,0x0d,0x56,0x0c,0x58,0x0b,0x59,0x0a,0x5a,0x09,0x5b,0x09,0x5c,0x07,0x5e,0x07,0x5f,0x07,0x5f,0x06, + 0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x73,0x01,0x5e,0x05,0x4f,0x08,0x44,0x0c,0x3a,0x10,0x33,0x15,0x2d,0x19,0x28,0x1d,0x23,0x20,0x20, + 0x23,0x1d,0x26,0x1a,0x2a,0x18,0x2c,0x16,0x2f,0x14,0x31,0x12,0x34,0x12,0x35,0x0f,0x38,0x0f,0x3b,0x0f, + 0x41,0x39,0x42,0x2f,0x44,0x27,0x45,0x22,0x48,0x1d,0x4a,0x19,0x4c,0x16,0x4d,0x14,0x50,0x11,0x52,0x10, + 0x53,0x0e,0x55,0x0d,0x56,0x0c,0x58,0x0b,0x59,0x0a,0x59,0x09,0x5c,0x09,0x5c,0x07,0x5e,0x07,0x5f,0x07, + 0x00,0x00,0x00,0x00,0x03,0x00,0x2d,0x00,0x48,0x00,0x59,0x00,0x63,0x00,0x6a,0x00,0x6e,0x00,0x72,0x00, + 0x74,0x00,0x76,0x00,0x77,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x00,0x66,0x00,0x3f,0x03,0x03,0x2d,0x00, + 0x48,0x00,0x59,0x00,0x63,0x00,0x6a,0x00,0x6e,0x00,0x72,0x00,0x74,0x00,0x76,0x00,0x77,0x00,0x78,0x00, + 0x79,0x00,0x7a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x55,0x00, + 0x20,0x00,0x3e,0x00,0x50,0x00,0x5a,0x00,0x63,0x00,0x6a,0x00,0x6e,0x00,0x72,0x00,0x74,0x00,0x76,0x00, + 0x77,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x00,0x66,0x00,0x3f,0x03,0x03,0x2d,0x00,0x48,0x00,0x59,0x00, + 0x63,0x00,0x6a,0x00,0x6e,0x00,0x72,0x00,0x74,0x00,0x76,0x00,0x77,0x00,0x78,0x00,0x79,0x00,0x7a,0x00, + 0x42,0x30,0x44,0x29,0x45,0x23,0x46,0x1f,0x49,0x1b,0x4b,0x18,0x4c,0x15,0x4d,0x13,0x50,0x11,0x52,0x10, + 0x53,0x0e,0x55,0x0d,0x56,0x0c,0x57,0x0b,0x59,0x0b,0x59,0x09,0x5b,0x09,0x5c,0x09,0x5c,0x07,0x5e,0x07, + 0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x73,0x01,0x61,0x04,0x52,0x07,0x47,0x0b,0x3e,0x0f,0x37,0x12,0x31,0x16,0x2b,0x19,0x27,0x1d,0x23, + 0x20,0x20,0x23,0x1d,0x26,0x1b,0x29,0x19,0x2b,0x16,0x2e,0x16,0x30,0x13,0x32,0x12,0x35,0x12,0x36,0x0f, + 0x41,0x39,0x42,0x30,0x44,0x29,0x44,0x23,0x47,0x1f,0x49,0x1b,0x4b,0x18,0x4c,0x15,0x4e,0x13,0x50,0x11, + 0x52,0x10,0x53,0x0e,0x55,0x0d,0x56,0x0c,0x57,0x0b,0x57,0x0b,0x5a,0x09,0x5b,0x09,0x5c,0x09,0x5c,0x07, + 0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x22,0x00,0x3a,0x00,0x4a,0x00,0x56,0x00,0x5e,0x00,0x64,0x00, + 0x69,0x00,0x6d,0x00,0x6f,0x00,0x71,0x00,0x73,0x00,0x75,0x00,0x00,0x72,0x00,0x5c,0x00,0x2d,0x01,0x01, + 0x22,0x00,0x3a,0x00,0x4a,0x00,0x56,0x00,0x5e,0x00,0x64,0x00,0x69,0x00,0x6d,0x00,0x6f,0x00,0x71,0x00, + 0x73,0x00,0x75,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x00,0x67,0x00, + 0x3e,0x00,0x0d,0x00,0x28,0x00,0x3a,0x00,0x4a,0x00,0x56,0x00,0x5e,0x00,0x64,0x00,0x69,0x00,0x6d,0x00, + 0x6f,0x00,0x71,0x00,0x73,0x00,0x75,0x00,0x00,0x72,0x00,0x5c,0x00,0x2d,0x01,0x01,0x22,0x00,0x3a,0x00, + 0x4a,0x00,0x56,0x00,0x5e,0x00,0x64,0x00,0x69,0x00,0x6d,0x00,0x6f,0x00,0x71,0x00,0x73,0x00,0x75,0x00, + 0x42,0x32,0x44,0x2a,0x45,0x25,0x46,0x21,0x48,0x1d,0x4a,0x1a,0x4b,0x17,0x4c,0x15,0x4e,0x13,0x50,0x11, + 0x52,0x10,0x53,0x0e,0x55,0x0d,0x55,0x0c,0x57,0x0c,0x57,0x0b,0x5a,0x0a,0x5a,0x09,0x5b,0x09,0x5c,0x09, + 0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x74,0x01,0x64,0x04,0x55,0x06,0x4a,0x0a,0x42,0x0d,0x3a,0x10,0x34,0x14,0x2f,0x17,0x2a,0x1a,0x26, + 0x1d,0x23,0x21,0x21,0x22,0x1d,0x26,0x1b,0x28,0x19,0x2b,0x18,0x2c,0x16,0x30,0x15,0x30,0x12,0x33,0x12, + 0x41,0x3a,0x42,0x32,0x44,0x2a,0x44,0x25,0x46,0x21,0x48,0x1d,0x4a,0x1a,0x4b,0x17,0x4d,0x15,0x4e,0x13, + 0x50,0x11,0x52,0x10,0x53,0x0e,0x55,0x0d,0x55,0x0c,0x56,0x0c,0x58,0x0b,0x5a,0x0a,0x5a,0x09,0x5b,0x09, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1b,0x00,0x30,0x00,0x3f,0x00,0x4b,0x00,0x54,0x00, + 0x5b,0x00,0x61,0x00,0x65,0x00,0x68,0x00,0x6b,0x00,0x6e,0x00,0x00,0x78,0x00,0x6a,0x00,0x48,0x00,0x22, + 0x00,0x00,0x1b,0x00,0x30,0x00,0x3f,0x00,0x4b,0x00,0x54,0x00,0x5b,0x00,0x61,0x00,0x65,0x00,0x68,0x00, + 0x6b,0x00,0x6e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x79,0x00,0x6e,0x00, + 0x50,0x00,0x28,0x00,0x01,0x00,0x1b,0x00,0x30,0x00,0x3f,0x00,0x4b,0x00,0x54,0x00,0x5b,0x00,0x61,0x00, + 0x65,0x00,0x68,0x00,0x6b,0x00,0x6e,0x00,0x00,0x78,0x00,0x6a,0x00,0x48,0x00,0x22,0x00,0x00,0x1b,0x00, + 0x30,0x00,0x3f,0x00,0x4b,0x00,0x54,0x00,0x5b,0x00,0x61,0x00,0x65,0x00,0x68,0x00,0x6b,0x00,0x6e,0x00, + 0x42,0x32,0x43,0x2c,0x44,0x26,0x45,0x22,0x48,0x1f,0x49,0x1b,0x4b,0x19,0x4c,0x16,0x4e,0x15,0x4f,0x13, + 0x50,0x11,0x52,0x10,0x53,0x0e,0x55,0x0e,0x55,0x0c,0x56,0x0c,0x57,0x0b,0x59,0x0b,0x5a,0x0a,0x5a,0x09, + 0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x75,0x01,0x65,0x03,0x58,0x05,0x4d,0x09,0x45,0x0c,0x3e,0x0f,0x37,0x12,0x32,0x16,0x2d,0x18,0x2a, + 0x1b,0x26,0x1d,0x22,0x21,0x21,0x22,0x1d,0x26,0x1c,0x27,0x19,0x2b,0x19,0x2b,0x16,0x2e,0x16,0x30,0x14, + 0x41,0x3a,0x42,0x32,0x43,0x2c,0x44,0x26,0x46,0x22,0x48,0x1f,0x49,0x1b,0x4a,0x19,0x4c,0x16,0x4e,0x15, + 0x4f,0x13,0x50,0x11,0x52,0x10,0x53,0x0e,0x55,0x0e,0x54,0x0c,0x57,0x0c,0x57,0x0b,0x59,0x0b,0x5a,0x0a, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x16,0x00,0x28,0x00,0x37,0x00,0x42,0x00, + 0x4b,0x00,0x53,0x00,0x59,0x00,0x5e,0x00,0x62,0x00,0x65,0x00,0x00,0x7a,0x00,0x71,0x00,0x59,0x00,0x3a, + 0x00,0x1b,0x00,0x00,0x16,0x00,0x28,0x00,0x37,0x00,0x42,0x00,0x4b,0x00,0x53,0x00,0x59,0x00,0x5e,0x00, + 0x62,0x00,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7b,0x00,0x72,0x00, + 0x5a,0x00,0x3a,0x00,0x1b,0x00,0x01,0x00,0x16,0x00,0x28,0x00,0x37,0x00,0x42,0x00,0x4b,0x00,0x53,0x00, + 0x59,0x00,0x5e,0x00,0x62,0x00,0x65,0x00,0x00,0x7a,0x00,0x71,0x00,0x59,0x00,0x3a,0x00,0x1b,0x00,0x00, + 0x16,0x00,0x28,0x00,0x37,0x00,0x42,0x00,0x4b,0x00,0x53,0x00,0x59,0x00,0x5e,0x00,0x62,0x00,0x65,0x00, + 0x42,0x33,0x43,0x2d,0x44,0x28,0x45,0x23,0x47,0x20,0x48,0x1d,0x4a,0x1a,0x4a,0x18,0x4c,0x16,0x4e,0x14, + 0x4f,0x13,0x50,0x11,0x52,0x10,0x53,0x0e,0x55,0x0e,0x54,0x0d,0x57,0x0c,0x57,0x0b,0x58,0x0b,0x5a,0x0b, + 0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x76,0x01,0x67,0x02,0x5a,0x05,0x50,0x07,0x47,0x0a,0x40,0x0d,0x3a,0x10,0x35,0x12,0x30,0x16,0x2c, + 0x19,0x29,0x1b,0x26,0x1d,0x22,0x21,0x21,0x22,0x1d,0x26,0x1d,0x26,0x1a,0x2a,0x19,0x2b,0x17,0x2d,0x16, + 0x41,0x3b,0x42,0x33,0x43,0x2d,0x44,0x28,0x45,0x23,0x47,0x20,0x48,0x1d,0x49,0x1a,0x4b,0x18,0x4c,0x16, + 0x4e,0x14,0x4f,0x13,0x50,0x11,0x52,0x10,0x53,0x0e,0x54,0x0e,0x55,0x0d,0x57,0x0c,0x57,0x0b,0x58,0x0b, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x13,0x00,0x23,0x00,0x30,0x00, + 0x3b,0x00,0x44,0x00,0x4c,0x00,0x52,0x00,0x57,0x00,0x5b,0x00,0x00,0x7c,0x00,0x75,0x00,0x63,0x00,0x4a, + 0x00,0x30,0x00,0x16,0x00,0x00,0x13,0x00,0x23,0x00,0x30,0x00,0x3b,0x00,0x44,0x00,0x4c,0x00,0x52,0x00, + 0x57,0x00,0x5b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x75,0x00, + 0x63,0x00,0x4a,0x00,0x30,0x00,0x16,0x00,0x00,0x00,0x13,0x00,0x23,0x00,0x30,0x00,0x3b,0x00,0x44,0x00, + 0x4c,0x00,0x52,0x00,0x57,0x00,0x5b,0x00,0x00,0x7c,0x00,0x75,0x00,0x63,0x00,0x4a,0x00,0x30,0x00,0x16, + 0x00,0x00,0x13,0x00,0x23,0x00,0x30,0x00,0x3b,0x00,0x44,0x00,0x4c,0x00,0x52,0x00,0x57,0x00,0x5b,0x00, + 0x42,0x34,0x43,0x2e,0x44,0x29,0x45,0x25,0x46,0x21,0x48,0x1e,0x49,0x1b,0x4a,0x19,0x4c,0x17,0x4d,0x15, + 0x4e,0x14,0x50,0x13,0x50,0x11,0x52,0x11,0x52,0x0f,0x53,0x0e,0x55,0x0d,0x56,0x0c,0x57,0x0c,0x57,0x0b, + 0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x77,0x00,0x68,0x02,0x5c,0x05,0x52,0x07,0x4a,0x0a,0x43,0x0c,0x3d,0x0f,0x37,0x12,0x33,0x14,0x2f, + 0x16,0x2b,0x19,0x28,0x1c,0x26,0x1d,0x22,0x21,0x22,0x21,0x1e,0x25,0x1d,0x26,0x1a,0x29,0x19,0x2b,0x18, + 0x41,0x3b,0x42,0x34,0x43,0x2e,0x44,0x29,0x45,0x25,0x46,0x21,0x48,0x1e,0x48,0x1b,0x4b,0x19,0x4c,0x17, + 0x4d,0x15,0x4e,0x14,0x50,0x13,0x50,0x11,0x52,0x11,0x51,0x0f,0x54,0x0e,0x55,0x0d,0x56,0x0c,0x57,0x0c, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x1f,0x00, + 0x2b,0x00,0x35,0x00,0x3e,0x00,0x45,0x00,0x4c,0x00,0x51,0x00,0x00,0x7c,0x00,0x78,0x00,0x6a,0x00,0x56, + 0x00,0x3f,0x00,0x28,0x00,0x13,0x00,0x00,0x10,0x00,0x1f,0x00,0x2b,0x00,0x35,0x00,0x3e,0x00,0x45,0x00, + 0x4c,0x00,0x51,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x78,0x00, + 0x6a,0x00,0x56,0x00,0x3f,0x00,0x28,0x00,0x13,0x00,0x00,0x00,0x10,0x00,0x1f,0x00,0x2b,0x00,0x35,0x00, + 0x3e,0x00,0x45,0x00,0x4c,0x00,0x51,0x00,0x00,0x7c,0x00,0x78,0x00,0x6a,0x00,0x56,0x00,0x3f,0x00,0x28, + 0x00,0x13,0x00,0x00,0x10,0x00,0x1f,0x00,0x2b,0x00,0x35,0x00,0x3e,0x00,0x45,0x00,0x4c,0x00,0x51,0x00, + 0x42,0x34,0x43,0x2f,0x44,0x2a,0x44,0x26,0x46,0x22,0x47,0x1f,0x48,0x1d,0x49,0x1a,0x4b,0x18,0x4c,0x17, + 0x4e,0x15,0x4e,0x13,0x50,0x13,0x50,0x11,0x52,0x11,0x51,0x0f,0x54,0x0e,0x55,0x0d,0x56,0x0c,0x57,0x0c, + 0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x77,0x00,0x69,0x02,0x5e,0x04,0x55,0x06,0x4c,0x09,0x45,0x0c,0x3f,0x0e,0x3a,0x10,0x35,0x12,0x31, + 0x16,0x2e,0x18,0x2b,0x19,0x27,0x1d,0x26,0x1e,0x22,0x21,0x22,0x21,0x1e,0x25,0x1d,0x26,0x1b,0x28,0x19, + 0x41,0x3b,0x42,0x34,0x43,0x2f,0x43,0x2a,0x45,0x26,0x46,0x22,0x47,0x1f,0x48,0x1d,0x4a,0x1a,0x4b,0x18, + 0x4c,0x17,0x4e,0x15,0x4e,0x13,0x50,0x13,0x50,0x11,0x51,0x11,0x52,0x0f,0x54,0x0e,0x55,0x0d,0x56,0x0c, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0e,0x00, + 0x1b,0x00,0x27,0x00,0x30,0x00,0x39,0x00,0x40,0x00,0x46,0x00,0x00,0x7d,0x00,0x79,0x00,0x6e,0x00,0x5e, + 0x00,0x4b,0x00,0x37,0x00,0x23,0x00,0x10,0x00,0x00,0x0e,0x00,0x1b,0x00,0x27,0x00,0x30,0x00,0x39,0x00, + 0x40,0x00,0x46,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x79,0x00, + 0x6e,0x00,0x5e,0x00,0x4b,0x00,0x37,0x00,0x23,0x00,0x10,0x00,0x00,0x00,0x0e,0x00,0x1b,0x00,0x27,0x00, + 0x30,0x00,0x39,0x00,0x40,0x00,0x46,0x00,0x00,0x7d,0x00,0x79,0x00,0x6e,0x00,0x5e,0x00,0x4b,0x00,0x37, + 0x00,0x23,0x00,0x10,0x00,0x00,0x0e,0x00,0x1b,0x00,0x27,0x00,0x30,0x00,0x39,0x00,0x40,0x00,0x46,0x00, + 0x42,0x35,0x43,0x30,0x44,0x2b,0x44,0x27,0x45,0x24,0x46,0x21,0x48,0x1e,0x48,0x1c,0x4b,0x1a,0x4b,0x18, + 0x4c,0x16,0x4e,0x15,0x4e,0x13,0x50,0x12,0x50,0x11,0x51,0x11,0x52,0x0f,0x54,0x0e,0x55,0x0e,0x55,0x0c, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x77,0x00,0x6b,0x02,0x60,0x04,0x57,0x05,0x4f,0x07,0x48,0x0a,0x42,0x0c,0x3c,0x0f,0x38,0x12,0x34, + 0x14,0x30,0x16,0x2c,0x19,0x2b,0x19,0x26,0x1d,0x25,0x1e,0x22,0x21,0x22,0x21,0x1e,0x25,0x1d,0x26,0x1c, + 0x41,0x3b,0x42,0x35,0x43,0x30,0x43,0x2b,0x44,0x27,0x45,0x24,0x46,0x21,0x47,0x1e,0x49,0x1c,0x4b,0x1a, + 0x4b,0x18,0x4c,0x16,0x4e,0x15,0x4e,0x13,0x50,0x12,0x50,0x11,0x52,0x11,0x52,0x0f,0x54,0x0e,0x55,0x0e, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x0d,0x00,0x19,0x00,0x23,0x00,0x2c,0x00,0x34,0x00,0x3b,0x00,0x00,0x7d,0x00,0x7a,0x00,0x72,0x00,0x64, + 0x00,0x54,0x00,0x42,0x00,0x30,0x00,0x1f,0x00,0x0e,0x00,0x00,0x0d,0x00,0x19,0x00,0x23,0x00,0x2c,0x00, + 0x34,0x00,0x3b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x7a,0x00, + 0x72,0x00,0x64,0x00,0x54,0x00,0x42,0x00,0x30,0x00,0x1f,0x00,0x0e,0x00,0x00,0x00,0x0d,0x00,0x19,0x00, + 0x23,0x00,0x2c,0x00,0x34,0x00,0x3b,0x00,0x00,0x7d,0x00,0x7a,0x00,0x72,0x00,0x64,0x00,0x54,0x00,0x42, + 0x00,0x30,0x00,0x1f,0x00,0x0e,0x00,0x00,0x0d,0x00,0x19,0x00,0x23,0x00,0x2c,0x00,0x34,0x00,0x3b,0x00, + 0x42,0x36,0x43,0x30,0x44,0x2c,0x44,0x28,0x45,0x25,0x46,0x22,0x48,0x1f,0x48,0x1d,0x49,0x1a,0x4b,0x19, + 0x4c,0x18,0x4d,0x15,0x4e,0x15,0x4f,0x13,0x50,0x12,0x50,0x11,0x52,0x11,0x52,0x0f,0x54,0x0e,0x55,0x0e, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x77,0x00,0x6c,0x02,0x61,0x04,0x58,0x05,0x51,0x07,0x4a,0x0a,0x44,0x0c,0x3f,0x0f,0x3a,0x10,0x35, + 0x12,0x32,0x16,0x30,0x16,0x2b,0x19,0x2a,0x1a,0x26,0x1d,0x25,0x1e,0x22,0x21,0x22,0x21,0x1e,0x25,0x1d, + 0x41,0x3b,0x42,0x36,0x43,0x30,0x43,0x2c,0x44,0x28,0x45,0x25,0x46,0x22,0x47,0x1f,0x49,0x1d,0x49,0x1a, + 0x4b,0x19,0x4c,0x18,0x4d,0x15,0x4e,0x15,0x4f,0x13,0x4f,0x12,0x51,0x11,0x52,0x11,0x52,0x0f,0x54,0x0e, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x0c,0x00,0x16,0x00,0x20,0x00,0x29,0x00,0x30,0x00,0x00,0x7e,0x00,0x7b,0x00,0x74,0x00,0x69, + 0x00,0x5b,0x00,0x4b,0x00,0x3b,0x00,0x2b,0x00,0x1b,0x00,0x0d,0x00,0x00,0x0c,0x00,0x16,0x00,0x20,0x00, + 0x29,0x00,0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7b,0x00, + 0x74,0x00,0x69,0x00,0x5b,0x00,0x4b,0x00,0x3b,0x00,0x2b,0x00,0x1b,0x00,0x0d,0x00,0x00,0x00,0x0c,0x00, + 0x16,0x00,0x20,0x00,0x29,0x00,0x30,0x00,0x00,0x7e,0x00,0x7b,0x00,0x74,0x00,0x69,0x00,0x5b,0x00,0x4b, + 0x00,0x3b,0x00,0x2b,0x00,0x1b,0x00,0x0d,0x00,0x00,0x0c,0x00,0x16,0x00,0x20,0x00,0x29,0x00,0x30,0x00, + 0x42,0x36,0x42,0x31,0x43,0x2d,0x44,0x29,0x45,0x26,0x46,0x23,0x47,0x20,0x47,0x1e,0x49,0x1c,0x4b,0x1a, + 0x4b,0x18,0x4c,0x17,0x4d,0x15,0x4e,0x14,0x4f,0x13,0x4f,0x12,0x51,0x11,0x52,0x11,0x52,0x0f,0x54,0x0e, + 0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x78,0x00,0x6d,0x01,0x62,0x03,0x5a,0x05,0x52,0x07,0x4c,0x09,0x46,0x0b,0x41,0x0c,0x3c,0x0f,0x38, + 0x12,0x35,0x12,0x30,0x16,0x2e,0x17,0x2b,0x19,0x29,0x1b,0x26,0x1d,0x25,0x1e,0x22,0x21,0x22,0x21,0x1f, + 0x41,0x3c,0x42,0x36,0x42,0x31,0x43,0x2d,0x44,0x29,0x45,0x26,0x46,0x23,0x46,0x20,0x48,0x1e,0x49,0x1c, + 0x4b,0x1a,0x4b,0x18,0x4c,0x17,0x4d,0x15,0x4e,0x14,0x4e,0x13,0x50,0x12,0x51,0x11,0x52,0x11,0x52,0x0f, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x0b,0x00,0x15,0x00,0x1e,0x00,0x26,0x00,0x00,0x7e,0x00,0x7c,0x00,0x76,0x00,0x6d, + 0x00,0x61,0x00,0x53,0x00,0x44,0x00,0x35,0x00,0x27,0x00,0x19,0x00,0x0c,0x00,0x00,0x0b,0x00,0x15,0x00, + 0x1e,0x00,0x26,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00, + 0x76,0x00,0x6d,0x00,0x61,0x00,0x53,0x00,0x44,0x00,0x35,0x00,0x27,0x00,0x19,0x00,0x0c,0x00,0x00,0x00, + 0x0b,0x00,0x15,0x00,0x1e,0x00,0x26,0x00,0x00,0x7e,0x00,0x7c,0x00,0x76,0x00,0x6d,0x00,0x61,0x00,0x53, + 0x00,0x44,0x00,0x35,0x00,0x27,0x00,0x19,0x00,0x0c,0x00,0x00,0x0b,0x00,0x15,0x00,0x1e,0x00,0x26,0x00, + 0x42,0x37,0x42,0x32,0x43,0x2d,0x44,0x2a,0x45,0x27,0x45,0x23,0x46,0x21,0x47,0x1f,0x49,0x1d,0x49,0x1a, + 0x4b,0x19,0x4c,0x18,0x4c,0x16,0x4e,0x15,0x4e,0x14,0x4f,0x13,0x50,0x12,0x51,0x11,0x52,0x11,0x52,0x0f, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x82,0x00,0x83,0x00,0x83,0x00, + 0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x81,0x00,0x83,0x00,0x83,0x00,0x83,0x00,0x83,0x00, + 0x00,0x78,0x00,0x6e,0x01,0x64,0x02,0x5b,0x04,0x54,0x06,0x4e,0x07,0x47,0x0a,0x42,0x0c,0x3e,0x0f,0x3b, + 0x0f,0x35,0x12,0x33,0x14,0x30,0x16,0x2d,0x19,0x2b,0x19,0x28,0x1c,0x26,0x1d,0x25,0x1f,0x22,0x21,0x22, + 0x41,0x3c,0x42,0x37,0x42,0x32,0x43,0x2d,0x44,0x2a,0x45,0x27,0x45,0x23,0x46,0x21,0x48,0x1f,0x49,0x1d, + 0x49,0x1a,0x4b,0x19,0x4c,0x18,0x4c,0x16,0x4e,0x15,0x4d,0x14,0x50,0x13,0x50,0x12,0x51,0x11,0x52,0x11, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x0a,0x00,0x13,0x00,0x1b,0x00,0x00,0x7e,0x00,0x7c,0x00,0x77,0x00,0x6f, + 0x00,0x65,0x00,0x59,0x00,0x4c,0x00,0x3e,0x00,0x30,0x00,0x23,0x00,0x16,0x00,0x0b,0x00,0x00,0x0a,0x00, + 0x13,0x00,0x1b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00, + 0x77,0x00,0x6f,0x00,0x65,0x00,0x59,0x00,0x4c,0x00,0x3e,0x00,0x30,0x00,0x23,0x00,0x16,0x00,0x0b,0x00, + 0x00,0x00,0x0a,0x00,0x13,0x00,0x1b,0x00,0x00,0x7e,0x00,0x7c,0x00,0x77,0x00,0x6f,0x00,0x65,0x00,0x59, + 0x00,0x4c,0x00,0x3e,0x00,0x30,0x00,0x23,0x00,0x16,0x00,0x0b,0x00,0x00,0x0a,0x00,0x13,0x00,0x1b,0x00, + 0x40,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x61,0x20,0x4d,0x2a,0x48,0x30,0x44,0x33,0x44,0x35,0x44,0x36,0x43,0x37,0x42,0x38,0x43,0x39,0x42,0x39, + 0x42,0x3a,0x42,0x3a,0x42,0x3b,0x42,0x3b,0x42,0x3b,0x41,0x3b,0x42,0x3c,0x42,0x3c,0x42,0x3c,0x42,0x3c, + 0x04,0x3d,0x22,0x3d,0x2b,0x3d,0x30,0x3d,0x33,0x3d,0x35,0x3d,0x37,0x3d,0x38,0x3d,0x39,0x3d,0x39,0x3d, + 0x3a,0x3d,0x3a,0x3d,0x3b,0x3d,0x3b,0x3d,0x3b,0x3d,0x3c,0x3d,0x3c,0x3d,0x3c,0x3d,0x3c,0x3d,0x3c,0x3d, + 0x40,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x09,0x00,0x12,0x00,0x00,0x7e,0x00,0x7d,0x00,0x78,0x00,0x71, + 0x00,0x68,0x00,0x5e,0x00,0x52,0x00,0x45,0x00,0x39,0x00,0x2c,0x00,0x20,0x00,0x15,0x00,0x0a,0x00,0x00, + 0x09,0x00,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x78,0x00,0x71,0x00,0x68,0x00,0x5e,0x00,0x52,0x00,0x45,0x00,0x39,0x00,0x2c,0x00,0x20,0x00,0x15,0x00, + 0x0a,0x00,0x00,0x00,0x09,0x00,0x12,0x00,0x00,0x7e,0x00,0x7d,0x00,0x78,0x00,0x71,0x00,0x68,0x00,0x5e, + 0x00,0x52,0x00,0x45,0x00,0x39,0x00,0x2c,0x00,0x20,0x00,0x15,0x00,0x0a,0x00,0x00,0x09,0x00,0x12,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x6c,0x0b,0x57,0x16,0x4f,0x1d,0x4a,0x22,0x48,0x26,0x47,0x29,0x46,0x2b,0x44,0x2d,0x44,0x2f,0x44,0x30, + 0x44,0x31,0x44,0x32,0x43,0x33,0x43,0x34,0x43,0x34,0x42,0x35,0x43,0x36,0x42,0x36,0x42,0x37,0x42,0x37, + 0x00,0x5d,0x0c,0x49,0x16,0x43,0x1d,0x41,0x22,0x40,0x26,0x3f,0x29,0x3f,0x2c,0x3f,0x2e,0x3e,0x2f,0x3e, + 0x31,0x3e,0x32,0x3e,0x33,0x3e,0x33,0x3e,0x34,0x3e,0x35,0x3e,0x35,0x3e,0x36,0x3e,0x37,0x3e,0x37,0x3e, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x7e,0x00,0x7d,0x00,0x79,0x00,0x73, + 0x00,0x6b,0x00,0x62,0x00,0x57,0x00,0x4c,0x00,0x40,0x00,0x34,0x00,0x29,0x00,0x1e,0x00,0x13,0x00,0x09, + 0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x79,0x00,0x73,0x00,0x6b,0x00,0x62,0x00,0x57,0x00,0x4c,0x00,0x40,0x00,0x34,0x00,0x29,0x00,0x1e,0x00, + 0x13,0x00,0x09,0x00,0x00,0x00,0x08,0x00,0x00,0x7e,0x00,0x7d,0x00,0x79,0x00,0x73,0x00,0x6b,0x00,0x62, + 0x00,0x57,0x00,0x4c,0x00,0x40,0x00,0x34,0x00,0x29,0x00,0x1e,0x00,0x13,0x00,0x09,0x00,0x00,0x08,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x72,0x06,0x5f,0x0d,0x56,0x14,0x4f,0x19,0x4d,0x1d,0x4a,0x20,0x49,0x23,0x47,0x25,0x46,0x27,0x46,0x29, + 0x45,0x2a,0x45,0x2c,0x44,0x2d,0x44,0x2e,0x44,0x2f,0x43,0x30,0x44,0x30,0x44,0x31,0x43,0x32,0x43,0x33, + 0x00,0x68,0x06,0x54,0x0d,0x4b,0x14,0x47,0x19,0x44,0x1d,0x43,0x20,0x41,0x23,0x41,0x26,0x40,0x27,0x40, + 0x29,0x3f,0x2b,0x3f,0x2c,0x3f,0x2d,0x3f,0x2e,0x3f,0x2f,0x3f,0x30,0x3f,0x30,0x3e,0x31,0x3e,0x32,0x3e, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00,0x7a,0x00,0x75, + 0x00,0x6e,0x00,0x65,0x00,0x5b,0x00,0x51,0x00,0x46,0x00,0x3b,0x00,0x30,0x00,0x26,0x00,0x1b,0x00,0x12, + 0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x7a,0x00,0x75,0x00,0x6e,0x00,0x65,0x00,0x5b,0x00,0x51,0x00,0x46,0x00,0x3b,0x00,0x30,0x00,0x26,0x00, + 0x1b,0x00,0x12,0x00,0x08,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00,0x7a,0x00,0x75,0x00,0x6e,0x00,0x65, + 0x00,0x5b,0x00,0x51,0x00,0x46,0x00,0x3b,0x00,0x30,0x00,0x26,0x00,0x1b,0x00,0x12,0x00,0x08,0x00,0x00, + 0x42,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x75,0x03,0x64,0x09,0x5a,0x0e,0x54,0x13,0x51,0x17,0x4e,0x1a,0x4c,0x1d,0x49,0x1f,0x49,0x22,0x48,0x23, + 0x47,0x25,0x46,0x26,0x46,0x28,0x45,0x29,0x45,0x2a,0x44,0x2b,0x44,0x2c,0x44,0x2d,0x44,0x2e,0x44,0x2e, + 0x00,0x6d,0x04,0x5b,0x09,0x51,0x0e,0x4c,0x13,0x48,0x17,0x46,0x1a,0x44,0x1d,0x43,0x1f,0x42,0x22,0x42, + 0x24,0x41,0x25,0x41,0x27,0x40,0x28,0x40,0x29,0x40,0x2a,0x3f,0x2b,0x3f,0x2c,0x3f,0x2d,0x3f,0x2e,0x3f, + 0x42,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x1f,0x3f,0x00,0x66,0x00,0x72,0x00, + 0x78,0x00,0x7a,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00, + 0x7e,0x00,0x7e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f,0x1f,0x00,0x3f, + 0x00,0x66,0x00,0x72,0x00,0x78,0x00,0x7a,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7e,0x00,0x7e, + 0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x7e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x77,0x02,0x68,0x06,0x5f,0x0b,0x58,0x0f,0x54,0x12,0x51,0x15,0x4f,0x18,0x4c,0x1b,0x4b,0x1d,0x4a,0x1f, + 0x49,0x21,0x48,0x22,0x48,0x23,0x47,0x25,0x46,0x26,0x45,0x27,0x45,0x28,0x45,0x29,0x45,0x2a,0x44,0x2b, + 0x00,0x70,0x02,0x60,0x07,0x56,0x0b,0x50,0x0f,0x4c,0x12,0x49,0x16,0x47,0x18,0x46,0x1b,0x45,0x1d,0x44, + 0x1f,0x43,0x21,0x42,0x22,0x42,0x24,0x41,0x25,0x41,0x26,0x40,0x27,0x40,0x28,0x40,0x29,0x40,0x2a,0x3f, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3f,0x0a,0x0a,0x3f,0x00,0x5c,0x00, + 0x6a,0x00,0x71,0x00,0x75,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x7b,0x00,0x7c,0x00,0x7c,0x00,0x7d,0x00, + 0x7d,0x00,0x7d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3f,0x00,0x0a,0x0a, + 0x00,0x3f,0x00,0x5c,0x00,0x6a,0x00,0x71,0x00,0x75,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x7b,0x00,0x7c, + 0x00,0x7c,0x00,0x7d,0x00,0x7d,0x00,0x7d,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x78,0x02,0x6b,0x05,0x62,0x08,0x5b,0x0c,0x57,0x0f,0x54,0x12,0x51,0x14,0x4e,0x17,0x4d,0x19,0x4c,0x1b, + 0x4b,0x1d,0x4a,0x1e,0x49,0x20,0x48,0x21,0x48,0x22,0x46,0x24,0x46,0x25,0x46,0x26,0x46,0x27,0x45,0x27, + 0x00,0x72,0x02,0x64,0x05,0x5b,0x08,0x54,0x0c,0x50,0x0f,0x4d,0x12,0x4a,0x14,0x48,0x17,0x47,0x19,0x46, + 0x1b,0x45,0x1d,0x44,0x1f,0x44,0x20,0x42,0x21,0x42,0x22,0x42,0x24,0x41,0x25,0x41,0x26,0x41,0x27,0x40, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x66,0x00,0x3f,0x03,0x03,0x2d,0x00, + 0x48,0x00,0x59,0x00,0x63,0x00,0x6a,0x00,0x6e,0x00,0x72,0x00,0x74,0x00,0x76,0x00,0x77,0x00,0x78,0x00, + 0x79,0x00,0x7a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x66,0x00,0x3f,0x00, + 0x03,0x03,0x00,0x2d,0x00,0x48,0x00,0x59,0x00,0x63,0x00,0x6a,0x00,0x6e,0x00,0x72,0x00,0x74,0x00,0x76, + 0x00,0x77,0x00,0x78,0x00,0x79,0x00,0x7a,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x79,0x01,0x6d,0x04,0x65,0x07,0x5e,0x0a,0x5a,0x0d,0x56,0x0f,0x54,0x12,0x51,0x14,0x4f,0x16,0x4e,0x18, + 0x4c,0x1a,0x4b,0x1b,0x4b,0x1d,0x4a,0x1e,0x49,0x1f,0x48,0x21,0x48,0x22,0x48,0x23,0x47,0x23,0x46,0x25, + 0x00,0x74,0x01,0x66,0x04,0x5e,0x07,0x57,0x0a,0x53,0x0d,0x4f,0x10,0x4d,0x12,0x4b,0x14,0x49,0x16,0x48, + 0x18,0x46,0x1a,0x45,0x1b,0x45,0x1d,0x44,0x1e,0x44,0x20,0x43,0x21,0x42,0x22,0x42,0x23,0x42,0x24,0x41, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x72,0x00,0x5c,0x00,0x2d,0x01,0x01, + 0x22,0x00,0x3a,0x00,0x4a,0x00,0x56,0x00,0x5e,0x00,0x64,0x00,0x69,0x00,0x6d,0x00,0x6f,0x00,0x71,0x00, + 0x73,0x00,0x75,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x72,0x00,0x5c,0x00, + 0x2d,0x00,0x01,0x01,0x00,0x22,0x00,0x3a,0x00,0x4a,0x00,0x56,0x00,0x5e,0x00,0x64,0x00,0x69,0x00,0x6d, + 0x00,0x6f,0x00,0x71,0x00,0x73,0x00,0x75,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7a,0x01,0x6f,0x03,0x67,0x06,0x60,0x08,0x5d,0x0b,0x59,0x0d,0x56,0x10,0x53,0x11,0x51,0x14,0x50,0x15, + 0x4e,0x17,0x4d,0x19,0x4c,0x1a,0x4b,0x1b,0x4b,0x1d,0x48,0x1e,0x49,0x1f,0x49,0x20,0x48,0x21,0x48,0x22, + 0x00,0x75,0x01,0x69,0x03,0x61,0x06,0x5a,0x08,0x56,0x0b,0x52,0x0d,0x4f,0x10,0x4d,0x12,0x4b,0x14,0x4a, + 0x16,0x48,0x17,0x47,0x19,0x46,0x1a,0x45,0x1c,0x45,0x1d,0x44,0x1e,0x44,0x1f,0x44,0x20,0x43,0x21,0x42, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x78,0x00,0x6a,0x00,0x48,0x00,0x22, + 0x00,0x00,0x1b,0x00,0x30,0x00,0x3f,0x00,0x4b,0x00,0x54,0x00,0x5b,0x00,0x61,0x00,0x65,0x00,0x68,0x00, + 0x6b,0x00,0x6e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x78,0x00,0x6a,0x00, + 0x48,0x00,0x22,0x00,0x00,0x00,0x00,0x1b,0x00,0x30,0x00,0x3f,0x00,0x4b,0x00,0x54,0x00,0x5b,0x00,0x61, + 0x00,0x65,0x00,0x68,0x00,0x6b,0x00,0x6e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7b,0x01,0x71,0x02,0x69,0x05,0x62,0x07,0x5f,0x09,0x5b,0x0c,0x58,0x0e,0x55,0x10,0x53,0x11,0x52,0x13, + 0x50,0x15,0x4e,0x16,0x4e,0x18,0x4c,0x19,0x4c,0x1a,0x4a,0x1c,0x4b,0x1d,0x49,0x1e,0x49,0x1f,0x49,0x20, + 0x00,0x76,0x01,0x6b,0x03,0x63,0x05,0x5d,0x07,0x58,0x09,0x54,0x0c,0x52,0x0e,0x4f,0x10,0x4d,0x11,0x4c, + 0x13,0x4a,0x15,0x49,0x17,0x48,0x18,0x47,0x19,0x46,0x1b,0x45,0x1c,0x45,0x1d,0x44,0x1e,0x44,0x1f,0x44, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7a,0x00,0x71,0x00,0x59,0x00,0x3a, + 0x00,0x1b,0x00,0x00,0x16,0x00,0x28,0x00,0x37,0x00,0x42,0x00,0x4b,0x00,0x53,0x00,0x59,0x00,0x5e,0x00, + 0x62,0x00,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7a,0x00,0x71,0x00, + 0x59,0x00,0x3a,0x00,0x1b,0x00,0x00,0x00,0x00,0x16,0x00,0x28,0x00,0x37,0x00,0x42,0x00,0x4b,0x00,0x53, + 0x00,0x59,0x00,0x5e,0x00,0x62,0x00,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7b,0x00,0x72,0x02,0x6b,0x04,0x64,0x06,0x61,0x08,0x5d,0x0a,0x5a,0x0c,0x56,0x0e,0x55,0x10,0x53,0x11, + 0x52,0x13,0x50,0x15,0x4f,0x16,0x4e,0x17,0x4d,0x18,0x4b,0x1a,0x4b,0x1a,0x4b,0x1c,0x4b,0x1d,0x49,0x1d, + 0x00,0x77,0x00,0x6c,0x02,0x65,0x04,0x5f,0x06,0x5a,0x08,0x57,0x0a,0x54,0x0c,0x51,0x0e,0x4f,0x10,0x4d, + 0x11,0x4c,0x13,0x4a,0x15,0x49,0x16,0x48,0x18,0x48,0x18,0x46,0x1a,0x46,0x1b,0x45,0x1c,0x45,0x1d,0x45, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x75,0x00,0x63,0x00,0x4a, + 0x00,0x30,0x00,0x16,0x00,0x00,0x13,0x00,0x23,0x00,0x30,0x00,0x3b,0x00,0x44,0x00,0x4c,0x00,0x52,0x00, + 0x57,0x00,0x5b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x75,0x00, + 0x63,0x00,0x4a,0x00,0x30,0x00,0x16,0x00,0x00,0x00,0x00,0x13,0x00,0x23,0x00,0x30,0x00,0x3b,0x00,0x44, + 0x00,0x4c,0x00,0x52,0x00,0x57,0x00,0x5b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7c,0x00,0x73,0x02,0x6c,0x03,0x66,0x05,0x63,0x07,0x5e,0x09,0x5c,0x0b,0x58,0x0c,0x57,0x0e,0x55,0x10, + 0x53,0x11,0x52,0x13,0x50,0x14,0x4f,0x15,0x4e,0x17,0x4c,0x18,0x4c,0x19,0x4c,0x1a,0x4b,0x1a,0x4b,0x1c, + 0x00,0x77,0x00,0x6e,0x02,0x66,0x04,0x61,0x05,0x5c,0x07,0x59,0x09,0x56,0x0b,0x53,0x0d,0x51,0x0f,0x4f, + 0x10,0x4e,0x11,0x4c,0x13,0x4b,0x14,0x4a,0x15,0x48,0x17,0x48,0x18,0x47,0x19,0x46,0x1b,0x46,0x1b,0x45, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x78,0x00,0x6a,0x00,0x56, + 0x00,0x3f,0x00,0x28,0x00,0x13,0x00,0x00,0x10,0x00,0x1f,0x00,0x2b,0x00,0x35,0x00,0x3e,0x00,0x45,0x00, + 0x4c,0x00,0x51,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7c,0x00,0x78,0x00, + 0x6a,0x00,0x56,0x00,0x3f,0x00,0x28,0x00,0x13,0x00,0x00,0x00,0x00,0x10,0x00,0x1f,0x00,0x2b,0x00,0x35, + 0x00,0x3e,0x00,0x45,0x00,0x4c,0x00,0x51,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7c,0x00,0x74,0x02,0x6e,0x03,0x68,0x05,0x64,0x06,0x60,0x08,0x5d,0x0a,0x5a,0x0b,0x58,0x0d,0x56,0x0e, + 0x55,0x10,0x53,0x11,0x52,0x13,0x50,0x14,0x50,0x15,0x4d,0x16,0x4e,0x18,0x4c,0x18,0x4c,0x19,0x4c,0x1a, + 0x00,0x77,0x00,0x6f,0x02,0x68,0x03,0x63,0x05,0x5e,0x06,0x5a,0x08,0x57,0x0a,0x55,0x0b,0x53,0x0d,0x50, + 0x0f,0x4f,0x10,0x4e,0x11,0x4c,0x13,0x4b,0x14,0x4a,0x15,0x49,0x16,0x48,0x18,0x48,0x18,0x46,0x19,0x46, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x79,0x00,0x6e,0x00,0x5e, + 0x00,0x4b,0x00,0x37,0x00,0x23,0x00,0x10,0x00,0x00,0x0e,0x00,0x1b,0x00,0x27,0x00,0x30,0x00,0x39,0x00, + 0x40,0x00,0x46,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x79,0x00, + 0x6e,0x00,0x5e,0x00,0x4b,0x00,0x37,0x00,0x23,0x00,0x10,0x00,0x00,0x00,0x00,0x0e,0x00,0x1b,0x00,0x27, + 0x00,0x30,0x00,0x39,0x00,0x40,0x00,0x46,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7d,0x00,0x75,0x01,0x6f,0x02,0x69,0x04,0x65,0x06,0x62,0x07,0x5f,0x09,0x5b,0x0b,0x5a,0x0c,0x58,0x0d, + 0x56,0x0e,0x55,0x10,0x53,0x11,0x52,0x13,0x50,0x13,0x4f,0x15,0x4e,0x15,0x4e,0x17,0x4d,0x18,0x4c,0x18, + 0x00,0x78,0x00,0x70,0x01,0x69,0x03,0x64,0x04,0x60,0x06,0x5c,0x07,0x59,0x09,0x56,0x0b,0x54,0x0c,0x52, + 0x0d,0x50,0x0f,0x4f,0x10,0x4e,0x11,0x4c,0x13,0x4b,0x13,0x4a,0x15,0x4a,0x15,0x48,0x17,0x48,0x18,0x47, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x7a,0x00,0x72,0x00,0x64, + 0x00,0x54,0x00,0x42,0x00,0x30,0x00,0x1f,0x00,0x0e,0x00,0x00,0x0d,0x00,0x19,0x00,0x23,0x00,0x2c,0x00, + 0x34,0x00,0x3b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x7a,0x00, + 0x72,0x00,0x64,0x00,0x54,0x00,0x42,0x00,0x30,0x00,0x1f,0x00,0x0e,0x00,0x00,0x00,0x00,0x0d,0x00,0x19, + 0x00,0x23,0x00,0x2c,0x00,0x34,0x00,0x3b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7d,0x00,0x76,0x01,0x70,0x02,0x6a,0x03,0x67,0x05,0x63,0x06,0x60,0x08,0x5d,0x09,0x5b,0x0b,0x59,0x0c, + 0x57,0x0d,0x55,0x0e,0x55,0x10,0x53,0x11,0x52,0x13,0x4f,0x13,0x50,0x15,0x4f,0x15,0x4e,0x16,0x4e,0x18, + 0x00,0x78,0x00,0x71,0x01,0x6a,0x03,0x66,0x04,0x61,0x05,0x5d,0x06,0x5a,0x08,0x58,0x09,0x55,0x0b,0x53, + 0x0d,0x52,0x0e,0x50,0x0f,0x4e,0x10,0x4e,0x11,0x4c,0x13,0x4c,0x13,0x4a,0x15,0x4a,0x15,0x49,0x16,0x48, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7b,0x00,0x74,0x00,0x69, + 0x00,0x5b,0x00,0x4b,0x00,0x3b,0x00,0x2b,0x00,0x1b,0x00,0x0d,0x00,0x00,0x0c,0x00,0x16,0x00,0x20,0x00, + 0x29,0x00,0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7b,0x00, + 0x74,0x00,0x69,0x00,0x5b,0x00,0x4b,0x00,0x3b,0x00,0x2b,0x00,0x1b,0x00,0x0d,0x00,0x00,0x00,0x00,0x0c, + 0x00,0x16,0x00,0x20,0x00,0x29,0x00,0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7d,0x00,0x76,0x01,0x71,0x02,0x6c,0x03,0x68,0x05,0x64,0x06,0x61,0x07,0x5e,0x09,0x5c,0x0a,0x5a,0x0b, + 0x59,0x0c,0x57,0x0e,0x55,0x0e,0x55,0x11,0x52,0x11,0x51,0x12,0x51,0x13,0x50,0x14,0x4f,0x15,0x4e,0x15, + 0x00,0x79,0x00,0x71,0x01,0x6c,0x02,0x66,0x04,0x62,0x05,0x5f,0x06,0x5c,0x07,0x59,0x09,0x57,0x0a,0x55, + 0x0b,0x53,0x0d,0x51,0x0e,0x50,0x0f,0x4e,0x11,0x4e,0x11,0x4c,0x13,0x4c,0x13,0x4b,0x14,0x4a,0x15,0x4a, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00,0x76,0x00,0x6d, + 0x00,0x61,0x00,0x53,0x00,0x44,0x00,0x35,0x00,0x27,0x00,0x19,0x00,0x0c,0x00,0x00,0x0b,0x00,0x15,0x00, + 0x1e,0x00,0x26,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00, + 0x76,0x00,0x6d,0x00,0x61,0x00,0x53,0x00,0x44,0x00,0x35,0x00,0x27,0x00,0x19,0x00,0x0c,0x00,0x00,0x00, + 0x00,0x0b,0x00,0x15,0x00,0x1e,0x00,0x26,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7d,0x00,0x77,0x01,0x72,0x02,0x6d,0x03,0x69,0x04,0x66,0x06,0x63,0x07,0x5f,0x08,0x5e,0x09,0x5c,0x0b, + 0x5a,0x0c,0x58,0x0c,0x57,0x0e,0x55,0x0f,0x54,0x11,0x51,0x11,0x52,0x12,0x51,0x13,0x50,0x14,0x50,0x15, + 0x00,0x79,0x00,0x72,0x01,0x6d,0x02,0x68,0x03,0x63,0x04,0x60,0x06,0x5d,0x07,0x5b,0x08,0x58,0x09,0x56, + 0x0b,0x54,0x0c,0x53,0x0d,0x51,0x0e,0x50,0x0f,0x4e,0x11,0x4e,0x11,0x4c,0x12,0x4c,0x13,0x4b,0x14,0x4a, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00,0x77,0x00,0x6f, + 0x00,0x65,0x00,0x59,0x00,0x4c,0x00,0x3e,0x00,0x30,0x00,0x23,0x00,0x16,0x00,0x0b,0x00,0x00,0x0a,0x00, + 0x13,0x00,0x1b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7c,0x00, + 0x77,0x00,0x6f,0x00,0x65,0x00,0x59,0x00,0x4c,0x00,0x3e,0x00,0x30,0x00,0x23,0x00,0x16,0x00,0x0b,0x00, + 0x00,0x00,0x00,0x0a,0x00,0x13,0x00,0x1b,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7d,0x00,0x78,0x01,0x72,0x02,0x6e,0x02,0x6a,0x03,0x67,0x05,0x64,0x06,0x60,0x07,0x5f,0x09,0x5c,0x0a, + 0x5b,0x0b,0x5a,0x0c,0x57,0x0c,0x56,0x0e,0x55,0x0f,0x53,0x11,0x52,0x11,0x52,0x12,0x51,0x13,0x50,0x13, + 0x00,0x79,0x00,0x73,0x01,0x6d,0x02,0x69,0x03,0x65,0x04,0x61,0x05,0x5e,0x06,0x5c,0x07,0x59,0x09,0x57, + 0x0a,0x55,0x0b,0x54,0x0d,0x53,0x0d,0x51,0x0f,0x50,0x0f,0x4e,0x11,0x4e,0x11,0x4c,0x12,0x4c,0x13,0x4b, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00,0x78,0x00,0x71, + 0x00,0x68,0x00,0x5e,0x00,0x52,0x00,0x45,0x00,0x39,0x00,0x2c,0x00,0x20,0x00,0x15,0x00,0x0a,0x00,0x00, + 0x09,0x00,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x78,0x00,0x71,0x00,0x68,0x00,0x5e,0x00,0x52,0x00,0x45,0x00,0x39,0x00,0x2c,0x00,0x20,0x00,0x15,0x00, + 0x0a,0x00,0x00,0x00,0x00,0x09,0x00,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7e,0x00,0x78,0x01,0x73,0x02,0x6e,0x02,0x6b,0x03,0x68,0x05,0x65,0x06,0x62,0x07,0x5f,0x07,0x5e,0x09, + 0x5c,0x0b,0x5a,0x0b,0x59,0x0c,0x57,0x0d,0x56,0x0e,0x54,0x0f,0x54,0x11,0x52,0x11,0x52,0x12,0x51,0x13, + 0x00,0x79,0x00,0x73,0x01,0x6e,0x02,0x69,0x03,0x66,0x04,0x62,0x05,0x5f,0x06,0x5d,0x07,0x5b,0x08,0x58, + 0x09,0x56,0x0b,0x55,0x0b,0x53,0x0d,0x52,0x0d,0x50,0x0f,0x50,0x0f,0x4e,0x11,0x4e,0x11,0x4d,0x12,0x4c, + 0x41,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00,0x79,0x00,0x73, + 0x00,0x6b,0x00,0x62,0x00,0x57,0x00,0x4c,0x00,0x40,0x00,0x34,0x00,0x29,0x00,0x1e,0x00,0x13,0x00,0x09, + 0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x79,0x00,0x73,0x00,0x6b,0x00,0x62,0x00,0x57,0x00,0x4c,0x00,0x40,0x00,0x34,0x00,0x29,0x00,0x1e,0x00, + 0x13,0x00,0x09,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7e,0x00,0x78,0x00,0x74,0x01,0x6f,0x02,0x6c,0x03,0x68,0x04,0x65,0x05,0x62,0x06,0x61,0x07,0x5f,0x09, + 0x5c,0x09,0x5b,0x0b,0x5a,0x0b,0x58,0x0c,0x57,0x0d,0x55,0x0e,0x55,0x0f,0x54,0x11,0x52,0x11,0x52,0x12, + 0x00,0x79,0x00,0x74,0x00,0x6f,0x02,0x6a,0x03,0x66,0x04,0x63,0x05,0x60,0x05,0x5e,0x06,0x5b,0x07,0x59, + 0x09,0x58,0x09,0x55,0x0b,0x55,0x0c,0x53,0x0d,0x52,0x0d,0x50,0x0f,0x50,0x0f,0x4e,0x11,0x4e,0x11,0x4d, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00,0x7a,0x00,0x75, + 0x00,0x6e,0x00,0x65,0x00,0x5b,0x00,0x51,0x00,0x46,0x00,0x3b,0x00,0x30,0x00,0x26,0x00,0x1b,0x00,0x12, + 0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x7d,0x00, + 0x7a,0x00,0x75,0x00,0x6e,0x00,0x65,0x00,0x5b,0x00,0x51,0x00,0x46,0x00,0x3b,0x00,0x30,0x00,0x26,0x00, + 0x1b,0x00,0x12,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, + 0x7e,0x00,0x79,0x00,0x74,0x01,0x70,0x02,0x6c,0x03,0x69,0x03,0x66,0x05,0x63,0x06,0x62,0x07,0x5f,0x07, + 0x5e,0x09,0x5c,0x0a,0x5a,0x0b,0x5a,0x0c,0x57,0x0c,0x56,0x0e,0x55,0x0e,0x55,0x0f,0x54,0x11,0x52,0x11, + 0x00,0x79,0x00,0x74,0x00,0x70,0x01,0x6b,0x02,0x67,0x03,0x64,0x04,0x61,0x05,0x5f,0x06,0x5d,0x07,0x5b, + 0x08,0x58,0x09,0x57,0x0a,0x55,0x0b,0x54,0x0c,0x53,0x0d,0x51,0x0e,0x50,0x0f,0x50,0x0f,0x4e,0x11,0x4e, + 0x41,0x3d,0x41,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d, + 0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x41,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d,0x42,0x3d, +}; + +static const unsigned char kSmaaSearch[SMAA_SEARCH_W * SMAA_SEARCH_H] = { + 0xfe,0xfe,0x00,0x7f,0x7f,0x00,0x00,0xfe,0xfe,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0xfe,0x7f,0x00,0x00,0x00,0x00,0x00, + 0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0xfe,0xfe,0x00,0x7f,0x7f,0x00,0x00,0xfe,0xfe,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0xfe,0x7f,0x00, + 0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfe,0xfe,0x00,0x7f,0x7f,0x00,0x00,0xfe, + 0xfe,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00, + 0x7f,0x7f,0x00,0x7f,0x7f,0xfe,0x7f,0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfe,0xfe,0x00,0x7f, + 0x7f,0x00,0x00,0xfe,0xfe,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00, + 0x7f,0x7f,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0xfe,0x7f,0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x7f,0x7f,0x00,0x7f, + 0x7f,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x7f, + 0x7f,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00, + 0x7f,0x7f,0x00,0x7f,0x7f,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00, + 0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x00,0x00,0x7f,0x7f,0x00,0x7f,0x7f,0x7f,0x7f,0x00, + 0x00,0x00,0x00,0x00,0x7f,0x7f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00, +}; diff --git a/app/src/main/cpp/shaders/smaa_weights.frag b/app/src/main/cpp/shaders/smaa_weights.frag index 32e8b404cd..3d6bca5601 100644 --- a/app/src/main/cpp/shaders/smaa_weights.frag +++ b/app/src/main/cpp/shaders/smaa_weights.frag @@ -1,153 +1,25 @@ #version 450 +#extension GL_GOOGLE_include_directive : require layout(location = 0) in vec2 fragTexCoord; layout(location = 0) out vec4 outColor; layout(set = 0, binding = 0) uniform sampler2D EdgeTexture; +layout(set = 1, binding = 0) uniform sampler2D AreaTexture; +layout(set = 2, binding = 0) uniform sampler2D SearchTexture; layout(push_constant) uniform Constants { vec4 ndc; - vec2 resolution; - float extra; - float pad; + vec4 metrics; // 1/width, 1/height, width, height } pc; -vec4 edgeAt(vec2 uv, vec2 px) { - vec2 edgeUV = clamp(uv, px * 0.5, vec2(1.0) - px * 0.5); - vec4 e = textureLod(EdgeTexture, edgeUV, 0.0); - e.a = edgeUV.y >= 1.0 - px.y ? 0.0 : e.a; - return e; -} - -float verticalEdge(vec2 uv, vec2 px) { - vec4 e = edgeAt(uv, px); - return max(e.r, e.g); -} - -float horizontalEdge(vec2 uv, vec2 px) { - vec4 e = edgeAt(uv, px); - return max(e.b, e.a); -} - -float measureRun(vec2 origin, vec2 texel, vec2 tangent, - bool verticalLine, float limit, bool positive) { - float run = 0.0; - for (int i = 1; i <= 6; ++i) { - vec2 probe = origin + tangent * float(i) * (positive ? 1.0 : -1.0); - ivec2 index = ivec2(floor(probe * pc.resolution)); - ivec2 size = ivec2(pc.resolution); - if (any(lessThan(index, ivec2(0))) || - any(greaterThanEqual(index, size))) { - break; - } - float edge = verticalLine - ? verticalEdge(probe, texel) - : horizontalEdge(probe, texel); - if (edge <= limit * 0.65) { - break; - } - run = float(i); - } - return run; -} +#define SMAA_RT_METRICS pc.metrics +#define SMAA_GLSL_4 +#define SMAA_PRESET_HIGH +#include "SMAA.hlsl" void main() { - vec2 px = 1.0 / max(pc.resolution, vec2(1.0)); - vec2 uv = clamp(fragTexCoord, px * 0.5, vec2(1.0) - px * 0.5); - vec4 e = edgeAt(uv, px); - - float dL = e.r; - float dR = e.g; - float dU = e.b; - float dD = e.a; - float vertical = max(dL, dR); - float horizontal = max(dU, dD); - float strongest = max(vertical, horizontal); - float threshold = max(0.045, strongest * 0.12); - - if (strongest <= threshold) { - outColor = vec4(0.0, 0.5, 0.5, 0.0); - return; - } - - bool verticalLine; - float negativeRun = 0.0; - float positiveRun = 0.0; - bool runsMeasured = false; - - if (vertical > horizontal) { - verticalLine = true; - } else if (horizontal > vertical) { - verticalLine = false; - } else { - float vNeg = measureRun(uv, px, vec2(0.0, px.y), true, threshold, false); - float vPos = measureRun(uv, px, vec2(0.0, px.y), true, threshold, true); - float hNeg = measureRun(uv, px, vec2(px.x, 0.0), false, threshold, false); - float hPos = measureRun(uv, px, vec2(px.x, 0.0), false, threshold, true); - verticalLine = (vNeg + vPos) >= (hNeg + hPos); - negativeRun = verticalLine ? vNeg : hNeg; - positiveRun = verticalLine ? vPos : hPos; - runsMeasured = true; - } - - vec2 tangent = verticalLine ? vec2(0.0, px.y) : vec2(px.x, 0.0); - vec2 normal = verticalLine - ? vec2(dL >= dR ? -1.0 : 1.0, 0.0) - : vec2(0.0, dU >= dD ? -1.0 : 1.0); - - if (!runsMeasured) { - negativeRun = measureRun(uv, px, tangent, verticalLine, threshold, false); - positiveRun = measureRun(uv, px, tangent, verticalLine, threshold, true); - } - - float span = negativeRun + positiveRun; - float edgeConfidence = smoothstep(threshold, threshold * 2.5, strongest); - - vec4 nw = edgeAt(uv + vec2(-px.x, -px.y), px); - vec4 ne = edgeAt(uv + vec2(px.x, -px.y), px); - vec4 sw = edgeAt(uv + vec2(-px.x, px.y), px); - vec4 se = edgeAt(uv + vec2(px.x, px.y), px); - - float runEndpointPattern = clamp( - abs(negativeRun - positiveRun) / max(span, 1.0), 0.0, 1.0); - float crossingA = verticalLine - ? abs(nw.a - ne.a) - : abs(nw.g - sw.g); - float crossingB = verticalLine - ? abs(sw.b - se.b) - : abs(ne.r - se.r); - float crossingContrast = abs(crossingA - crossingB); - float crossingPattern = smoothstep(threshold, threshold * 2.5, crossingContrast); - vec4 edgeMin = min(min(nw, ne), min(sw, se)); - vec4 edgeMax = max(max(nw, ne), max(sw, se)); - float edgeVariation = max( - max(edgeMax.r - edgeMin.r, edgeMax.g - edgeMin.g), - max(edgeMax.b - edgeMin.b, edgeMax.a - edgeMin.a)); - float balancedCrossing = edgeVariation > 0.01 - ? smoothstep(threshold, threshold * 2.5, min(crossingA, crossingB)) - : 0.0; - float endpointPattern = runEndpointPattern > 0.01 - ? max(runEndpointPattern, balancedCrossing) - : runEndpointPattern; - float endpointArea = endpointPattern / (1.0 + span * 0.055); - float areaWeight = 0.38 * crossingPattern * clamp(span / 4.0, 0.0, 1.0); - float diagonalContrast = max( - max(max(abs(nw.r - se.r), abs(nw.g - se.g)), - max(abs(nw.b - se.b), abs(nw.a - se.a))), - max(max(abs(ne.r - sw.r), abs(ne.g - sw.g)), - max(abs(ne.b - sw.b), abs(ne.a - sw.a)))); - float cornerFactor = 1.0 - 0.35 * smoothstep(threshold, threshold * 3.0, diagonalContrast); - float baseWeight = areaWeight * endpointArea * edgeConfidence * cornerFactor; - - float diagonalStrength = min(vertical, horizontal); - float diagonalPattern = smoothstep(threshold, threshold * 2.5, diagonalStrength); - float diagonalContinuity = smoothstep(1.0, 3.0, span); - float shortDiagonalFallback = - (span > 0.0 && span <= 1.0 && crossingContrast <= threshold && diagonalStrength > threshold) - ? 1.0 : 0.0; - float diagonalFallback = 0.16 * diagonalPattern * edgeConfidence - * cornerFactor * max( - diagonalContinuity * max(crossingPattern, balancedCrossing), - shortDiagonalFallback); - - float weight = clamp(max(baseWeight, diagonalFallback), 0.0, 0.42); - outColor = vec4(weight, normal.x * 0.5 + 0.5, normal.y * 0.5 + 0.5, 1.0); + vec2 pixcoord; + vec4 offset[3]; + SMAABlendingWeightCalculationVS(fragTexCoord, pixcoord, offset); + outColor = SMAABlendingWeightCalculationPS(fragTexCoord, pixcoord, offset, EdgeTexture, + AreaTexture, SearchTexture, vec4(0.0)); } diff --git a/app/src/main/cpp/shaders/smaa_weights_frag.h b/app/src/main/cpp/shaders/smaa_weights_frag.h index be2681e8a2..5802838e6e 100644 --- a/app/src/main/cpp/shaders/smaa_weights_frag.h +++ b/app/src/main/cpp/shaders/smaa_weights_frag.h @@ -1,567 +1,986 @@ -// SPIR-V gerado -#pragma once + // 1116.6.0 + #pragma once const uint32_t smaa_weights_code[] = { - 0x07230203,0x00010000,0x0008000b,0x000002e6,0x00000000,0x00020011,0x00000001,0x0006000b, + 0x07230203,0x00010000,0x0008000b,0x000004fe,0x00000000,0x00020011,0x00000001,0x0006000b, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, - 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x000000cb,0x000000fd,0x00030010, - 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, - 0x00000000,0x00060005,0x0000000d,0x65676465,0x76287441,0x763b3266,0x003b3266,0x00030005, - 0x0000000b,0x00007675,0x00030005,0x0000000c,0x00007870,0x00080005,0x00000012,0x74726576, - 0x6c616369,0x65676445,0x32667628,0x3266763b,0x0000003b,0x00030005,0x00000010,0x00007675, - 0x00030005,0x00000011,0x00007870,0x00080005,0x00000016,0x69726f68,0x746e6f7a,0x64456c61, - 0x76286567,0x763b3266,0x003b3266,0x00030005,0x00000014,0x00007675,0x00030005,0x00000015, - 0x00007870,0x000b0005,0x00000022,0x7361656d,0x52657275,0x76286e75,0x763b3266,0x763b3266, - 0x623b3266,0x31663b31,0x3b31623b,0x00000000,0x00040005,0x0000001c,0x6769726f,0x00006e69, - 0x00040005,0x0000001d,0x65786574,0x0000006c,0x00040005,0x0000001e,0x676e6174,0x00746e65, - 0x00060005,0x0000001f,0x74726576,0x6c616369,0x656e694c,0x00000000,0x00040005,0x00000020, - 0x696d696c,0x00000074,0x00050005,0x00000021,0x69736f70,0x65766974,0x00000000,0x00040005, - 0x00000024,0x65676465,0x00005655,0x00030005,0x00000030,0x00000065,0x00050005,0x00000034, - 0x65676445,0x74786554,0x00657275,0x00030005,0x0000004d,0x00000065,0x00040005,0x0000004e, - 0x61726170,0x0000006d,0x00040005,0x00000050,0x61726170,0x0000006d,0x00030005,0x0000005b, - 0x00000065,0x00040005,0x0000005c,0x61726170,0x0000006d,0x00040005,0x0000005e,0x61726170, - 0x0000006d,0x00030005,0x00000069,0x006e7572,0x00030005,0x0000006c,0x00000069,0x00040005, - 0x00000076,0x626f7270,0x00000065,0x00040005,0x00000083,0x65646e69,0x00000078,0x00050005, - 0x00000085,0x736e6f43,0x746e6174,0x00000073,0x00040006,0x00000085,0x00000000,0x0063646e, - 0x00060006,0x00000085,0x00000001,0x6f736572,0x6974756c,0x00006e6f,0x00050006,0x00000085, - 0x00000002,0x72747865,0x00000061,0x00040006,0x00000085,0x00000003,0x00646170,0x00030005, - 0x00000087,0x00006370,0x00040005,0x0000008e,0x657a6973,0x00000000,0x00040005,0x000000a3, - 0x65676465,0x00000000,0x00040005,0x000000a8,0x61726170,0x0000006d,0x00040005,0x000000aa, - 0x61726170,0x0000006d,0x00040005,0x000000ae,0x61726170,0x0000006d,0x00040005,0x000000b0, - 0x61726170,0x0000006d,0x00030005,0x000000c3,0x00007870,0x00030005,0x000000c9,0x00007675, - 0x00060005,0x000000cb,0x67617266,0x43786554,0x64726f6f,0x00000000,0x00030005,0x000000d3, - 0x00000065,0x00040005,0x000000d4,0x61726170,0x0000006d,0x00040005,0x000000d6,0x61726170, - 0x0000006d,0x00030005,0x000000d9,0x00004c64,0x00030005,0x000000dc,0x00005264,0x00030005, - 0x000000df,0x00005564,0x00030005,0x000000e2,0x00004464,0x00050005,0x000000e5,0x74726576, - 0x6c616369,0x00000000,0x00050005,0x000000e9,0x69726f68,0x746e6f7a,0x00006c61,0x00050005, - 0x000000ed,0x6f727473,0x7365676e,0x00000074,0x00050005,0x000000f1,0x65726874,0x6c6f6873, - 0x00000064,0x00050005,0x000000fd,0x4374756f,0x726f6c6f,0x00000000,0x00050005,0x00000100, - 0x6167656e,0x65766974,0x006e7552,0x00050005,0x00000101,0x69736f70,0x65766974,0x006e7552, - 0x00060005,0x00000102,0x736e7572,0x7361654d,0x64657275,0x00000000,0x00060005,0x00000109, - 0x74726576,0x6c616369,0x656e694c,0x00000000,0x00040005,0x00000112,0x67654e76,0x00000000, - 0x00040005,0x00000116,0x61726170,0x0000006d,0x00040005,0x00000118,0x61726170,0x0000006d, - 0x00040005,0x0000011a,0x61726170,0x0000006d,0x00040005,0x0000011b,0x61726170,0x0000006d, - 0x00040005,0x0000011c,0x61726170,0x0000006d,0x00040005,0x0000011e,0x61726170,0x0000006d, - 0x00040005,0x00000120,0x736f5076,0x00000000,0x00040005,0x00000124,0x61726170,0x0000006d, - 0x00040005,0x00000126,0x61726170,0x0000006d,0x00040005,0x00000128,0x61726170,0x0000006d, - 0x00040005,0x00000129,0x61726170,0x0000006d,0x00040005,0x0000012a,0x61726170,0x0000006d, - 0x00040005,0x0000012c,0x61726170,0x0000006d,0x00040005,0x0000012e,0x67654e68,0x00000000, - 0x00040005,0x00000132,0x61726170,0x0000006d,0x00040005,0x00000134,0x61726170,0x0000006d, - 0x00040005,0x00000136,0x61726170,0x0000006d,0x00040005,0x00000137,0x61726170,0x0000006d, - 0x00040005,0x00000138,0x61726170,0x0000006d,0x00040005,0x0000013a,0x61726170,0x0000006d, - 0x00040005,0x0000013c,0x736f5068,0x00000000,0x00040005,0x00000140,0x61726170,0x0000006d, - 0x00040005,0x00000142,0x61726170,0x0000006d,0x00040005,0x00000144,0x61726170,0x0000006d, - 0x00040005,0x00000145,0x61726170,0x0000006d,0x00040005,0x00000146,0x61726170,0x0000006d, - 0x00040005,0x00000148,0x61726170,0x0000006d,0x00040005,0x00000159,0x676e6174,0x00746e65, - 0x00040005,0x00000166,0x6d726f6e,0x00006c61,0x00040005,0x0000017b,0x61726170,0x0000006d, - 0x00040005,0x0000017d,0x61726170,0x0000006d,0x00040005,0x0000017f,0x61726170,0x0000006d, - 0x00040005,0x00000181,0x61726170,0x0000006d,0x00040005,0x00000183,0x61726170,0x0000006d, - 0x00040005,0x00000185,0x61726170,0x0000006d,0x00040005,0x00000187,0x61726170,0x0000006d, - 0x00040005,0x00000189,0x61726170,0x0000006d,0x00040005,0x0000018b,0x61726170,0x0000006d, - 0x00040005,0x0000018d,0x61726170,0x0000006d,0x00040005,0x0000018f,0x61726170,0x0000006d, - 0x00040005,0x00000191,0x61726170,0x0000006d,0x00040005,0x00000193,0x6e617073,0x00000000, - 0x00060005,0x00000197,0x65676465,0x666e6f43,0x6e656469,0x00006563,0x00030005,0x0000019e, - 0x0000776e,0x00040005,0x000001a8,0x61726170,0x0000006d,0x00040005,0x000001a9,0x61726170, - 0x0000006d,0x00030005,0x000001ac,0x0000656e,0x00040005,0x000001b5,0x61726170,0x0000006d, - 0x00040005,0x000001b6,0x61726170,0x0000006d,0x00030005,0x000001b9,0x00007773,0x00040005, - 0x000001c2,0x61726170,0x0000006d,0x00040005,0x000001c3,0x61726170,0x0000006d,0x00030005, - 0x000001c6,0x00006573,0x00040005,0x000001ce,0x61726170,0x0000006d,0x00040005,0x000001cf, - 0x61726170,0x0000006d,0x00070005,0x000001d2,0x456e7572,0x6f70646e,0x50746e69,0x65747461, - 0x00006e72,0x00050005,0x000001db,0x736f7263,0x676e6973,0x00000041,0x00050005,0x000001ee, - 0x736f7263,0x676e6973,0x00000042,0x00070005,0x00000201,0x736f7263,0x676e6973,0x746e6f43, - 0x74736172,0x00000000,0x00060005,0x00000206,0x736f7263,0x676e6973,0x74746150,0x006e7265, - 0x00040005,0x0000020c,0x65676465,0x006e694d,0x00040005,0x00000214,0x65676465,0x0078614d, - 0x00060005,0x0000021c,0x65676465,0x69726156,0x6f697461,0x0000006e,0x00070005,0x00000234, - 0x616c6162,0x6465636e,0x736f7243,0x676e6973,0x00000000,0x00060005,0x00000244,0x70646e65, - 0x746e696f,0x74746150,0x006e7265,0x00060005,0x00000250,0x70646e65,0x746e696f,0x61657241, - 0x00000000,0x00050005,0x00000257,0x61657261,0x67696557,0x00007468,0x00070005,0x00000260, - 0x67616964,0x6c616e6f,0x746e6f43,0x74736172,0x00000000,0x00060005,0x00000298,0x6e726f63, - 0x61467265,0x726f7463,0x00000000,0x00050005,0x000002a2,0x65736162,0x67696557,0x00007468, - 0x00070005,0x000002aa,0x67616964,0x6c616e6f,0x65727453,0x6874676e,0x00000000,0x00060005, - 0x000002ae,0x67616964,0x6c616e6f,0x74746150,0x006e7265,0x00070005,0x000002b4,0x67616964, - 0x6c616e6f,0x746e6f43,0x69756e69,0x00007974,0x00080005,0x000002b7,0x726f6873,0x61694474, - 0x616e6f67,0x6c61466c,0x6361626c,0x0000006b,0x00070005,0x000002c6,0x67616964,0x6c616e6f, - 0x6c6c6146,0x6b636162,0x00000000,0x00040005,0x000002d6,0x67696577,0x00007468,0x00040047, - 0x00000034,0x00000021,0x00000000,0x00040047,0x00000034,0x00000022,0x00000000,0x00030047, - 0x00000085,0x00000002,0x00050048,0x00000085,0x00000000,0x00000023,0x00000000,0x00050048, - 0x00000085,0x00000001,0x00000023,0x00000010,0x00050048,0x00000085,0x00000002,0x00000023, - 0x00000018,0x00050048,0x00000085,0x00000003,0x00000023,0x0000001c,0x00040047,0x000000cb, - 0x0000001e,0x00000000,0x00040047,0x000000fd,0x0000001e,0x00000000,0x00020013,0x00000002, - 0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007, - 0x00000006,0x00000002,0x00040020,0x00000008,0x00000007,0x00000007,0x00040017,0x00000009, - 0x00000006,0x00000004,0x00050021,0x0000000a,0x00000009,0x00000008,0x00000008,0x00050021, - 0x0000000f,0x00000006,0x00000008,0x00000008,0x00020014,0x00000018,0x00040020,0x00000019, - 0x00000007,0x00000018,0x00040020,0x0000001a,0x00000007,0x00000006,0x00090021,0x0000001b, - 0x00000006,0x00000008,0x00000008,0x00000008,0x00000019,0x0000001a,0x00000019,0x0004002b, - 0x00000006,0x00000027,0x3f000000,0x0004002b,0x00000006,0x00000029,0x3f800000,0x0005002c, - 0x00000007,0x0000002a,0x00000029,0x00000029,0x00040020,0x0000002f,0x00000007,0x00000009, - 0x00090019,0x00000031,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,0x00000001, - 0x00000000,0x0003001b,0x00000032,0x00000031,0x00040020,0x00000033,0x00000000,0x00000032, - 0x0004003b,0x00000033,0x00000034,0x00000000,0x0004002b,0x00000006,0x00000037,0x00000000, - 0x00040015,0x00000039,0x00000020,0x00000000,0x0004002b,0x00000039,0x0000003a,0x00000001, - 0x0004002b,0x00000039,0x00000045,0x00000003,0x0004002b,0x00000039,0x00000053,0x00000000, - 0x0004002b,0x00000039,0x00000061,0x00000002,0x00040015,0x0000006a,0x00000020,0x00000001, - 0x00040020,0x0000006b,0x00000007,0x0000006a,0x0004002b,0x0000006a,0x0000006d,0x00000001, - 0x0004002b,0x0000006a,0x00000074,0x00000006,0x0004002b,0x00000006,0x0000007d,0xbf800000, - 0x00040017,0x00000081,0x0000006a,0x00000002,0x00040020,0x00000082,0x00000007,0x00000081, - 0x0006001e,0x00000085,0x00000009,0x00000007,0x00000006,0x00000006,0x00040020,0x00000086, - 0x00000009,0x00000085,0x0004003b,0x00000086,0x00000087,0x00000009,0x00040020,0x00000088, - 0x00000009,0x00000007,0x0004002b,0x0000006a,0x00000093,0x00000000,0x0005002c,0x00000081, - 0x00000094,0x00000093,0x00000093,0x00040017,0x00000095,0x00000018,0x00000002,0x0004002b, - 0x00000006,0x000000b6,0x3f266666,0x00040020,0x000000ca,0x00000001,0x00000007,0x0004003b, - 0x000000ca,0x000000cb,0x00000001,0x0004002b,0x00000006,0x000000f2,0x3d3851ec,0x0004002b, - 0x00000006,0x000000f4,0x3df5c28f,0x00040020,0x000000fc,0x00000003,0x00000009,0x0004003b, - 0x000000fc,0x000000fd,0x00000003,0x0007002c,0x00000009,0x000000fe,0x00000037,0x00000027, - 0x00000027,0x00000037,0x0003002a,0x00000018,0x00000103,0x00030029,0x00000018,0x0000010a, - 0x0004002b,0x00000006,0x0000019a,0x40200000,0x0004002b,0x00000006,0x00000236,0x3c23d70a, - 0x0004002b,0x00000006,0x00000253,0x3d6147ae,0x0004002b,0x00000006,0x00000258,0x3ec28f5c, - 0x0004002b,0x00000006,0x0000025c,0x40800000,0x0004002b,0x00000006,0x00000299,0x3eb33333, - 0x0004002b,0x00000006,0x0000029c,0x40400000,0x0004002b,0x00000006,0x000002c7,0x3e23d70a, - 0x0004002b,0x00000006,0x000002da,0x3ed70a3d,0x00050036,0x00000002,0x00000004,0x00000000, - 0x00000003,0x000200f8,0x00000005,0x0004003b,0x00000008,0x000000c3,0x00000007,0x0004003b, - 0x00000008,0x000000c9,0x00000007,0x0004003b,0x0000002f,0x000000d3,0x00000007,0x0004003b, - 0x00000008,0x000000d4,0x00000007,0x0004003b,0x00000008,0x000000d6,0x00000007,0x0004003b, - 0x0000001a,0x000000d9,0x00000007,0x0004003b,0x0000001a,0x000000dc,0x00000007,0x0004003b, - 0x0000001a,0x000000df,0x00000007,0x0004003b,0x0000001a,0x000000e2,0x00000007,0x0004003b, - 0x0000001a,0x000000e5,0x00000007,0x0004003b,0x0000001a,0x000000e9,0x00000007,0x0004003b, - 0x0000001a,0x000000ed,0x00000007,0x0004003b,0x0000001a,0x000000f1,0x00000007,0x0004003b, - 0x0000001a,0x00000100,0x00000007,0x0004003b,0x0000001a,0x00000101,0x00000007,0x0004003b, - 0x00000019,0x00000102,0x00000007,0x0004003b,0x00000019,0x00000109,0x00000007,0x0004003b, - 0x0000001a,0x00000112,0x00000007,0x0004003b,0x00000008,0x00000116,0x00000007,0x0004003b, - 0x00000008,0x00000118,0x00000007,0x0004003b,0x00000008,0x0000011a,0x00000007,0x0004003b, - 0x00000019,0x0000011b,0x00000007,0x0004003b,0x0000001a,0x0000011c,0x00000007,0x0004003b, - 0x00000019,0x0000011e,0x00000007,0x0004003b,0x0000001a,0x00000120,0x00000007,0x0004003b, - 0x00000008,0x00000124,0x00000007,0x0004003b,0x00000008,0x00000126,0x00000007,0x0004003b, - 0x00000008,0x00000128,0x00000007,0x0004003b,0x00000019,0x00000129,0x00000007,0x0004003b, - 0x0000001a,0x0000012a,0x00000007,0x0004003b,0x00000019,0x0000012c,0x00000007,0x0004003b, - 0x0000001a,0x0000012e,0x00000007,0x0004003b,0x00000008,0x00000132,0x00000007,0x0004003b, - 0x00000008,0x00000134,0x00000007,0x0004003b,0x00000008,0x00000136,0x00000007,0x0004003b, - 0x00000019,0x00000137,0x00000007,0x0004003b,0x0000001a,0x00000138,0x00000007,0x0004003b, - 0x00000019,0x0000013a,0x00000007,0x0004003b,0x0000001a,0x0000013c,0x00000007,0x0004003b, - 0x00000008,0x00000140,0x00000007,0x0004003b,0x00000008,0x00000142,0x00000007,0x0004003b, - 0x00000008,0x00000144,0x00000007,0x0004003b,0x00000019,0x00000145,0x00000007,0x0004003b, - 0x0000001a,0x00000146,0x00000007,0x0004003b,0x00000019,0x00000148,0x00000007,0x0004003b, - 0x00000008,0x00000159,0x00000007,0x0004003b,0x00000008,0x0000015b,0x00000007,0x0004003b, - 0x00000008,0x00000166,0x00000007,0x0004003b,0x00000008,0x00000168,0x00000007,0x0004003b, - 0x00000008,0x0000017b,0x00000007,0x0004003b,0x00000008,0x0000017d,0x00000007,0x0004003b, - 0x00000008,0x0000017f,0x00000007,0x0004003b,0x00000019,0x00000181,0x00000007,0x0004003b, - 0x0000001a,0x00000183,0x00000007,0x0004003b,0x00000019,0x00000185,0x00000007,0x0004003b, - 0x00000008,0x00000187,0x00000007,0x0004003b,0x00000008,0x00000189,0x00000007,0x0004003b, - 0x00000008,0x0000018b,0x00000007,0x0004003b,0x00000019,0x0000018d,0x00000007,0x0004003b, - 0x0000001a,0x0000018f,0x00000007,0x0004003b,0x00000019,0x00000191,0x00000007,0x0004003b, - 0x0000001a,0x00000193,0x00000007,0x0004003b,0x0000001a,0x00000197,0x00000007,0x0004003b, - 0x0000002f,0x0000019e,0x00000007,0x0004003b,0x00000008,0x000001a8,0x00000007,0x0004003b, - 0x00000008,0x000001a9,0x00000007,0x0004003b,0x0000002f,0x000001ac,0x00000007,0x0004003b, - 0x00000008,0x000001b5,0x00000007,0x0004003b,0x00000008,0x000001b6,0x00000007,0x0004003b, - 0x0000002f,0x000001b9,0x00000007,0x0004003b,0x00000008,0x000001c2,0x00000007,0x0004003b, - 0x00000008,0x000001c3,0x00000007,0x0004003b,0x0000002f,0x000001c6,0x00000007,0x0004003b, - 0x00000008,0x000001ce,0x00000007,0x0004003b,0x00000008,0x000001cf,0x00000007,0x0004003b, - 0x0000001a,0x000001d2,0x00000007,0x0004003b,0x0000001a,0x000001db,0x00000007,0x0004003b, - 0x0000001a,0x000001dd,0x00000007,0x0004003b,0x0000001a,0x000001ee,0x00000007,0x0004003b, - 0x0000001a,0x000001f0,0x00000007,0x0004003b,0x0000001a,0x00000201,0x00000007,0x0004003b, - 0x0000001a,0x00000206,0x00000007,0x0004003b,0x0000002f,0x0000020c,0x00000007,0x0004003b, - 0x0000002f,0x00000214,0x00000007,0x0004003b,0x0000001a,0x0000021c,0x00000007,0x0004003b, - 0x0000001a,0x00000234,0x00000007,0x0004003b,0x0000001a,0x00000238,0x00000007,0x0004003b, - 0x0000001a,0x00000244,0x00000007,0x0004003b,0x0000001a,0x00000247,0x00000007,0x0004003b, - 0x0000001a,0x00000250,0x00000007,0x0004003b,0x0000001a,0x00000257,0x00000007,0x0004003b, - 0x0000001a,0x00000260,0x00000007,0x0004003b,0x0000001a,0x00000298,0x00000007,0x0004003b, - 0x0000001a,0x000002a2,0x00000007,0x0004003b,0x0000001a,0x000002aa,0x00000007,0x0004003b, - 0x0000001a,0x000002ae,0x00000007,0x0004003b,0x0000001a,0x000002b4,0x00000007,0x0004003b, - 0x0000001a,0x000002b7,0x00000007,0x0004003b,0x0000001a,0x000002c6,0x00000007,0x0004003b, - 0x0000001a,0x000002d6,0x00000007,0x00050041,0x00000088,0x000000c4,0x00000087,0x0000006d, - 0x0004003d,0x00000007,0x000000c5,0x000000c4,0x0007000c,0x00000007,0x000000c6,0x00000001, - 0x00000028,0x000000c5,0x0000002a,0x00050050,0x00000007,0x000000c7,0x00000029,0x00000029, - 0x00050088,0x00000007,0x000000c8,0x000000c7,0x000000c6,0x0003003e,0x000000c3,0x000000c8, - 0x0004003d,0x00000007,0x000000cc,0x000000cb,0x0004003d,0x00000007,0x000000cd,0x000000c3, - 0x0005008e,0x00000007,0x000000ce,0x000000cd,0x00000027,0x0004003d,0x00000007,0x000000cf, - 0x000000c3,0x0005008e,0x00000007,0x000000d0,0x000000cf,0x00000027,0x00050083,0x00000007, - 0x000000d1,0x0000002a,0x000000d0,0x0008000c,0x00000007,0x000000d2,0x00000001,0x0000002b, - 0x000000cc,0x000000ce,0x000000d1,0x0003003e,0x000000c9,0x000000d2,0x0004003d,0x00000007, - 0x000000d5,0x000000c9,0x0003003e,0x000000d4,0x000000d5,0x0004003d,0x00000007,0x000000d7, - 0x000000c3,0x0003003e,0x000000d6,0x000000d7,0x00060039,0x00000009,0x000000d8,0x0000000d, - 0x000000d4,0x000000d6,0x0003003e,0x000000d3,0x000000d8,0x00050041,0x0000001a,0x000000da, - 0x000000d3,0x00000053,0x0004003d,0x00000006,0x000000db,0x000000da,0x0003003e,0x000000d9, - 0x000000db,0x00050041,0x0000001a,0x000000dd,0x000000d3,0x0000003a,0x0004003d,0x00000006, - 0x000000de,0x000000dd,0x0003003e,0x000000dc,0x000000de,0x00050041,0x0000001a,0x000000e0, - 0x000000d3,0x00000061,0x0004003d,0x00000006,0x000000e1,0x000000e0,0x0003003e,0x000000df, - 0x000000e1,0x00050041,0x0000001a,0x000000e3,0x000000d3,0x00000045,0x0004003d,0x00000006, - 0x000000e4,0x000000e3,0x0003003e,0x000000e2,0x000000e4,0x0004003d,0x00000006,0x000000e6, - 0x000000d9,0x0004003d,0x00000006,0x000000e7,0x000000dc,0x0007000c,0x00000006,0x000000e8, - 0x00000001,0x00000028,0x000000e6,0x000000e7,0x0003003e,0x000000e5,0x000000e8,0x0004003d, - 0x00000006,0x000000ea,0x000000df,0x0004003d,0x00000006,0x000000eb,0x000000e2,0x0007000c, - 0x00000006,0x000000ec,0x00000001,0x00000028,0x000000ea,0x000000eb,0x0003003e,0x000000e9, - 0x000000ec,0x0004003d,0x00000006,0x000000ee,0x000000e5,0x0004003d,0x00000006,0x000000ef, - 0x000000e9,0x0007000c,0x00000006,0x000000f0,0x00000001,0x00000028,0x000000ee,0x000000ef, - 0x0003003e,0x000000ed,0x000000f0,0x0004003d,0x00000006,0x000000f3,0x000000ed,0x00050085, - 0x00000006,0x000000f5,0x000000f3,0x000000f4,0x0007000c,0x00000006,0x000000f6,0x00000001, - 0x00000028,0x000000f2,0x000000f5,0x0003003e,0x000000f1,0x000000f6,0x0004003d,0x00000006, - 0x000000f7,0x000000ed,0x0004003d,0x00000006,0x000000f8,0x000000f1,0x000500bc,0x00000018, - 0x000000f9,0x000000f7,0x000000f8,0x000300f7,0x000000fb,0x00000000,0x000400fa,0x000000f9, - 0x000000fa,0x000000fb,0x000200f8,0x000000fa,0x0003003e,0x000000fd,0x000000fe,0x000100fd, - 0x000200f8,0x000000fb,0x0003003e,0x00000100,0x00000037,0x0003003e,0x00000101,0x00000037, - 0x0003003e,0x00000102,0x00000103,0x0004003d,0x00000006,0x00000104,0x000000e5,0x0004003d, - 0x00000006,0x00000105,0x000000e9,0x000500ba,0x00000018,0x00000106,0x00000104,0x00000105, - 0x000300f7,0x00000108,0x00000000,0x000400fa,0x00000106,0x00000107,0x0000010b,0x000200f8, - 0x00000107,0x0003003e,0x00000109,0x0000010a,0x000200f9,0x00000108,0x000200f8,0x0000010b, - 0x0004003d,0x00000006,0x0000010c,0x000000e9,0x0004003d,0x00000006,0x0000010d,0x000000e5, - 0x000500ba,0x00000018,0x0000010e,0x0000010c,0x0000010d,0x000300f7,0x00000110,0x00000000, - 0x000400fa,0x0000010e,0x0000010f,0x00000111,0x000200f8,0x0000010f,0x0003003e,0x00000109, - 0x00000103,0x000200f9,0x00000110,0x000200f8,0x00000111,0x00050041,0x0000001a,0x00000113, - 0x000000c3,0x0000003a,0x0004003d,0x00000006,0x00000114,0x00000113,0x00050050,0x00000007, - 0x00000115,0x00000037,0x00000114,0x0004003d,0x00000007,0x00000117,0x000000c9,0x0003003e, - 0x00000116,0x00000117,0x0004003d,0x00000007,0x00000119,0x000000c3,0x0003003e,0x00000118, - 0x00000119,0x0003003e,0x0000011a,0x00000115,0x0003003e,0x0000011b,0x0000010a,0x0004003d, - 0x00000006,0x0000011d,0x000000f1,0x0003003e,0x0000011c,0x0000011d,0x0003003e,0x0000011e, - 0x00000103,0x000a0039,0x00000006,0x0000011f,0x00000022,0x00000116,0x00000118,0x0000011a, - 0x0000011b,0x0000011c,0x0000011e,0x0003003e,0x00000112,0x0000011f,0x00050041,0x0000001a, - 0x00000121,0x000000c3,0x0000003a,0x0004003d,0x00000006,0x00000122,0x00000121,0x00050050, - 0x00000007,0x00000123,0x00000037,0x00000122,0x0004003d,0x00000007,0x00000125,0x000000c9, - 0x0003003e,0x00000124,0x00000125,0x0004003d,0x00000007,0x00000127,0x000000c3,0x0003003e, - 0x00000126,0x00000127,0x0003003e,0x00000128,0x00000123,0x0003003e,0x00000129,0x0000010a, - 0x0004003d,0x00000006,0x0000012b,0x000000f1,0x0003003e,0x0000012a,0x0000012b,0x0003003e, - 0x0000012c,0x0000010a,0x000a0039,0x00000006,0x0000012d,0x00000022,0x00000124,0x00000126, - 0x00000128,0x00000129,0x0000012a,0x0000012c,0x0003003e,0x00000120,0x0000012d,0x00050041, - 0x0000001a,0x0000012f,0x000000c3,0x00000053,0x0004003d,0x00000006,0x00000130,0x0000012f, - 0x00050050,0x00000007,0x00000131,0x00000130,0x00000037,0x0004003d,0x00000007,0x00000133, - 0x000000c9,0x0003003e,0x00000132,0x00000133,0x0004003d,0x00000007,0x00000135,0x000000c3, - 0x0003003e,0x00000134,0x00000135,0x0003003e,0x00000136,0x00000131,0x0003003e,0x00000137, - 0x00000103,0x0004003d,0x00000006,0x00000139,0x000000f1,0x0003003e,0x00000138,0x00000139, - 0x0003003e,0x0000013a,0x00000103,0x000a0039,0x00000006,0x0000013b,0x00000022,0x00000132, - 0x00000134,0x00000136,0x00000137,0x00000138,0x0000013a,0x0003003e,0x0000012e,0x0000013b, - 0x00050041,0x0000001a,0x0000013d,0x000000c3,0x00000053,0x0004003d,0x00000006,0x0000013e, - 0x0000013d,0x00050050,0x00000007,0x0000013f,0x0000013e,0x00000037,0x0004003d,0x00000007, - 0x00000141,0x000000c9,0x0003003e,0x00000140,0x00000141,0x0004003d,0x00000007,0x00000143, - 0x000000c3,0x0003003e,0x00000142,0x00000143,0x0003003e,0x00000144,0x0000013f,0x0003003e, - 0x00000145,0x00000103,0x0004003d,0x00000006,0x00000147,0x000000f1,0x0003003e,0x00000146, - 0x00000147,0x0003003e,0x00000148,0x0000010a,0x000a0039,0x00000006,0x00000149,0x00000022, - 0x00000140,0x00000142,0x00000144,0x00000145,0x00000146,0x00000148,0x0003003e,0x0000013c, - 0x00000149,0x0004003d,0x00000006,0x0000014a,0x00000112,0x0004003d,0x00000006,0x0000014b, - 0x00000120,0x00050081,0x00000006,0x0000014c,0x0000014a,0x0000014b,0x0004003d,0x00000006, - 0x0000014d,0x0000012e,0x0004003d,0x00000006,0x0000014e,0x0000013c,0x00050081,0x00000006, - 0x0000014f,0x0000014d,0x0000014e,0x000500be,0x00000018,0x00000150,0x0000014c,0x0000014f, - 0x0003003e,0x00000109,0x00000150,0x0004003d,0x00000018,0x00000151,0x00000109,0x0004003d, - 0x00000006,0x00000152,0x00000112,0x0004003d,0x00000006,0x00000153,0x0000012e,0x000600a9, - 0x00000006,0x00000154,0x00000151,0x00000152,0x00000153,0x0003003e,0x00000100,0x00000154, - 0x0004003d,0x00000018,0x00000155,0x00000109,0x0004003d,0x00000006,0x00000156,0x00000120, - 0x0004003d,0x00000006,0x00000157,0x0000013c,0x000600a9,0x00000006,0x00000158,0x00000155, - 0x00000156,0x00000157,0x0003003e,0x00000101,0x00000158,0x0003003e,0x00000102,0x0000010a, - 0x000200f9,0x00000110,0x000200f8,0x00000110,0x000200f9,0x00000108,0x000200f8,0x00000108, - 0x0004003d,0x00000018,0x0000015a,0x00000109,0x000300f7,0x0000015d,0x00000000,0x000400fa, - 0x0000015a,0x0000015c,0x00000161,0x000200f8,0x0000015c,0x00050041,0x0000001a,0x0000015e, - 0x000000c3,0x0000003a,0x0004003d,0x00000006,0x0000015f,0x0000015e,0x00050050,0x00000007, - 0x00000160,0x00000037,0x0000015f,0x0003003e,0x0000015b,0x00000160,0x000200f9,0x0000015d, - 0x000200f8,0x00000161,0x00050041,0x0000001a,0x00000162,0x000000c3,0x00000053,0x0004003d, - 0x00000006,0x00000163,0x00000162,0x00050050,0x00000007,0x00000164,0x00000163,0x00000037, - 0x0003003e,0x0000015b,0x00000164,0x000200f9,0x0000015d,0x000200f8,0x0000015d,0x0004003d, - 0x00000007,0x00000165,0x0000015b,0x0003003e,0x00000159,0x00000165,0x0004003d,0x00000018, - 0x00000167,0x00000109,0x000300f7,0x0000016a,0x00000000,0x000400fa,0x00000167,0x00000169, - 0x00000170,0x000200f8,0x00000169,0x0004003d,0x00000006,0x0000016b,0x000000d9,0x0004003d, - 0x00000006,0x0000016c,0x000000dc,0x000500be,0x00000018,0x0000016d,0x0000016b,0x0000016c, - 0x000600a9,0x00000006,0x0000016e,0x0000016d,0x0000007d,0x00000029,0x00050050,0x00000007, - 0x0000016f,0x0000016e,0x00000037,0x0003003e,0x00000168,0x0000016f,0x000200f9,0x0000016a, - 0x000200f8,0x00000170,0x0004003d,0x00000006,0x00000171,0x000000df,0x0004003d,0x00000006, - 0x00000172,0x000000e2,0x000500be,0x00000018,0x00000173,0x00000171,0x00000172,0x000600a9, - 0x00000006,0x00000174,0x00000173,0x0000007d,0x00000029,0x00050050,0x00000007,0x00000175, - 0x00000037,0x00000174,0x0003003e,0x00000168,0x00000175,0x000200f9,0x0000016a,0x000200f8, - 0x0000016a,0x0004003d,0x00000007,0x00000176,0x00000168,0x0003003e,0x00000166,0x00000176, - 0x0004003d,0x00000018,0x00000177,0x00000102,0x000400a8,0x00000018,0x00000178,0x00000177, - 0x000300f7,0x0000017a,0x00000000,0x000400fa,0x00000178,0x00000179,0x0000017a,0x000200f8, - 0x00000179,0x0004003d,0x00000007,0x0000017c,0x000000c9,0x0003003e,0x0000017b,0x0000017c, - 0x0004003d,0x00000007,0x0000017e,0x000000c3,0x0003003e,0x0000017d,0x0000017e,0x0004003d, - 0x00000007,0x00000180,0x00000159,0x0003003e,0x0000017f,0x00000180,0x0004003d,0x00000018, - 0x00000182,0x00000109,0x0003003e,0x00000181,0x00000182,0x0004003d,0x00000006,0x00000184, - 0x000000f1,0x0003003e,0x00000183,0x00000184,0x0003003e,0x00000185,0x00000103,0x000a0039, - 0x00000006,0x00000186,0x00000022,0x0000017b,0x0000017d,0x0000017f,0x00000181,0x00000183, - 0x00000185,0x0003003e,0x00000100,0x00000186,0x0004003d,0x00000007,0x00000188,0x000000c9, - 0x0003003e,0x00000187,0x00000188,0x0004003d,0x00000007,0x0000018a,0x000000c3,0x0003003e, - 0x00000189,0x0000018a,0x0004003d,0x00000007,0x0000018c,0x00000159,0x0003003e,0x0000018b, - 0x0000018c,0x0004003d,0x00000018,0x0000018e,0x00000109,0x0003003e,0x0000018d,0x0000018e, - 0x0004003d,0x00000006,0x00000190,0x000000f1,0x0003003e,0x0000018f,0x00000190,0x0003003e, - 0x00000191,0x0000010a,0x000a0039,0x00000006,0x00000192,0x00000022,0x00000187,0x00000189, - 0x0000018b,0x0000018d,0x0000018f,0x00000191,0x0003003e,0x00000101,0x00000192,0x000200f9, - 0x0000017a,0x000200f8,0x0000017a,0x0004003d,0x00000006,0x00000194,0x00000100,0x0004003d, - 0x00000006,0x00000195,0x00000101,0x00050081,0x00000006,0x00000196,0x00000194,0x00000195, - 0x0003003e,0x00000193,0x00000196,0x0004003d,0x00000006,0x00000198,0x000000f1,0x0004003d, - 0x00000006,0x00000199,0x000000f1,0x00050085,0x00000006,0x0000019b,0x00000199,0x0000019a, - 0x0004003d,0x00000006,0x0000019c,0x000000ed,0x0008000c,0x00000006,0x0000019d,0x00000001, - 0x00000031,0x00000198,0x0000019b,0x0000019c,0x0003003e,0x00000197,0x0000019d,0x0004003d, - 0x00000007,0x0000019f,0x000000c9,0x00050041,0x0000001a,0x000001a0,0x000000c3,0x00000053, - 0x0004003d,0x00000006,0x000001a1,0x000001a0,0x0004007f,0x00000006,0x000001a2,0x000001a1, - 0x00050041,0x0000001a,0x000001a3,0x000000c3,0x0000003a,0x0004003d,0x00000006,0x000001a4, - 0x000001a3,0x0004007f,0x00000006,0x000001a5,0x000001a4,0x00050050,0x00000007,0x000001a6, - 0x000001a2,0x000001a5,0x00050081,0x00000007,0x000001a7,0x0000019f,0x000001a6,0x0003003e, - 0x000001a8,0x000001a7,0x0004003d,0x00000007,0x000001aa,0x000000c3,0x0003003e,0x000001a9, - 0x000001aa,0x00060039,0x00000009,0x000001ab,0x0000000d,0x000001a8,0x000001a9,0x0003003e, - 0x0000019e,0x000001ab,0x0004003d,0x00000007,0x000001ad,0x000000c9,0x00050041,0x0000001a, - 0x000001ae,0x000000c3,0x00000053,0x0004003d,0x00000006,0x000001af,0x000001ae,0x00050041, - 0x0000001a,0x000001b0,0x000000c3,0x0000003a,0x0004003d,0x00000006,0x000001b1,0x000001b0, - 0x0004007f,0x00000006,0x000001b2,0x000001b1,0x00050050,0x00000007,0x000001b3,0x000001af, - 0x000001b2,0x00050081,0x00000007,0x000001b4,0x000001ad,0x000001b3,0x0003003e,0x000001b5, - 0x000001b4,0x0004003d,0x00000007,0x000001b7,0x000000c3,0x0003003e,0x000001b6,0x000001b7, - 0x00060039,0x00000009,0x000001b8,0x0000000d,0x000001b5,0x000001b6,0x0003003e,0x000001ac, - 0x000001b8,0x0004003d,0x00000007,0x000001ba,0x000000c9,0x00050041,0x0000001a,0x000001bb, - 0x000000c3,0x00000053,0x0004003d,0x00000006,0x000001bc,0x000001bb,0x0004007f,0x00000006, - 0x000001bd,0x000001bc,0x00050041,0x0000001a,0x000001be,0x000000c3,0x0000003a,0x0004003d, - 0x00000006,0x000001bf,0x000001be,0x00050050,0x00000007,0x000001c0,0x000001bd,0x000001bf, - 0x00050081,0x00000007,0x000001c1,0x000001ba,0x000001c0,0x0003003e,0x000001c2,0x000001c1, - 0x0004003d,0x00000007,0x000001c4,0x000000c3,0x0003003e,0x000001c3,0x000001c4,0x00060039, - 0x00000009,0x000001c5,0x0000000d,0x000001c2,0x000001c3,0x0003003e,0x000001b9,0x000001c5, - 0x0004003d,0x00000007,0x000001c7,0x000000c9,0x00050041,0x0000001a,0x000001c8,0x000000c3, - 0x00000053,0x0004003d,0x00000006,0x000001c9,0x000001c8,0x00050041,0x0000001a,0x000001ca, - 0x000000c3,0x0000003a,0x0004003d,0x00000006,0x000001cb,0x000001ca,0x00050050,0x00000007, - 0x000001cc,0x000001c9,0x000001cb,0x00050081,0x00000007,0x000001cd,0x000001c7,0x000001cc, - 0x0003003e,0x000001ce,0x000001cd,0x0004003d,0x00000007,0x000001d0,0x000000c3,0x0003003e, - 0x000001cf,0x000001d0,0x00060039,0x00000009,0x000001d1,0x0000000d,0x000001ce,0x000001cf, - 0x0003003e,0x000001c6,0x000001d1,0x0004003d,0x00000006,0x000001d3,0x00000100,0x0004003d, - 0x00000006,0x000001d4,0x00000101,0x00050083,0x00000006,0x000001d5,0x000001d3,0x000001d4, - 0x0006000c,0x00000006,0x000001d6,0x00000001,0x00000004,0x000001d5,0x0004003d,0x00000006, - 0x000001d7,0x00000193,0x0007000c,0x00000006,0x000001d8,0x00000001,0x00000028,0x000001d7, - 0x00000029,0x00050088,0x00000006,0x000001d9,0x000001d6,0x000001d8,0x0008000c,0x00000006, - 0x000001da,0x00000001,0x0000002b,0x000001d9,0x00000037,0x00000029,0x0003003e,0x000001d2, - 0x000001da,0x0004003d,0x00000018,0x000001dc,0x00000109,0x000300f7,0x000001df,0x00000000, - 0x000400fa,0x000001dc,0x000001de,0x000001e6,0x000200f8,0x000001de,0x00050041,0x0000001a, - 0x000001e0,0x0000019e,0x00000045,0x0004003d,0x00000006,0x000001e1,0x000001e0,0x00050041, - 0x0000001a,0x000001e2,0x000001ac,0x00000045,0x0004003d,0x00000006,0x000001e3,0x000001e2, - 0x00050083,0x00000006,0x000001e4,0x000001e1,0x000001e3,0x0006000c,0x00000006,0x000001e5, - 0x00000001,0x00000004,0x000001e4,0x0003003e,0x000001dd,0x000001e5,0x000200f9,0x000001df, - 0x000200f8,0x000001e6,0x00050041,0x0000001a,0x000001e7,0x0000019e,0x0000003a,0x0004003d, - 0x00000006,0x000001e8,0x000001e7,0x00050041,0x0000001a,0x000001e9,0x000001b9,0x0000003a, - 0x0004003d,0x00000006,0x000001ea,0x000001e9,0x00050083,0x00000006,0x000001eb,0x000001e8, - 0x000001ea,0x0006000c,0x00000006,0x000001ec,0x00000001,0x00000004,0x000001eb,0x0003003e, - 0x000001dd,0x000001ec,0x000200f9,0x000001df,0x000200f8,0x000001df,0x0004003d,0x00000006, - 0x000001ed,0x000001dd,0x0003003e,0x000001db,0x000001ed,0x0004003d,0x00000018,0x000001ef, - 0x00000109,0x000300f7,0x000001f2,0x00000000,0x000400fa,0x000001ef,0x000001f1,0x000001f9, - 0x000200f8,0x000001f1,0x00050041,0x0000001a,0x000001f3,0x000001b9,0x00000061,0x0004003d, - 0x00000006,0x000001f4,0x000001f3,0x00050041,0x0000001a,0x000001f5,0x000001c6,0x00000061, - 0x0004003d,0x00000006,0x000001f6,0x000001f5,0x00050083,0x00000006,0x000001f7,0x000001f4, - 0x000001f6,0x0006000c,0x00000006,0x000001f8,0x00000001,0x00000004,0x000001f7,0x0003003e, - 0x000001f0,0x000001f8,0x000200f9,0x000001f2,0x000200f8,0x000001f9,0x00050041,0x0000001a, - 0x000001fa,0x000001ac,0x00000053,0x0004003d,0x00000006,0x000001fb,0x000001fa,0x00050041, - 0x0000001a,0x000001fc,0x000001c6,0x00000053,0x0004003d,0x00000006,0x000001fd,0x000001fc, - 0x00050083,0x00000006,0x000001fe,0x000001fb,0x000001fd,0x0006000c,0x00000006,0x000001ff, - 0x00000001,0x00000004,0x000001fe,0x0003003e,0x000001f0,0x000001ff,0x000200f9,0x000001f2, - 0x000200f8,0x000001f2,0x0004003d,0x00000006,0x00000200,0x000001f0,0x0003003e,0x000001ee, - 0x00000200,0x0004003d,0x00000006,0x00000202,0x000001db,0x0004003d,0x00000006,0x00000203, - 0x000001ee,0x00050083,0x00000006,0x00000204,0x00000202,0x00000203,0x0006000c,0x00000006, - 0x00000205,0x00000001,0x00000004,0x00000204,0x0003003e,0x00000201,0x00000205,0x0004003d, - 0x00000006,0x00000207,0x000000f1,0x0004003d,0x00000006,0x00000208,0x000000f1,0x00050085, - 0x00000006,0x00000209,0x00000208,0x0000019a,0x0004003d,0x00000006,0x0000020a,0x00000201, - 0x0008000c,0x00000006,0x0000020b,0x00000001,0x00000031,0x00000207,0x00000209,0x0000020a, - 0x0003003e,0x00000206,0x0000020b,0x0004003d,0x00000009,0x0000020d,0x0000019e,0x0004003d, - 0x00000009,0x0000020e,0x000001ac,0x0007000c,0x00000009,0x0000020f,0x00000001,0x00000025, - 0x0000020d,0x0000020e,0x0004003d,0x00000009,0x00000210,0x000001b9,0x0004003d,0x00000009, - 0x00000211,0x000001c6,0x0007000c,0x00000009,0x00000212,0x00000001,0x00000025,0x00000210, - 0x00000211,0x0007000c,0x00000009,0x00000213,0x00000001,0x00000025,0x0000020f,0x00000212, - 0x0003003e,0x0000020c,0x00000213,0x0004003d,0x00000009,0x00000215,0x0000019e,0x0004003d, - 0x00000009,0x00000216,0x000001ac,0x0007000c,0x00000009,0x00000217,0x00000001,0x00000028, - 0x00000215,0x00000216,0x0004003d,0x00000009,0x00000218,0x000001b9,0x0004003d,0x00000009, - 0x00000219,0x000001c6,0x0007000c,0x00000009,0x0000021a,0x00000001,0x00000028,0x00000218, - 0x00000219,0x0007000c,0x00000009,0x0000021b,0x00000001,0x00000028,0x00000217,0x0000021a, - 0x0003003e,0x00000214,0x0000021b,0x00050041,0x0000001a,0x0000021d,0x00000214,0x00000053, - 0x0004003d,0x00000006,0x0000021e,0x0000021d,0x00050041,0x0000001a,0x0000021f,0x0000020c, - 0x00000053,0x0004003d,0x00000006,0x00000220,0x0000021f,0x00050083,0x00000006,0x00000221, - 0x0000021e,0x00000220,0x00050041,0x0000001a,0x00000222,0x00000214,0x0000003a,0x0004003d, - 0x00000006,0x00000223,0x00000222,0x00050041,0x0000001a,0x00000224,0x0000020c,0x0000003a, - 0x0004003d,0x00000006,0x00000225,0x00000224,0x00050083,0x00000006,0x00000226,0x00000223, - 0x00000225,0x0007000c,0x00000006,0x00000227,0x00000001,0x00000028,0x00000221,0x00000226, - 0x00050041,0x0000001a,0x00000228,0x00000214,0x00000061,0x0004003d,0x00000006,0x00000229, - 0x00000228,0x00050041,0x0000001a,0x0000022a,0x0000020c,0x00000061,0x0004003d,0x00000006, - 0x0000022b,0x0000022a,0x00050083,0x00000006,0x0000022c,0x00000229,0x0000022b,0x00050041, - 0x0000001a,0x0000022d,0x00000214,0x00000045,0x0004003d,0x00000006,0x0000022e,0x0000022d, - 0x00050041,0x0000001a,0x0000022f,0x0000020c,0x00000045,0x0004003d,0x00000006,0x00000230, - 0x0000022f,0x00050083,0x00000006,0x00000231,0x0000022e,0x00000230,0x0007000c,0x00000006, - 0x00000232,0x00000001,0x00000028,0x0000022c,0x00000231,0x0007000c,0x00000006,0x00000233, - 0x00000001,0x00000028,0x00000227,0x00000232,0x0003003e,0x0000021c,0x00000233,0x0004003d, - 0x00000006,0x00000235,0x0000021c,0x000500ba,0x00000018,0x00000237,0x00000235,0x00000236, - 0x000300f7,0x0000023a,0x00000000,0x000400fa,0x00000237,0x00000239,0x00000242,0x000200f8, - 0x00000239,0x0004003d,0x00000006,0x0000023b,0x000000f1,0x0004003d,0x00000006,0x0000023c, - 0x000000f1,0x00050085,0x00000006,0x0000023d,0x0000023c,0x0000019a,0x0004003d,0x00000006, - 0x0000023e,0x000001db,0x0004003d,0x00000006,0x0000023f,0x000001ee,0x0007000c,0x00000006, - 0x00000240,0x00000001,0x00000025,0x0000023e,0x0000023f,0x0008000c,0x00000006,0x00000241, - 0x00000001,0x00000031,0x0000023b,0x0000023d,0x00000240,0x0003003e,0x00000238,0x00000241, - 0x000200f9,0x0000023a,0x000200f8,0x00000242,0x0003003e,0x00000238,0x00000037,0x000200f9, - 0x0000023a,0x000200f8,0x0000023a,0x0004003d,0x00000006,0x00000243,0x00000238,0x0003003e, - 0x00000234,0x00000243,0x0004003d,0x00000006,0x00000245,0x000001d2,0x000500ba,0x00000018, - 0x00000246,0x00000245,0x00000236,0x000300f7,0x00000249,0x00000000,0x000400fa,0x00000246, - 0x00000248,0x0000024d,0x000200f8,0x00000248,0x0004003d,0x00000006,0x0000024a,0x000001d2, - 0x0004003d,0x00000006,0x0000024b,0x00000234,0x0007000c,0x00000006,0x0000024c,0x00000001, - 0x00000028,0x0000024a,0x0000024b,0x0003003e,0x00000247,0x0000024c,0x000200f9,0x00000249, - 0x000200f8,0x0000024d,0x0004003d,0x00000006,0x0000024e,0x000001d2,0x0003003e,0x00000247, - 0x0000024e,0x000200f9,0x00000249,0x000200f8,0x00000249,0x0004003d,0x00000006,0x0000024f, - 0x00000247,0x0003003e,0x00000244,0x0000024f,0x0004003d,0x00000006,0x00000251,0x00000244, - 0x0004003d,0x00000006,0x00000252,0x00000193,0x00050085,0x00000006,0x00000254,0x00000252, - 0x00000253,0x00050081,0x00000006,0x00000255,0x00000029,0x00000254,0x00050088,0x00000006, - 0x00000256,0x00000251,0x00000255,0x0003003e,0x00000250,0x00000256,0x0004003d,0x00000006, - 0x00000259,0x00000206,0x00050085,0x00000006,0x0000025a,0x00000258,0x00000259,0x0004003d, - 0x00000006,0x0000025b,0x00000193,0x00050088,0x00000006,0x0000025d,0x0000025b,0x0000025c, - 0x0008000c,0x00000006,0x0000025e,0x00000001,0x0000002b,0x0000025d,0x00000037,0x00000029, - 0x00050085,0x00000006,0x0000025f,0x0000025a,0x0000025e,0x0003003e,0x00000257,0x0000025f, - 0x00050041,0x0000001a,0x00000261,0x0000019e,0x00000053,0x0004003d,0x00000006,0x00000262, - 0x00000261,0x00050041,0x0000001a,0x00000263,0x000001c6,0x00000053,0x0004003d,0x00000006, - 0x00000264,0x00000263,0x00050083,0x00000006,0x00000265,0x00000262,0x00000264,0x0006000c, - 0x00000006,0x00000266,0x00000001,0x00000004,0x00000265,0x00050041,0x0000001a,0x00000267, - 0x0000019e,0x0000003a,0x0004003d,0x00000006,0x00000268,0x00000267,0x00050041,0x0000001a, - 0x00000269,0x000001c6,0x0000003a,0x0004003d,0x00000006,0x0000026a,0x00000269,0x00050083, - 0x00000006,0x0000026b,0x00000268,0x0000026a,0x0006000c,0x00000006,0x0000026c,0x00000001, - 0x00000004,0x0000026b,0x0007000c,0x00000006,0x0000026d,0x00000001,0x00000028,0x00000266, - 0x0000026c,0x00050041,0x0000001a,0x0000026e,0x0000019e,0x00000061,0x0004003d,0x00000006, - 0x0000026f,0x0000026e,0x00050041,0x0000001a,0x00000270,0x000001c6,0x00000061,0x0004003d, - 0x00000006,0x00000271,0x00000270,0x00050083,0x00000006,0x00000272,0x0000026f,0x00000271, - 0x0006000c,0x00000006,0x00000273,0x00000001,0x00000004,0x00000272,0x00050041,0x0000001a, - 0x00000274,0x0000019e,0x00000045,0x0004003d,0x00000006,0x00000275,0x00000274,0x00050041, - 0x0000001a,0x00000276,0x000001c6,0x00000045,0x0004003d,0x00000006,0x00000277,0x00000276, - 0x00050083,0x00000006,0x00000278,0x00000275,0x00000277,0x0006000c,0x00000006,0x00000279, - 0x00000001,0x00000004,0x00000278,0x0007000c,0x00000006,0x0000027a,0x00000001,0x00000028, - 0x00000273,0x00000279,0x0007000c,0x00000006,0x0000027b,0x00000001,0x00000028,0x0000026d, - 0x0000027a,0x00050041,0x0000001a,0x0000027c,0x000001ac,0x00000053,0x0004003d,0x00000006, - 0x0000027d,0x0000027c,0x00050041,0x0000001a,0x0000027e,0x000001b9,0x00000053,0x0004003d, - 0x00000006,0x0000027f,0x0000027e,0x00050083,0x00000006,0x00000280,0x0000027d,0x0000027f, - 0x0006000c,0x00000006,0x00000281,0x00000001,0x00000004,0x00000280,0x00050041,0x0000001a, - 0x00000282,0x000001ac,0x0000003a,0x0004003d,0x00000006,0x00000283,0x00000282,0x00050041, - 0x0000001a,0x00000284,0x000001b9,0x0000003a,0x0004003d,0x00000006,0x00000285,0x00000284, - 0x00050083,0x00000006,0x00000286,0x00000283,0x00000285,0x0006000c,0x00000006,0x00000287, - 0x00000001,0x00000004,0x00000286,0x0007000c,0x00000006,0x00000288,0x00000001,0x00000028, - 0x00000281,0x00000287,0x00050041,0x0000001a,0x00000289,0x000001ac,0x00000061,0x0004003d, - 0x00000006,0x0000028a,0x00000289,0x00050041,0x0000001a,0x0000028b,0x000001b9,0x00000061, - 0x0004003d,0x00000006,0x0000028c,0x0000028b,0x00050083,0x00000006,0x0000028d,0x0000028a, - 0x0000028c,0x0006000c,0x00000006,0x0000028e,0x00000001,0x00000004,0x0000028d,0x00050041, - 0x0000001a,0x0000028f,0x000001ac,0x00000045,0x0004003d,0x00000006,0x00000290,0x0000028f, - 0x00050041,0x0000001a,0x00000291,0x000001b9,0x00000045,0x0004003d,0x00000006,0x00000292, - 0x00000291,0x00050083,0x00000006,0x00000293,0x00000290,0x00000292,0x0006000c,0x00000006, - 0x00000294,0x00000001,0x00000004,0x00000293,0x0007000c,0x00000006,0x00000295,0x00000001, - 0x00000028,0x0000028e,0x00000294,0x0007000c,0x00000006,0x00000296,0x00000001,0x00000028, - 0x00000288,0x00000295,0x0007000c,0x00000006,0x00000297,0x00000001,0x00000028,0x0000027b, - 0x00000296,0x0003003e,0x00000260,0x00000297,0x0004003d,0x00000006,0x0000029a,0x000000f1, - 0x0004003d,0x00000006,0x0000029b,0x000000f1,0x00050085,0x00000006,0x0000029d,0x0000029b, - 0x0000029c,0x0004003d,0x00000006,0x0000029e,0x00000260,0x0008000c,0x00000006,0x0000029f, - 0x00000001,0x00000031,0x0000029a,0x0000029d,0x0000029e,0x00050085,0x00000006,0x000002a0, - 0x00000299,0x0000029f,0x00050083,0x00000006,0x000002a1,0x00000029,0x000002a0,0x0003003e, - 0x00000298,0x000002a1,0x0004003d,0x00000006,0x000002a3,0x00000257,0x0004003d,0x00000006, - 0x000002a4,0x00000250,0x00050085,0x00000006,0x000002a5,0x000002a3,0x000002a4,0x0004003d, - 0x00000006,0x000002a6,0x00000197,0x00050085,0x00000006,0x000002a7,0x000002a5,0x000002a6, - 0x0004003d,0x00000006,0x000002a8,0x00000298,0x00050085,0x00000006,0x000002a9,0x000002a7, - 0x000002a8,0x0003003e,0x000002a2,0x000002a9,0x0004003d,0x00000006,0x000002ab,0x000000e5, - 0x0004003d,0x00000006,0x000002ac,0x000000e9,0x0007000c,0x00000006,0x000002ad,0x00000001, - 0x00000025,0x000002ab,0x000002ac,0x0003003e,0x000002aa,0x000002ad,0x0004003d,0x00000006, - 0x000002af,0x000000f1,0x0004003d,0x00000006,0x000002b0,0x000000f1,0x00050085,0x00000006, - 0x000002b1,0x000002b0,0x0000019a,0x0004003d,0x00000006,0x000002b2,0x000002aa,0x0008000c, - 0x00000006,0x000002b3,0x00000001,0x00000031,0x000002af,0x000002b1,0x000002b2,0x0003003e, - 0x000002ae,0x000002b3,0x0004003d,0x00000006,0x000002b5,0x00000193,0x0008000c,0x00000006, - 0x000002b6,0x00000001,0x00000031,0x00000029,0x0000029c,0x000002b5,0x0003003e,0x000002b4, - 0x000002b6,0x0004003d,0x00000006,0x000002b8,0x00000193,0x000500ba,0x00000018,0x000002b9, - 0x000002b8,0x00000037,0x0004003d,0x00000006,0x000002ba,0x00000193,0x000500bc,0x00000018, - 0x000002bb,0x000002ba,0x00000029,0x000500a7,0x00000018,0x000002bc,0x000002b9,0x000002bb, - 0x0004003d,0x00000006,0x000002bd,0x00000201,0x0004003d,0x00000006,0x000002be,0x000000f1, - 0x000500bc,0x00000018,0x000002bf,0x000002bd,0x000002be,0x000500a7,0x00000018,0x000002c0, - 0x000002bc,0x000002bf,0x0004003d,0x00000006,0x000002c1,0x000002aa,0x0004003d,0x00000006, - 0x000002c2,0x000000f1,0x000500ba,0x00000018,0x000002c3,0x000002c1,0x000002c2,0x000500a7, - 0x00000018,0x000002c4,0x000002c0,0x000002c3,0x000600a9,0x00000006,0x000002c5,0x000002c4, - 0x00000029,0x00000037,0x0003003e,0x000002b7,0x000002c5,0x0004003d,0x00000006,0x000002c8, - 0x000002ae,0x00050085,0x00000006,0x000002c9,0x000002c7,0x000002c8,0x0004003d,0x00000006, - 0x000002ca,0x00000197,0x00050085,0x00000006,0x000002cb,0x000002c9,0x000002ca,0x0004003d, - 0x00000006,0x000002cc,0x00000298,0x00050085,0x00000006,0x000002cd,0x000002cb,0x000002cc, - 0x0004003d,0x00000006,0x000002ce,0x000002b4,0x0004003d,0x00000006,0x000002cf,0x00000206, - 0x0004003d,0x00000006,0x000002d0,0x00000234,0x0007000c,0x00000006,0x000002d1,0x00000001, - 0x00000028,0x000002cf,0x000002d0,0x00050085,0x00000006,0x000002d2,0x000002ce,0x000002d1, - 0x0004003d,0x00000006,0x000002d3,0x000002b7,0x0007000c,0x00000006,0x000002d4,0x00000001, - 0x00000028,0x000002d2,0x000002d3,0x00050085,0x00000006,0x000002d5,0x000002cd,0x000002d4, - 0x0003003e,0x000002c6,0x000002d5,0x0004003d,0x00000006,0x000002d7,0x000002a2,0x0004003d, - 0x00000006,0x000002d8,0x000002c6,0x0007000c,0x00000006,0x000002d9,0x00000001,0x00000028, - 0x000002d7,0x000002d8,0x0008000c,0x00000006,0x000002db,0x00000001,0x0000002b,0x000002d9, - 0x00000037,0x000002da,0x0003003e,0x000002d6,0x000002db,0x0004003d,0x00000006,0x000002dc, - 0x000002d6,0x00050041,0x0000001a,0x000002dd,0x00000166,0x00000053,0x0004003d,0x00000006, - 0x000002de,0x000002dd,0x00050085,0x00000006,0x000002df,0x000002de,0x00000027,0x00050081, - 0x00000006,0x000002e0,0x000002df,0x00000027,0x00050041,0x0000001a,0x000002e1,0x00000166, - 0x0000003a,0x0004003d,0x00000006,0x000002e2,0x000002e1,0x00050085,0x00000006,0x000002e3, - 0x000002e2,0x00000027,0x00050081,0x00000006,0x000002e4,0x000002e3,0x00000027,0x00070050, - 0x00000009,0x000002e5,0x000002dc,0x000002e0,0x000002e4,0x00000029,0x0003003e,0x000000fd, - 0x000002e5,0x000100fd,0x00010038,0x00050036,0x00000009,0x0000000d,0x00000000,0x0000000a, - 0x00030037,0x00000008,0x0000000b,0x00030037,0x00000008,0x0000000c,0x000200f8,0x0000000e, - 0x0004003b,0x00000008,0x00000024,0x00000007,0x0004003b,0x0000002f,0x00000030,0x00000007, - 0x0004003b,0x0000001a,0x00000041,0x00000007,0x0004003d,0x00000007,0x00000025,0x0000000b, - 0x0004003d,0x00000007,0x00000026,0x0000000c,0x0005008e,0x00000007,0x00000028,0x00000026, - 0x00000027,0x0004003d,0x00000007,0x0000002b,0x0000000c,0x0005008e,0x00000007,0x0000002c, - 0x0000002b,0x00000027,0x00050083,0x00000007,0x0000002d,0x0000002a,0x0000002c,0x0008000c, - 0x00000007,0x0000002e,0x00000001,0x0000002b,0x00000025,0x00000028,0x0000002d,0x0003003e, - 0x00000024,0x0000002e,0x0004003d,0x00000032,0x00000035,0x00000034,0x0004003d,0x00000007, - 0x00000036,0x00000024,0x00070058,0x00000009,0x00000038,0x00000035,0x00000036,0x00000002, - 0x00000037,0x0003003e,0x00000030,0x00000038,0x00050041,0x0000001a,0x0000003b,0x00000024, - 0x0000003a,0x0004003d,0x00000006,0x0000003c,0x0000003b,0x00050041,0x0000001a,0x0000003d, - 0x0000000c,0x0000003a,0x0004003d,0x00000006,0x0000003e,0x0000003d,0x00050083,0x00000006, - 0x0000003f,0x00000029,0x0000003e,0x000500be,0x00000018,0x00000040,0x0000003c,0x0000003f, - 0x000300f7,0x00000043,0x00000000,0x000400fa,0x00000040,0x00000042,0x00000044,0x000200f8, - 0x00000042,0x0003003e,0x00000041,0x00000037,0x000200f9,0x00000043,0x000200f8,0x00000044, - 0x00050041,0x0000001a,0x00000046,0x00000030,0x00000045,0x0004003d,0x00000006,0x00000047, - 0x00000046,0x0003003e,0x00000041,0x00000047,0x000200f9,0x00000043,0x000200f8,0x00000043, - 0x0004003d,0x00000006,0x00000048,0x00000041,0x00050041,0x0000001a,0x00000049,0x00000030, - 0x00000045,0x0003003e,0x00000049,0x00000048,0x0004003d,0x00000009,0x0000004a,0x00000030, - 0x000200fe,0x0000004a,0x00010038,0x00050036,0x00000006,0x00000012,0x00000000,0x0000000f, - 0x00030037,0x00000008,0x00000010,0x00030037,0x00000008,0x00000011,0x000200f8,0x00000013, - 0x0004003b,0x0000002f,0x0000004d,0x00000007,0x0004003b,0x00000008,0x0000004e,0x00000007, - 0x0004003b,0x00000008,0x00000050,0x00000007,0x0004003d,0x00000007,0x0000004f,0x00000010, - 0x0003003e,0x0000004e,0x0000004f,0x0004003d,0x00000007,0x00000051,0x00000011,0x0003003e, - 0x00000050,0x00000051,0x00060039,0x00000009,0x00000052,0x0000000d,0x0000004e,0x00000050, - 0x0003003e,0x0000004d,0x00000052,0x00050041,0x0000001a,0x00000054,0x0000004d,0x00000053, - 0x0004003d,0x00000006,0x00000055,0x00000054,0x00050041,0x0000001a,0x00000056,0x0000004d, - 0x0000003a,0x0004003d,0x00000006,0x00000057,0x00000056,0x0007000c,0x00000006,0x00000058, - 0x00000001,0x00000028,0x00000055,0x00000057,0x000200fe,0x00000058,0x00010038,0x00050036, - 0x00000006,0x00000016,0x00000000,0x0000000f,0x00030037,0x00000008,0x00000014,0x00030037, - 0x00000008,0x00000015,0x000200f8,0x00000017,0x0004003b,0x0000002f,0x0000005b,0x00000007, - 0x0004003b,0x00000008,0x0000005c,0x00000007,0x0004003b,0x00000008,0x0000005e,0x00000007, - 0x0004003d,0x00000007,0x0000005d,0x00000014,0x0003003e,0x0000005c,0x0000005d,0x0004003d, - 0x00000007,0x0000005f,0x00000015,0x0003003e,0x0000005e,0x0000005f,0x00060039,0x00000009, - 0x00000060,0x0000000d,0x0000005c,0x0000005e,0x0003003e,0x0000005b,0x00000060,0x00050041, - 0x0000001a,0x00000062,0x0000005b,0x00000061,0x0004003d,0x00000006,0x00000063,0x00000062, - 0x00050041,0x0000001a,0x00000064,0x0000005b,0x00000045,0x0004003d,0x00000006,0x00000065, - 0x00000064,0x0007000c,0x00000006,0x00000066,0x00000001,0x00000028,0x00000063,0x00000065, - 0x000200fe,0x00000066,0x00010038,0x00050036,0x00000006,0x00000022,0x00000000,0x0000001b, - 0x00030037,0x00000008,0x0000001c,0x00030037,0x00000008,0x0000001d,0x00030037,0x00000008, - 0x0000001e,0x00030037,0x00000019,0x0000001f,0x00030037,0x0000001a,0x00000020,0x00030037, - 0x00000019,0x00000021,0x000200f8,0x00000023,0x0004003b,0x0000001a,0x00000069,0x00000007, - 0x0004003b,0x0000006b,0x0000006c,0x00000007,0x0004003b,0x00000008,0x00000076,0x00000007, - 0x0004003b,0x00000082,0x00000083,0x00000007,0x0004003b,0x00000082,0x0000008e,0x00000007, - 0x0004003b,0x0000001a,0x000000a3,0x00000007,0x0004003b,0x0000001a,0x000000a5,0x00000007, - 0x0004003b,0x00000008,0x000000a8,0x00000007,0x0004003b,0x00000008,0x000000aa,0x00000007, - 0x0004003b,0x00000008,0x000000ae,0x00000007,0x0004003b,0x00000008,0x000000b0,0x00000007, - 0x0003003e,0x00000069,0x00000037,0x0003003e,0x0000006c,0x0000006d,0x000200f9,0x0000006e, - 0x000200f8,0x0000006e,0x000400f6,0x00000070,0x00000071,0x00000000,0x000200f9,0x00000072, - 0x000200f8,0x00000072,0x0004003d,0x0000006a,0x00000073,0x0000006c,0x000500b3,0x00000018, - 0x00000075,0x00000073,0x00000074,0x000400fa,0x00000075,0x0000006f,0x00000070,0x000200f8, - 0x0000006f,0x0004003d,0x00000007,0x00000077,0x0000001c,0x0004003d,0x00000007,0x00000078, - 0x0000001e,0x0004003d,0x0000006a,0x00000079,0x0000006c,0x0004006f,0x00000006,0x0000007a, - 0x00000079,0x0005008e,0x00000007,0x0000007b,0x00000078,0x0000007a,0x0004003d,0x00000018, - 0x0000007c,0x00000021,0x000600a9,0x00000006,0x0000007e,0x0000007c,0x00000029,0x0000007d, - 0x0005008e,0x00000007,0x0000007f,0x0000007b,0x0000007e,0x00050081,0x00000007,0x00000080, - 0x00000077,0x0000007f,0x0003003e,0x00000076,0x00000080,0x0004003d,0x00000007,0x00000084, - 0x00000076,0x00050041,0x00000088,0x00000089,0x00000087,0x0000006d,0x0004003d,0x00000007, - 0x0000008a,0x00000089,0x00050085,0x00000007,0x0000008b,0x00000084,0x0000008a,0x0006000c, - 0x00000007,0x0000008c,0x00000001,0x00000008,0x0000008b,0x0004006e,0x00000081,0x0000008d, - 0x0000008c,0x0003003e,0x00000083,0x0000008d,0x00050041,0x00000088,0x0000008f,0x00000087, - 0x0000006d,0x0004003d,0x00000007,0x00000090,0x0000008f,0x0004006e,0x00000081,0x00000091, - 0x00000090,0x0003003e,0x0000008e,0x00000091,0x0004003d,0x00000081,0x00000092,0x00000083, - 0x000500b1,0x00000095,0x00000096,0x00000092,0x00000094,0x0004009a,0x00000018,0x00000097, - 0x00000096,0x000400a8,0x00000018,0x00000098,0x00000097,0x000300f7,0x0000009a,0x00000000, - 0x000400fa,0x00000098,0x00000099,0x0000009a,0x000200f8,0x00000099,0x0004003d,0x00000081, - 0x0000009b,0x00000083,0x0004003d,0x00000081,0x0000009c,0x0000008e,0x000500af,0x00000095, - 0x0000009d,0x0000009b,0x0000009c,0x0004009a,0x00000018,0x0000009e,0x0000009d,0x000200f9, - 0x0000009a,0x000200f8,0x0000009a,0x000700f5,0x00000018,0x0000009f,0x00000097,0x0000006f, - 0x0000009e,0x00000099,0x000300f7,0x000000a1,0x00000000,0x000400fa,0x0000009f,0x000000a0, - 0x000000a1,0x000200f8,0x000000a0,0x000200f9,0x00000070,0x000200f8,0x000000a1,0x0004003d, - 0x00000018,0x000000a4,0x0000001f,0x000300f7,0x000000a7,0x00000000,0x000400fa,0x000000a4, - 0x000000a6,0x000000ad,0x000200f8,0x000000a6,0x0004003d,0x00000007,0x000000a9,0x00000076, - 0x0003003e,0x000000a8,0x000000a9,0x0004003d,0x00000007,0x000000ab,0x0000001d,0x0003003e, - 0x000000aa,0x000000ab,0x00060039,0x00000006,0x000000ac,0x00000012,0x000000a8,0x000000aa, - 0x0003003e,0x000000a5,0x000000ac,0x000200f9,0x000000a7,0x000200f8,0x000000ad,0x0004003d, - 0x00000007,0x000000af,0x00000076,0x0003003e,0x000000ae,0x000000af,0x0004003d,0x00000007, - 0x000000b1,0x0000001d,0x0003003e,0x000000b0,0x000000b1,0x00060039,0x00000006,0x000000b2, - 0x00000016,0x000000ae,0x000000b0,0x0003003e,0x000000a5,0x000000b2,0x000200f9,0x000000a7, - 0x000200f8,0x000000a7,0x0004003d,0x00000006,0x000000b3,0x000000a5,0x0003003e,0x000000a3, - 0x000000b3,0x0004003d,0x00000006,0x000000b4,0x000000a3,0x0004003d,0x00000006,0x000000b5, - 0x00000020,0x00050085,0x00000006,0x000000b7,0x000000b5,0x000000b6,0x000500bc,0x00000018, - 0x000000b8,0x000000b4,0x000000b7,0x000300f7,0x000000ba,0x00000000,0x000400fa,0x000000b8, - 0x000000b9,0x000000ba,0x000200f8,0x000000b9,0x000200f9,0x00000070,0x000200f8,0x000000ba, - 0x0004003d,0x0000006a,0x000000bc,0x0000006c,0x0004006f,0x00000006,0x000000bd,0x000000bc, - 0x0003003e,0x00000069,0x000000bd,0x000200f9,0x00000071,0x000200f8,0x00000071,0x0004003d, - 0x0000006a,0x000000be,0x0000006c,0x00050080,0x0000006a,0x000000bf,0x000000be,0x0000006d, - 0x0003003e,0x0000006c,0x000000bf,0x000200f9,0x0000006e,0x000200f8,0x00000070,0x0004003d, - 0x00000006,0x000000c0,0x00000069,0x000200fe,0x000000c0,0x00010038, + 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x000004e7,0x000004f2,0x00030010, + 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x000a0004,0x475f4c47,0x4c474f4f, + 0x70635f45,0x74735f70,0x5f656c79,0x656e696c,0x7269645f,0x69746365,0x00006576,0x00080004, + 0x475f4c47,0x4c474f4f,0x6e695f45,0x64756c63,0x69645f65,0x74636572,0x00657669,0x00040005, + 0x00000004,0x6e69616d,0x00000000,0x00080005,0x00000010,0x41414d53,0x63766f4d,0x32627628, + 0x3266763b,0x3266763b,0x0000003b,0x00040005,0x0000000d,0x646e6f63,0x00000000,0x00050005, + 0x0000000e,0x69726176,0x656c6261,0x00000000,0x00040005,0x0000000f,0x756c6176,0x00000065, + 0x000e0005,0x0000001b,0x41414d53,0x6e656c42,0x676e6964,0x67696557,0x61437468,0x6c75636c, + 0x6f697461,0x2853566e,0x3b326676,0x3b326676,0x5b346676,0x003b5d33,0x00050005,0x00000018, + 0x63786574,0x64726f6f,0x00000000,0x00050005,0x00000019,0x63786970,0x64726f6f,0x00000000, + 0x00040005,0x0000001a,0x7366666f,0x00007465,0x000b0005,0x0000001f,0x41414d53,0x6f636544, + 0x69446564,0x69426761,0x656e696c,0x63417261,0x73736563,0x32667628,0x0000003b,0x00030005, + 0x0000001e,0x00000065,0x000b0005,0x00000024,0x41414d53,0x6f636544,0x69446564,0x69426761, + 0x656e696c,0x63417261,0x73736563,0x34667628,0x0000003b,0x00030005,0x00000023,0x00000065, + 0x000b0005,0x0000002e,0x41414d53,0x72616553,0x69446863,0x28316761,0x3b313273,0x3b326676, + 0x3b326676,0x3b326676,0x00000000,0x00050005,0x0000002a,0x65676465,0x78655473,0x00000000, + 0x00050005,0x0000002b,0x63786574,0x64726f6f,0x00000000,0x00030005,0x0000002c,0x00726964, + 0x00030005,0x0000002d,0x00000065,0x000b0005,0x00000034,0x41414d53,0x72616553,0x69446863, + 0x28326761,0x3b313273,0x3b326676,0x3b326676,0x3b326676,0x00000000,0x00050005,0x00000030, + 0x65676465,0x78655473,0x00000000,0x00050005,0x00000031,0x63786574,0x64726f6f,0x00000000, + 0x00030005,0x00000032,0x00726964,0x00030005,0x00000033,0x00000065,0x000a0005,0x0000003c, + 0x41414d53,0x61657241,0x67616944,0x31327328,0x3266763b,0x3266763b,0x3b31663b,0x00000000, + 0x00040005,0x00000038,0x61657261,0x00786554,0x00040005,0x00000039,0x74736964,0x00000000, + 0x00030005,0x0000003a,0x00000065,0x00040005,0x0000003b,0x7366666f,0x00007465,0x000e0005, + 0x00000044,0x41414d53,0x636c6143,0x74616c75,0x61694465,0x69655767,0x73746867,0x31327328, + 0x3132733b,0x3266763b,0x3266763b,0x3466763b,0x0000003b,0x00050005,0x0000003f,0x65676465, + 0x78655473,0x00000000,0x00040005,0x00000040,0x61657261,0x00786554,0x00050005,0x00000041, + 0x63786574,0x64726f6f,0x00000000,0x00030005,0x00000042,0x00000065,0x00070005,0x00000043, + 0x73627573,0x6c706d61,0x646e4965,0x73656369,0x00000000,0x000a0005,0x0000004a,0x41414d53, + 0x72616553,0x654c6863,0x6874676e,0x31327328,0x3266763b,0x3b31663b,0x00000000,0x00050005, + 0x00000047,0x72616573,0x65546863,0x00000078,0x00030005,0x00000048,0x00000065,0x00040005, + 0x00000049,0x7366666f,0x00007465,0x000a0005,0x00000051,0x41414d53,0x72616553,0x4c586863, + 0x28746665,0x3b313273,0x3b313273,0x3b326676,0x003b3166,0x00050005,0x0000004d,0x65676465, + 0x78655473,0x00000000,0x00050005,0x0000004e,0x72616573,0x65546863,0x00000078,0x00050005, + 0x0000004f,0x63786574,0x64726f6f,0x00000000,0x00030005,0x00000050,0x00646e65,0x000b0005, + 0x00000057,0x41414d53,0x72616553,0x52586863,0x74686769,0x31327328,0x3132733b,0x3266763b, + 0x3b31663b,0x00000000,0x00050005,0x00000053,0x65676465,0x78655473,0x00000000,0x00050005, + 0x00000054,0x72616573,0x65546863,0x00000078,0x00050005,0x00000055,0x63786574,0x64726f6f, + 0x00000000,0x00030005,0x00000056,0x00646e65,0x000a0005,0x0000005d,0x41414d53,0x72616553, + 0x55596863,0x32732870,0x32733b31,0x66763b31,0x31663b32,0x0000003b,0x00050005,0x00000059, + 0x65676465,0x78655473,0x00000000,0x00050005,0x0000005a,0x72616573,0x65546863,0x00000078, + 0x00050005,0x0000005b,0x63786574,0x64726f6f,0x00000000,0x00030005,0x0000005c,0x00646e65, + 0x000a0005,0x00000063,0x41414d53,0x72616553,0x44596863,0x286e776f,0x3b313273,0x3b313273, + 0x3b326676,0x003b3166,0x00050005,0x0000005f,0x65676465,0x78655473,0x00000000,0x00050005, + 0x00000060,0x72616573,0x65546863,0x00000078,0x00050005,0x00000061,0x63786574,0x64726f6f, + 0x00000000,0x00030005,0x00000062,0x00646e65,0x00090005,0x0000006b,0x41414d53,0x61657241, + 0x31327328,0x3266763b,0x3b31663b,0x663b3166,0x00003b31,0x00040005,0x00000066,0x61657261, + 0x00786554,0x00040005,0x00000067,0x74736964,0x00000000,0x00030005,0x00000068,0x00003165, + 0x00030005,0x00000069,0x00003265,0x00040005,0x0000006a,0x7366666f,0x00007465,0x000f0005, + 0x00000072,0x41414d53,0x65746544,0x6f487463,0x6f7a6972,0x6c61746e,0x6e726f43,0x61507265, + 0x72657474,0x3273286e,0x66763b31,0x66763b32,0x66763b34,0x00003b32,0x00050005,0x0000006e, + 0x65676465,0x78655473,0x00000000,0x00040005,0x0000006f,0x67696577,0x00737468,0x00050005, + 0x00000070,0x63786574,0x64726f6f,0x00000000,0x00030005,0x00000071,0x00000064,0x000f0005, + 0x00000078,0x41414d53,0x65746544,0x65567463,0x63697472,0x6f436c61,0x72656e72,0x74746150, + 0x286e7265,0x3b313273,0x3b326676,0x3b346676,0x3b326676,0x00000000,0x00050005,0x00000074, + 0x65676465,0x78655473,0x00000000,0x00040005,0x00000075,0x67696577,0x00737468,0x00050005, + 0x00000076,0x63786574,0x64726f6f,0x00000000,0x00030005,0x00000077,0x00000064,0x00120005, + 0x00000082,0x41414d53,0x6e656c42,0x676e6964,0x67696557,0x61437468,0x6c75636c,0x6f697461, + 0x2853506e,0x3b326676,0x3b326676,0x5b346676,0x733b5d33,0x733b3132,0x733b3132,0x763b3132, + 0x003b3466,0x00050005,0x0000007b,0x63786574,0x64726f6f,0x00000000,0x00050005,0x0000007c, + 0x63786970,0x64726f6f,0x00000000,0x00040005,0x0000007d,0x7366666f,0x00007465,0x00050005, + 0x0000007e,0x65676465,0x78655473,0x00000000,0x00040005,0x0000007f,0x61657261,0x00786554, + 0x00050005,0x00000080,0x72616573,0x65546863,0x00000078,0x00070005,0x00000081,0x73627573, + 0x6c706d61,0x646e4965,0x73656369,0x00000000,0x00050005,0x00000096,0x736e6f43,0x746e6174, + 0x00000073,0x00040006,0x00000096,0x00000000,0x0063646e,0x00050006,0x00000096,0x00000001, + 0x7274656d,0x00736369,0x00030005,0x00000098,0x00006370,0x00040005,0x000000e9,0x726f6f63, + 0x00000064,0x00030005,0x000000f2,0x00000074,0x00040005,0x00000126,0x726f6f63,0x00000064, + 0x00030005,0x00000134,0x00000074,0x00040005,0x0000015c,0x61726170,0x0000006d,0x00050005, + 0x00000166,0x63786574,0x64726f6f,0x00000000,0x00040005,0x00000185,0x67696577,0x00737468, + 0x00030005,0x0000018c,0x00000064,0x00030005,0x0000018e,0x00646e65,0x00040005,0x0000018f, + 0x61726170,0x0000006d,0x00040005,0x00000191,0x61726170,0x0000006d,0x00040005,0x00000192, + 0x61726170,0x0000006d,0x00040005,0x000001a7,0x61726170,0x0000006d,0x00040005,0x000001a9, + 0x61726170,0x0000006d,0x00040005,0x000001aa,0x61726170,0x0000006d,0x00040005,0x000001ba, + 0x726f6f63,0x00007364,0x00030005,0x000001ce,0x00000063,0x00040005,0x000001e5,0x61726170, + 0x0000006d,0x00030005,0x000001ea,0x00006363,0x00040005,0x000001f6,0x61726170,0x0000006d, + 0x00040005,0x000001f7,0x61726170,0x0000006d,0x00040005,0x000001f9,0x61726170,0x0000006d, + 0x00040005,0x000001fc,0x61726170,0x0000006d,0x00040005,0x000001ff,0x61726170,0x0000006d, + 0x00040005,0x00000201,0x61726170,0x0000006d,0x00040005,0x00000208,0x61726170,0x0000006d, + 0x00040005,0x0000020a,0x61726170,0x0000006d,0x00040005,0x0000020b,0x61726170,0x0000006d, + 0x00040005,0x0000021a,0x61726170,0x0000006d,0x00040005,0x0000021c,0x61726170,0x0000006d, + 0x00040005,0x0000021d,0x61726170,0x0000006d,0x00040005,0x00000239,0x726f6f63,0x00007364, + 0x00030005,0x0000024b,0x00000063,0x00030005,0x00000262,0x00006363,0x00040005,0x0000026d, + 0x61726170,0x0000006d,0x00040005,0x0000026e,0x61726170,0x0000006d,0x00040005,0x00000270, + 0x61726170,0x0000006d,0x00040005,0x00000273,0x61726170,0x0000006d,0x00040005,0x00000276, + 0x61726170,0x0000006d,0x00040005,0x00000278,0x61726170,0x0000006d,0x00040005,0x00000282, + 0x6c616373,0x00000065,0x00040005,0x00000286,0x73616962,0x00000000,0x00030005,0x000002a2, + 0x00000065,0x00040005,0x000002c6,0x7366666f,0x00007465,0x00040005,0x000002c8,0x61726170, + 0x0000006d,0x00040005,0x000002ca,0x61726170,0x0000006d,0x00030005,0x000002d6,0x00000065, + 0x00040005,0x000002f6,0x7366666f,0x00007465,0x00040005,0x000002f7,0x61726170,0x0000006d, + 0x00040005,0x000002f9,0x61726170,0x0000006d,0x00030005,0x00000305,0x00000065,0x00040005, + 0x00000326,0x7366666f,0x00007465,0x00040005,0x00000327,0x61726170,0x0000006d,0x00040005, + 0x0000032a,0x61726170,0x0000006d,0x00030005,0x00000335,0x00000065,0x00040005,0x00000355, + 0x7366666f,0x00007465,0x00040005,0x00000356,0x61726170,0x0000006d,0x00040005,0x00000359, + 0x61726170,0x0000006d,0x00050005,0x00000365,0x63786574,0x64726f6f,0x00000000,0x00050005, + 0x0000037d,0x7466656c,0x68676952,0x00000074,0x00050005,0x00000382,0x6e756f72,0x676e6964, + 0x00000000,0x00040005,0x0000038e,0x74636166,0x0000726f,0x00050005,0x000003ca,0x7466656c, + 0x68676952,0x00000074,0x00050005,0x000003cf,0x6e756f72,0x676e6964,0x00000000,0x00040005, + 0x000003da,0x74636166,0x0000726f,0x00040005,0x00000413,0x67696577,0x00737468,0x00030005, + 0x00000415,0x00000065,0x00040005,0x0000041f,0x61726170,0x0000006d,0x00040005,0x00000421, + 0x61726170,0x0000006d,0x00040005,0x00000423,0x61726170,0x0000006d,0x00040005,0x00000432, + 0x726f6f63,0x00007364,0x00040005,0x00000433,0x61726170,0x0000006d,0x00040005,0x00000437, + 0x61726170,0x0000006d,0x00030005,0x0000043f,0x00000064,0x00030005,0x00000443,0x00003165, + 0x00040005,0x00000449,0x61726170,0x0000006d,0x00040005,0x0000044d,0x61726170,0x0000006d, + 0x00040005,0x0000045f,0x74727173,0x0000645f,0x00030005,0x00000462,0x00003265,0x00040005, + 0x00000468,0x61726170,0x0000006d,0x00040005,0x0000046a,0x61726170,0x0000006d,0x00040005, + 0x0000046c,0x61726170,0x0000006d,0x00040005,0x0000046e,0x61726170,0x0000006d,0x00040005, + 0x00000479,0x61726170,0x0000006d,0x00040005,0x0000047c,0x61726170,0x0000006d,0x00040005, + 0x0000047f,0x61726170,0x0000006d,0x00040005,0x0000048e,0x726f6f63,0x00007364,0x00040005, + 0x0000048f,0x61726170,0x0000006d,0x00040005,0x00000493,0x61726170,0x0000006d,0x00030005, + 0x0000049b,0x00000064,0x00030005,0x0000049f,0x00003165,0x00040005,0x000004a5,0x61726170, + 0x0000006d,0x00040005,0x000004a9,0x61726170,0x0000006d,0x00040005,0x000004bb,0x74727173, + 0x0000645f,0x00030005,0x000004be,0x00003265,0x00040005,0x000004c4,0x61726170,0x0000006d, + 0x00040005,0x000004c6,0x61726170,0x0000006d,0x00040005,0x000004c8,0x61726170,0x0000006d, + 0x00040005,0x000004ca,0x61726170,0x0000006d,0x00040005,0x000004d5,0x61726170,0x0000006d, + 0x00040005,0x000004d8,0x61726170,0x0000006d,0x00040005,0x000004db,0x61726170,0x0000006d, + 0x00060005,0x000004e7,0x67617266,0x43786554,0x64726f6f,0x00000000,0x00050005,0x000004e8, + 0x63786970,0x64726f6f,0x00000000,0x00040005,0x000004e9,0x7366666f,0x00007465,0x00040005, + 0x000004ea,0x61726170,0x0000006d,0x00040005,0x000004ec,0x61726170,0x0000006d,0x00040005, + 0x000004ed,0x61726170,0x0000006d,0x00050005,0x000004f2,0x4374756f,0x726f6c6f,0x00000000, + 0x00050005,0x000004f3,0x65676445,0x74786554,0x00657275,0x00050005,0x000004f4,0x61657241, + 0x74786554,0x00657275,0x00060005,0x000004f5,0x72616553,0x65546863,0x72757478,0x00000065, + 0x00040005,0x000004f6,0x61726170,0x0000006d,0x00040005,0x000004f8,0x61726170,0x0000006d, + 0x00040005,0x000004fa,0x61726170,0x0000006d,0x00040005,0x000004fc,0x61726170,0x0000006d, + 0x00030047,0x00000096,0x00000002,0x00050048,0x00000096,0x00000000,0x00000023,0x00000000, + 0x00050048,0x00000096,0x00000001,0x00000023,0x00000010,0x00040047,0x000004e7,0x0000001e, + 0x00000000,0x00040047,0x000004f2,0x0000001e,0x00000000,0x00040047,0x000004f3,0x00000021, + 0x00000000,0x00040047,0x000004f3,0x00000022,0x00000000,0x00040047,0x000004f4,0x00000021, + 0x00000000,0x00040047,0x000004f4,0x00000022,0x00000001,0x00040047,0x000004f5,0x00000021, + 0x00000000,0x00040047,0x000004f5,0x00000022,0x00000002,0x00020013,0x00000002,0x00030021, + 0x00000003,0x00000002,0x00020014,0x00000006,0x00040017,0x00000007,0x00000006,0x00000002, + 0x00040020,0x00000008,0x00000007,0x00000007,0x00030016,0x00000009,0x00000020,0x00040017, + 0x0000000a,0x00000009,0x00000002,0x00040020,0x0000000b,0x00000007,0x0000000a,0x00060021, + 0x0000000c,0x00000002,0x00000008,0x0000000b,0x0000000b,0x00040017,0x00000012,0x00000009, + 0x00000004,0x00040015,0x00000013,0x00000020,0x00000000,0x0004002b,0x00000013,0x00000014, + 0x00000003,0x0004001c,0x00000015,0x00000012,0x00000014,0x00040020,0x00000016,0x00000007, + 0x00000015,0x00060021,0x00000017,0x00000002,0x0000000b,0x0000000b,0x00000016,0x00040021, + 0x0000001d,0x0000000a,0x0000000b,0x00040020,0x00000021,0x00000007,0x00000012,0x00040021, + 0x00000022,0x00000012,0x00000021,0x00090019,0x00000026,0x00000009,0x00000001,0x00000000, + 0x00000000,0x00000000,0x00000001,0x00000000,0x0003001b,0x00000027,0x00000026,0x00040020, + 0x00000028,0x00000000,0x00000027,0x00070021,0x00000029,0x0000000a,0x00000028,0x0000000b, + 0x0000000b,0x0000000b,0x00040020,0x00000036,0x00000007,0x00000009,0x00070021,0x00000037, + 0x0000000a,0x00000028,0x0000000b,0x0000000b,0x00000036,0x00080021,0x0000003e,0x0000000a, + 0x00000028,0x00000028,0x0000000b,0x0000000b,0x00000021,0x00060021,0x00000046,0x00000009, + 0x00000028,0x0000000b,0x00000036,0x00070021,0x0000004c,0x00000009,0x00000028,0x00000028, + 0x0000000b,0x00000036,0x00080021,0x00000065,0x0000000a,0x00000028,0x0000000b,0x00000036, + 0x00000036,0x00000036,0x00070021,0x0000006d,0x00000002,0x00000028,0x0000000b,0x00000021, + 0x0000000b,0x000a0021,0x0000007a,0x00000012,0x0000000b,0x0000000b,0x00000016,0x00000028, + 0x00000028,0x00000028,0x00000021,0x0004002b,0x00000013,0x00000084,0x00000000,0x00040020, + 0x00000085,0x00000007,0x00000006,0x0004002b,0x00000013,0x0000008d,0x00000001,0x0004001e, + 0x00000096,0x00000012,0x00000012,0x00040020,0x00000097,0x00000009,0x00000096,0x0004003b, + 0x00000097,0x00000098,0x00000009,0x00040015,0x00000099,0x00000020,0x00000001,0x0004002b, + 0x00000099,0x0000009a,0x00000001,0x00040020,0x0000009b,0x00000009,0x00000012,0x0004002b, + 0x00000099,0x000000a0,0x00000000,0x0004002b,0x00000009,0x000000a4,0xbe800000,0x0004002b, + 0x00000009,0x000000a5,0xbe000000,0x0004002b,0x00000009,0x000000a6,0x3fa00000,0x0007002c, + 0x00000012,0x000000a7,0x000000a4,0x000000a5,0x000000a6,0x000000a5,0x0007002c,0x00000012, + 0x000000af,0x000000a5,0x000000a4,0x000000a5,0x000000a6,0x0004002b,0x00000099,0x000000b4, + 0x00000002,0x0004002b,0x00000009,0x000000b8,0xc2000000,0x0004002b,0x00000009,0x000000b9, + 0x42000000,0x0007002c,0x00000012,0x000000ba,0x000000b8,0x000000b9,0x000000b8,0x000000b9, + 0x0004002b,0x00000009,0x000000ca,0x40a00000,0x0004002b,0x00000009,0x000000ce,0x40700000, + 0x0004002b,0x00000013,0x000000e2,0x00000002,0x0004002b,0x00000009,0x000000eb,0xbf800000, + 0x0004002b,0x00000009,0x000000ec,0x3f800000,0x00040017,0x000000f0,0x00000009,0x00000003, + 0x00040020,0x000000f1,0x00000007,0x000000f0,0x0004002b,0x00000009,0x00000100,0x40e00000, + 0x0004002b,0x00000009,0x00000106,0x3f666666,0x0004002b,0x00000009,0x0000011a,0x00000000, + 0x0004002b,0x00000009,0x0000011e,0x3f000000,0x0005002c,0x0000000a,0x0000011f,0x0000011e, + 0x0000011e,0x0004002b,0x00000009,0x0000012b,0x3e800000,0x00040020,0x0000012c,0x00000009, + 0x00000009,0x0004002b,0x00000009,0x00000167,0x41a00000,0x0005002c,0x0000000a,0x00000168, + 0x00000167,0x00000167,0x0004002b,0x00000009,0x0000016c,0x3bcccccd,0x0004002b,0x00000009, + 0x0000016d,0x3aea0ea1,0x0005002c,0x0000000a,0x0000016e,0x0000016c,0x0000016d,0x0004002b, + 0x00000009,0x00000170,0x3b4ccccd,0x0004002b,0x00000009,0x00000171,0x3a6a0ea1,0x0005002c, + 0x0000000a,0x00000172,0x00000170,0x00000171,0x0004002b,0x00000009,0x00000178,0x3e124925, + 0x0005002c,0x0000000a,0x00000186,0x0000011a,0x0000011a,0x0005002c,0x0000000a,0x0000018d, + 0x000000eb,0x000000ec,0x0005002c,0x0000000a,0x000001a6,0x000000ec,0x000000eb,0x0004002b, + 0x00000009,0x000001b6,0x40000000,0x00040017,0x000001d2,0x00000099,0x00000002,0x0004002b, + 0x00000099,0x000001d3,0xffffffff,0x0005002c,0x000001d2,0x000001d4,0x000001d3,0x000000a0, + 0x0005002c,0x000001d2,0x000001de,0x0000009a,0x000000a0,0x0005002c,0x0000000a,0x000001eb, + 0x000001b6,0x000001b6,0x0005002c,0x0000000a,0x00000207,0x000000eb,0x000000eb,0x0005002c, + 0x0000000a,0x00000219,0x000000ec,0x000000ec,0x0005002c,0x000001d2,0x00000255,0x000000a0, + 0x000001d3,0x0004002b,0x00000009,0x00000283,0x42040000,0x0004002b,0x00000009,0x00000284, + 0xc2040000,0x0005002c,0x0000000a,0x00000285,0x00000283,0x00000284,0x0004002b,0x00000009, + 0x00000287,0x42840000,0x0005002c,0x0000000a,0x00000288,0x00000287,0x00000283,0x0004002b, + 0x00000009,0x0000028e,0xbf000000,0x0005002c,0x0000000a,0x0000028f,0x0000011e,0x0000028e, + 0x0004002b,0x00000009,0x00000292,0x3c800000,0x0004002b,0x00000009,0x00000293,0x3d800000, + 0x0005002c,0x0000000a,0x00000294,0x00000292,0x00000293,0x0005002c,0x0000000a,0x000002a3, + 0x0000011a,0x000000ec,0x0004002b,0x00000009,0x000002b1,0x3f53fe5d,0x0004002b,0x00000009, + 0x000002be,0xc0000000,0x0004002b,0x00000009,0x000002bf,0x80000000,0x0005002c,0x0000000a, + 0x000002c0,0x000002be,0x000002bf,0x0004002b,0x00000009,0x000002c7,0xc0008102,0x0004002b, + 0x00000009,0x000002cc,0x40500000,0x0005002c,0x0000000a,0x000002f0,0x000001b6,0x0000011a, + 0x0005002c,0x0000000a,0x00000306,0x000000ec,0x0000011a,0x0005002c,0x0000000a,0x00000320, + 0x000002bf,0x000002be,0x0005002c,0x0000000a,0x0000034f,0x0000011a,0x000001b6,0x0004002b, + 0x00000009,0x00000366,0x41800000,0x0005002c,0x0000000a,0x00000367,0x00000366,0x00000366, + 0x0004002b,0x00000009,0x00000368,0x40800000,0x0004002b,0x00000009,0x00000383,0x3f400000, + 0x0005002c,0x000001d2,0x00000394,0x000000a0,0x0000009a,0x0005002c,0x000001d2,0x000003a1, + 0x0000009a,0x0000009a,0x0004002b,0x00000099,0x000003ae,0xfffffffe,0x0005002c,0x000001d2, + 0x000003af,0x000000a0,0x000003ae,0x0005002c,0x000001d2,0x000003bc,0x0000009a,0x000003ae, + 0x0005002c,0x000001d2,0x000003f8,0x000003ae,0x000000a0,0x0005002c,0x000001d2,0x00000405, + 0x000003ae,0x0000009a,0x0007002c,0x00000012,0x00000414,0x0000011a,0x0000011a,0x0000011a, + 0x0000011a,0x00040020,0x000004e6,0x00000001,0x0000000a,0x0004003b,0x000004e6,0x000004e7, + 0x00000001,0x00040020,0x000004f1,0x00000003,0x00000012,0x0004003b,0x000004f1,0x000004f2, + 0x00000003,0x0004003b,0x00000028,0x000004f3,0x00000000,0x0004003b,0x00000028,0x000004f4, + 0x00000000,0x0004003b,0x00000028,0x000004f5,0x00000000,0x00050036,0x00000002,0x00000004, + 0x00000000,0x00000003,0x000200f8,0x00000005,0x0004003b,0x0000000b,0x000004e8,0x00000007, + 0x0004003b,0x00000016,0x000004e9,0x00000007,0x0004003b,0x0000000b,0x000004ea,0x00000007, + 0x0004003b,0x0000000b,0x000004ec,0x00000007,0x0004003b,0x00000016,0x000004ed,0x00000007, + 0x0004003b,0x0000000b,0x000004f6,0x00000007,0x0004003b,0x0000000b,0x000004f8,0x00000007, + 0x0004003b,0x00000016,0x000004fa,0x00000007,0x0004003b,0x00000021,0x000004fc,0x00000007, + 0x0004003d,0x0000000a,0x000004eb,0x000004e7,0x0003003e,0x000004ea,0x000004eb,0x00070039, + 0x00000002,0x000004ee,0x0000001b,0x000004ea,0x000004ec,0x000004ed,0x0004003d,0x0000000a, + 0x000004ef,0x000004ec,0x0003003e,0x000004e8,0x000004ef,0x0004003d,0x00000015,0x000004f0, + 0x000004ed,0x0003003e,0x000004e9,0x000004f0,0x0004003d,0x0000000a,0x000004f7,0x000004e7, + 0x0003003e,0x000004f6,0x000004f7,0x0004003d,0x0000000a,0x000004f9,0x000004e8,0x0003003e, + 0x000004f8,0x000004f9,0x0004003d,0x00000015,0x000004fb,0x000004e9,0x0003003e,0x000004fa, + 0x000004fb,0x0003003e,0x000004fc,0x00000414,0x000b0039,0x00000012,0x000004fd,0x00000082, + 0x000004f6,0x000004f8,0x000004fa,0x000004f3,0x000004f4,0x000004f5,0x000004fc,0x0003003e, + 0x000004f2,0x000004fd,0x000100fd,0x00010038,0x00050036,0x00000002,0x00000010,0x00000000, + 0x0000000c,0x00030037,0x00000008,0x0000000d,0x00030037,0x0000000b,0x0000000e,0x00030037, + 0x0000000b,0x0000000f,0x000200f8,0x00000011,0x00050041,0x00000085,0x00000086,0x0000000d, + 0x00000084,0x0004003d,0x00000006,0x00000087,0x00000086,0x000300f7,0x00000089,0x00000000, + 0x000400fa,0x00000087,0x00000088,0x00000089,0x000200f8,0x00000088,0x00050041,0x00000036, + 0x0000008a,0x0000000f,0x00000084,0x0004003d,0x00000009,0x0000008b,0x0000008a,0x00050041, + 0x00000036,0x0000008c,0x0000000e,0x00000084,0x0003003e,0x0000008c,0x0000008b,0x000200f9, + 0x00000089,0x000200f8,0x00000089,0x00050041,0x00000085,0x0000008e,0x0000000d,0x0000008d, + 0x0004003d,0x00000006,0x0000008f,0x0000008e,0x000300f7,0x00000091,0x00000000,0x000400fa, + 0x0000008f,0x00000090,0x00000091,0x000200f8,0x00000090,0x00050041,0x00000036,0x00000092, + 0x0000000f,0x0000008d,0x0004003d,0x00000009,0x00000093,0x00000092,0x00050041,0x00000036, + 0x00000094,0x0000000e,0x0000008d,0x0003003e,0x00000094,0x00000093,0x000200f9,0x00000091, + 0x000200f8,0x00000091,0x000100fd,0x00010038,0x00050036,0x00000002,0x0000001b,0x00000000, + 0x00000017,0x00030037,0x0000000b,0x00000018,0x00030037,0x0000000b,0x00000019,0x00030037, + 0x00000016,0x0000001a,0x000200f8,0x0000001c,0x0004003d,0x0000000a,0x00000095,0x00000018, + 0x00050041,0x0000009b,0x0000009c,0x00000098,0x0000009a,0x0004003d,0x00000012,0x0000009d, + 0x0000009c,0x0007004f,0x0000000a,0x0000009e,0x0000009d,0x0000009d,0x00000002,0x00000003, + 0x00050085,0x0000000a,0x0000009f,0x00000095,0x0000009e,0x0003003e,0x00000019,0x0000009f, + 0x00050041,0x0000009b,0x000000a1,0x00000098,0x0000009a,0x0004003d,0x00000012,0x000000a2, + 0x000000a1,0x0009004f,0x00000012,0x000000a3,0x000000a2,0x000000a2,0x00000000,0x00000001, + 0x00000000,0x00000001,0x0004003d,0x0000000a,0x000000a8,0x00000018,0x0009004f,0x00000012, + 0x000000a9,0x000000a8,0x000000a8,0x00000000,0x00000001,0x00000000,0x00000001,0x0008000c, + 0x00000012,0x000000aa,0x00000001,0x00000032,0x000000a3,0x000000a7,0x000000a9,0x00050041, + 0x00000021,0x000000ab,0x0000001a,0x000000a0,0x0003003e,0x000000ab,0x000000aa,0x00050041, + 0x0000009b,0x000000ac,0x00000098,0x0000009a,0x0004003d,0x00000012,0x000000ad,0x000000ac, + 0x0009004f,0x00000012,0x000000ae,0x000000ad,0x000000ad,0x00000000,0x00000001,0x00000000, + 0x00000001,0x0004003d,0x0000000a,0x000000b0,0x00000018,0x0009004f,0x00000012,0x000000b1, + 0x000000b0,0x000000b0,0x00000000,0x00000001,0x00000000,0x00000001,0x0008000c,0x00000012, + 0x000000b2,0x00000001,0x00000032,0x000000ae,0x000000af,0x000000b1,0x00050041,0x00000021, + 0x000000b3,0x0000001a,0x0000009a,0x0003003e,0x000000b3,0x000000b2,0x00050041,0x0000009b, + 0x000000b5,0x00000098,0x0000009a,0x0004003d,0x00000012,0x000000b6,0x000000b5,0x0009004f, + 0x00000012,0x000000b7,0x000000b6,0x000000b6,0x00000000,0x00000000,0x00000001,0x00000001, + 0x00050041,0x00000021,0x000000bb,0x0000001a,0x000000a0,0x0004003d,0x00000012,0x000000bc, + 0x000000bb,0x0007004f,0x0000000a,0x000000bd,0x000000bc,0x000000bc,0x00000000,0x00000002, + 0x00050041,0x00000021,0x000000be,0x0000001a,0x0000009a,0x0004003d,0x00000012,0x000000bf, + 0x000000be,0x0007004f,0x0000000a,0x000000c0,0x000000bf,0x000000bf,0x00000001,0x00000003, + 0x00050051,0x00000009,0x000000c1,0x000000bd,0x00000000,0x00050051,0x00000009,0x000000c2, + 0x000000bd,0x00000001,0x00050051,0x00000009,0x000000c3,0x000000c0,0x00000000,0x00050051, + 0x00000009,0x000000c4,0x000000c0,0x00000001,0x00070050,0x00000012,0x000000c5,0x000000c1, + 0x000000c2,0x000000c3,0x000000c4,0x0008000c,0x00000012,0x000000c6,0x00000001,0x00000032, + 0x000000b7,0x000000ba,0x000000c5,0x00050041,0x00000021,0x000000c7,0x0000001a,0x000000b4, + 0x0003003e,0x000000c7,0x000000c6,0x000100fd,0x00010038,0x00050036,0x0000000a,0x0000001f, + 0x00000000,0x0000001d,0x00030037,0x0000000b,0x0000001e,0x000200f8,0x00000020,0x00050041, + 0x00000036,0x000000c8,0x0000001e,0x00000084,0x0004003d,0x00000009,0x000000c9,0x000000c8, + 0x00050041,0x00000036,0x000000cb,0x0000001e,0x00000084,0x0004003d,0x00000009,0x000000cc, + 0x000000cb,0x00050085,0x00000009,0x000000cd,0x000000ca,0x000000cc,0x00050083,0x00000009, + 0x000000cf,0x000000cd,0x000000ce,0x0006000c,0x00000009,0x000000d0,0x00000001,0x00000004, + 0x000000cf,0x00050085,0x00000009,0x000000d1,0x000000c9,0x000000d0,0x00050041,0x00000036, + 0x000000d2,0x0000001e,0x00000084,0x0003003e,0x000000d2,0x000000d1,0x0004003d,0x0000000a, + 0x000000d3,0x0000001e,0x0006000c,0x0000000a,0x000000d4,0x00000001,0x00000001,0x000000d3, + 0x000200fe,0x000000d4,0x00010038,0x00050036,0x00000012,0x00000024,0x00000000,0x00000022, + 0x00030037,0x00000021,0x00000023,0x000200f8,0x00000025,0x0004003d,0x00000012,0x000000d7, + 0x00000023,0x0007004f,0x0000000a,0x000000d8,0x000000d7,0x000000d7,0x00000000,0x00000002, + 0x0004003d,0x00000012,0x000000d9,0x00000023,0x0007004f,0x0000000a,0x000000da,0x000000d9, + 0x000000d9,0x00000000,0x00000002,0x0005008e,0x0000000a,0x000000db,0x000000da,0x000000ca, + 0x00050050,0x0000000a,0x000000dc,0x000000ce,0x000000ce,0x00050083,0x0000000a,0x000000dd, + 0x000000db,0x000000dc,0x0006000c,0x0000000a,0x000000de,0x00000001,0x00000004,0x000000dd, + 0x00050085,0x0000000a,0x000000df,0x000000d8,0x000000de,0x00050041,0x00000036,0x000000e0, + 0x00000023,0x00000084,0x00050051,0x00000009,0x000000e1,0x000000df,0x00000000,0x0003003e, + 0x000000e0,0x000000e1,0x00050041,0x00000036,0x000000e3,0x00000023,0x000000e2,0x00050051, + 0x00000009,0x000000e4,0x000000df,0x00000001,0x0003003e,0x000000e3,0x000000e4,0x0004003d, + 0x00000012,0x000000e5,0x00000023,0x0006000c,0x00000012,0x000000e6,0x00000001,0x00000001, + 0x000000e5,0x000200fe,0x000000e6,0x00010038,0x00050036,0x0000000a,0x0000002e,0x00000000, + 0x00000029,0x00030037,0x00000028,0x0000002a,0x00030037,0x0000000b,0x0000002b,0x00030037, + 0x0000000b,0x0000002c,0x00030037,0x0000000b,0x0000002d,0x000200f8,0x0000002f,0x0004003b, + 0x00000021,0x000000e9,0x00000007,0x0004003b,0x000000f1,0x000000f2,0x00000007,0x0004003d, + 0x0000000a,0x000000ea,0x0000002b,0x00050051,0x00000009,0x000000ed,0x000000ea,0x00000000, + 0x00050051,0x00000009,0x000000ee,0x000000ea,0x00000001,0x00070050,0x00000012,0x000000ef, + 0x000000ed,0x000000ee,0x000000eb,0x000000ec,0x0003003e,0x000000e9,0x000000ef,0x00050041, + 0x0000009b,0x000000f3,0x00000098,0x0000009a,0x0004003d,0x00000012,0x000000f4,0x000000f3, + 0x0007004f,0x0000000a,0x000000f5,0x000000f4,0x000000f4,0x00000000,0x00000001,0x00050051, + 0x00000009,0x000000f6,0x000000f5,0x00000000,0x00050051,0x00000009,0x000000f7,0x000000f5, + 0x00000001,0x00060050,0x000000f0,0x000000f8,0x000000f6,0x000000f7,0x000000ec,0x0003003e, + 0x000000f2,0x000000f8,0x000200f9,0x000000f9,0x000200f8,0x000000f9,0x000400f6,0x000000fb, + 0x000000fc,0x00000000,0x000200f9,0x000000fd,0x000200f8,0x000000fd,0x00050041,0x00000036, + 0x000000fe,0x000000e9,0x000000e2,0x0004003d,0x00000009,0x000000ff,0x000000fe,0x000500b8, + 0x00000006,0x00000101,0x000000ff,0x00000100,0x000300f7,0x00000103,0x00000000,0x000400fa, + 0x00000101,0x00000102,0x00000103,0x000200f8,0x00000102,0x00050041,0x00000036,0x00000104, + 0x000000e9,0x00000014,0x0004003d,0x00000009,0x00000105,0x00000104,0x000500ba,0x00000006, + 0x00000107,0x00000105,0x00000106,0x000200f9,0x00000103,0x000200f8,0x00000103,0x000700f5, + 0x00000006,0x00000108,0x00000101,0x000000fd,0x00000107,0x00000102,0x000400fa,0x00000108, + 0x000000fa,0x000000fb,0x000200f8,0x000000fa,0x0004003d,0x000000f0,0x00000109,0x000000f2, + 0x0004003d,0x0000000a,0x0000010a,0x0000002c,0x00050051,0x00000009,0x0000010b,0x0000010a, + 0x00000000,0x00050051,0x00000009,0x0000010c,0x0000010a,0x00000001,0x00060050,0x000000f0, + 0x0000010d,0x0000010b,0x0000010c,0x000000ec,0x0004003d,0x00000012,0x0000010e,0x000000e9, + 0x0008004f,0x000000f0,0x0000010f,0x0000010e,0x0000010e,0x00000000,0x00000001,0x00000002, + 0x0008000c,0x000000f0,0x00000110,0x00000001,0x00000032,0x00000109,0x0000010d,0x0000010f, + 0x00050041,0x00000036,0x00000111,0x000000e9,0x00000084,0x00050051,0x00000009,0x00000112, + 0x00000110,0x00000000,0x0003003e,0x00000111,0x00000112,0x00050041,0x00000036,0x00000113, + 0x000000e9,0x0000008d,0x00050051,0x00000009,0x00000114,0x00000110,0x00000001,0x0003003e, + 0x00000113,0x00000114,0x00050041,0x00000036,0x00000115,0x000000e9,0x000000e2,0x00050051, + 0x00000009,0x00000116,0x00000110,0x00000002,0x0003003e,0x00000115,0x00000116,0x0004003d, + 0x00000027,0x00000117,0x0000002a,0x0004003d,0x00000012,0x00000118,0x000000e9,0x0007004f, + 0x0000000a,0x00000119,0x00000118,0x00000118,0x00000000,0x00000001,0x00070058,0x00000012, + 0x0000011b,0x00000117,0x00000119,0x00000002,0x0000011a,0x0007004f,0x0000000a,0x0000011c, + 0x0000011b,0x0000011b,0x00000000,0x00000001,0x0003003e,0x0000002d,0x0000011c,0x0004003d, + 0x0000000a,0x0000011d,0x0000002d,0x00050094,0x00000009,0x00000120,0x0000011d,0x0000011f, + 0x00050041,0x00000036,0x00000121,0x000000e9,0x00000014,0x0003003e,0x00000121,0x00000120, + 0x000200f9,0x000000fc,0x000200f8,0x000000fc,0x000200f9,0x000000f9,0x000200f8,0x000000fb, + 0x0004003d,0x00000012,0x00000122,0x000000e9,0x0007004f,0x0000000a,0x00000123,0x00000122, + 0x00000122,0x00000002,0x00000003,0x000200fe,0x00000123,0x00010038,0x00050036,0x0000000a, + 0x00000034,0x00000000,0x00000029,0x00030037,0x00000028,0x00000030,0x00030037,0x0000000b, + 0x00000031,0x00030037,0x0000000b,0x00000032,0x00030037,0x0000000b,0x00000033,0x000200f8, + 0x00000035,0x0004003b,0x00000021,0x00000126,0x00000007,0x0004003b,0x000000f1,0x00000134, + 0x00000007,0x0004003b,0x0000000b,0x0000015c,0x00000007,0x0004003d,0x0000000a,0x00000127, + 0x00000031,0x00050051,0x00000009,0x00000128,0x00000127,0x00000000,0x00050051,0x00000009, + 0x00000129,0x00000127,0x00000001,0x00070050,0x00000012,0x0000012a,0x00000128,0x00000129, + 0x000000eb,0x000000ec,0x0003003e,0x00000126,0x0000012a,0x00060041,0x0000012c,0x0000012d, + 0x00000098,0x0000009a,0x00000084,0x0004003d,0x00000009,0x0000012e,0x0000012d,0x00050085, + 0x00000009,0x0000012f,0x0000012b,0x0000012e,0x00050041,0x00000036,0x00000130,0x00000126, + 0x00000084,0x0004003d,0x00000009,0x00000131,0x00000130,0x00050081,0x00000009,0x00000132, + 0x00000131,0x0000012f,0x00050041,0x00000036,0x00000133,0x00000126,0x00000084,0x0003003e, + 0x00000133,0x00000132,0x00050041,0x0000009b,0x00000135,0x00000098,0x0000009a,0x0004003d, + 0x00000012,0x00000136,0x00000135,0x0007004f,0x0000000a,0x00000137,0x00000136,0x00000136, + 0x00000000,0x00000001,0x00050051,0x00000009,0x00000138,0x00000137,0x00000000,0x00050051, + 0x00000009,0x00000139,0x00000137,0x00000001,0x00060050,0x000000f0,0x0000013a,0x00000138, + 0x00000139,0x000000ec,0x0003003e,0x00000134,0x0000013a,0x000200f9,0x0000013b,0x000200f8, + 0x0000013b,0x000400f6,0x0000013d,0x0000013e,0x00000000,0x000200f9,0x0000013f,0x000200f8, + 0x0000013f,0x00050041,0x00000036,0x00000140,0x00000126,0x000000e2,0x0004003d,0x00000009, + 0x00000141,0x00000140,0x000500b8,0x00000006,0x00000142,0x00000141,0x00000100,0x000300f7, + 0x00000144,0x00000000,0x000400fa,0x00000142,0x00000143,0x00000144,0x000200f8,0x00000143, + 0x00050041,0x00000036,0x00000145,0x00000126,0x00000014,0x0004003d,0x00000009,0x00000146, + 0x00000145,0x000500ba,0x00000006,0x00000147,0x00000146,0x00000106,0x000200f9,0x00000144, + 0x000200f8,0x00000144,0x000700f5,0x00000006,0x00000148,0x00000142,0x0000013f,0x00000147, + 0x00000143,0x000400fa,0x00000148,0x0000013c,0x0000013d,0x000200f8,0x0000013c,0x0004003d, + 0x000000f0,0x00000149,0x00000134,0x0004003d,0x0000000a,0x0000014a,0x00000032,0x00050051, + 0x00000009,0x0000014b,0x0000014a,0x00000000,0x00050051,0x00000009,0x0000014c,0x0000014a, + 0x00000001,0x00060050,0x000000f0,0x0000014d,0x0000014b,0x0000014c,0x000000ec,0x0004003d, + 0x00000012,0x0000014e,0x00000126,0x0008004f,0x000000f0,0x0000014f,0x0000014e,0x0000014e, + 0x00000000,0x00000001,0x00000002,0x0008000c,0x000000f0,0x00000150,0x00000001,0x00000032, + 0x00000149,0x0000014d,0x0000014f,0x00050041,0x00000036,0x00000151,0x00000126,0x00000084, + 0x00050051,0x00000009,0x00000152,0x00000150,0x00000000,0x0003003e,0x00000151,0x00000152, + 0x00050041,0x00000036,0x00000153,0x00000126,0x0000008d,0x00050051,0x00000009,0x00000154, + 0x00000150,0x00000001,0x0003003e,0x00000153,0x00000154,0x00050041,0x00000036,0x00000155, + 0x00000126,0x000000e2,0x00050051,0x00000009,0x00000156,0x00000150,0x00000002,0x0003003e, + 0x00000155,0x00000156,0x0004003d,0x00000027,0x00000157,0x00000030,0x0004003d,0x00000012, + 0x00000158,0x00000126,0x0007004f,0x0000000a,0x00000159,0x00000158,0x00000158,0x00000000, + 0x00000001,0x00070058,0x00000012,0x0000015a,0x00000157,0x00000159,0x00000002,0x0000011a, + 0x0007004f,0x0000000a,0x0000015b,0x0000015a,0x0000015a,0x00000000,0x00000001,0x0003003e, + 0x00000033,0x0000015b,0x0004003d,0x0000000a,0x0000015d,0x00000033,0x0003003e,0x0000015c, + 0x0000015d,0x00050039,0x0000000a,0x0000015e,0x0000001f,0x0000015c,0x0003003e,0x00000033, + 0x0000015e,0x0004003d,0x0000000a,0x0000015f,0x00000033,0x00050094,0x00000009,0x00000160, + 0x0000015f,0x0000011f,0x00050041,0x00000036,0x00000161,0x00000126,0x00000014,0x0003003e, + 0x00000161,0x00000160,0x000200f9,0x0000013e,0x000200f8,0x0000013e,0x000200f9,0x0000013b, + 0x000200f8,0x0000013d,0x0004003d,0x00000012,0x00000162,0x00000126,0x0007004f,0x0000000a, + 0x00000163,0x00000162,0x00000162,0x00000002,0x00000003,0x000200fe,0x00000163,0x00010038, + 0x00050036,0x0000000a,0x0000003c,0x00000000,0x00000037,0x00030037,0x00000028,0x00000038, + 0x00030037,0x0000000b,0x00000039,0x00030037,0x0000000b,0x0000003a,0x00030037,0x00000036, + 0x0000003b,0x000200f8,0x0000003d,0x0004003b,0x0000000b,0x00000166,0x00000007,0x0004003d, + 0x0000000a,0x00000169,0x0000003a,0x0004003d,0x0000000a,0x0000016a,0x00000039,0x0008000c, + 0x0000000a,0x0000016b,0x00000001,0x00000032,0x00000168,0x00000169,0x0000016a,0x0003003e, + 0x00000166,0x0000016b,0x0004003d,0x0000000a,0x0000016f,0x00000166,0x0008000c,0x0000000a, + 0x00000173,0x00000001,0x00000032,0x0000016e,0x0000016f,0x00000172,0x0003003e,0x00000166, + 0x00000173,0x00050041,0x00000036,0x00000174,0x00000166,0x00000084,0x0004003d,0x00000009, + 0x00000175,0x00000174,0x00050081,0x00000009,0x00000176,0x00000175,0x0000011e,0x00050041, + 0x00000036,0x00000177,0x00000166,0x00000084,0x0003003e,0x00000177,0x00000176,0x0004003d, + 0x00000009,0x00000179,0x0000003b,0x00050085,0x00000009,0x0000017a,0x00000178,0x00000179, + 0x00050041,0x00000036,0x0000017b,0x00000166,0x0000008d,0x0004003d,0x00000009,0x0000017c, + 0x0000017b,0x00050081,0x00000009,0x0000017d,0x0000017c,0x0000017a,0x00050041,0x00000036, + 0x0000017e,0x00000166,0x0000008d,0x0003003e,0x0000017e,0x0000017d,0x0004003d,0x00000027, + 0x0000017f,0x00000038,0x0004003d,0x0000000a,0x00000180,0x00000166,0x00070058,0x00000012, + 0x00000181,0x0000017f,0x00000180,0x00000002,0x0000011a,0x0007004f,0x0000000a,0x00000182, + 0x00000181,0x00000181,0x00000000,0x00000001,0x000200fe,0x00000182,0x00010038,0x00050036, + 0x0000000a,0x00000044,0x00000000,0x0000003e,0x00030037,0x00000028,0x0000003f,0x00030037, + 0x00000028,0x00000040,0x00030037,0x0000000b,0x00000041,0x00030037,0x0000000b,0x00000042, + 0x00030037,0x00000021,0x00000043,0x000200f8,0x00000045,0x0004003b,0x0000000b,0x00000185, + 0x00000007,0x0004003b,0x00000021,0x0000018c,0x00000007,0x0004003b,0x0000000b,0x0000018e, + 0x00000007,0x0004003b,0x0000000b,0x0000018f,0x00000007,0x0004003b,0x0000000b,0x00000191, + 0x00000007,0x0004003b,0x0000000b,0x00000192,0x00000007,0x0004003b,0x0000000b,0x000001a7, + 0x00000007,0x0004003b,0x0000000b,0x000001a9,0x00000007,0x0004003b,0x0000000b,0x000001aa, + 0x00000007,0x0004003b,0x00000021,0x000001ba,0x00000007,0x0004003b,0x00000021,0x000001ce, + 0x00000007,0x0004003b,0x00000021,0x000001e5,0x00000007,0x0004003b,0x0000000b,0x000001ea, + 0x00000007,0x0004003b,0x00000008,0x000001f6,0x00000007,0x0004003b,0x0000000b,0x000001f7, + 0x00000007,0x0004003b,0x0000000b,0x000001f9,0x00000007,0x0004003b,0x0000000b,0x000001fc, + 0x00000007,0x0004003b,0x0000000b,0x000001ff,0x00000007,0x0004003b,0x00000036,0x00000201, + 0x00000007,0x0004003b,0x0000000b,0x00000208,0x00000007,0x0004003b,0x0000000b,0x0000020a, + 0x00000007,0x0004003b,0x0000000b,0x0000020b,0x00000007,0x0004003b,0x0000000b,0x0000021a, + 0x00000007,0x0004003b,0x0000000b,0x0000021c,0x00000007,0x0004003b,0x0000000b,0x0000021d, + 0x00000007,0x0004003b,0x00000021,0x00000239,0x00000007,0x0004003b,0x00000021,0x0000024b, + 0x00000007,0x0004003b,0x0000000b,0x00000262,0x00000007,0x0004003b,0x00000008,0x0000026d, + 0x00000007,0x0004003b,0x0000000b,0x0000026e,0x00000007,0x0004003b,0x0000000b,0x00000270, + 0x00000007,0x0004003b,0x0000000b,0x00000273,0x00000007,0x0004003b,0x0000000b,0x00000276, + 0x00000007,0x0004003b,0x00000036,0x00000278,0x00000007,0x0003003e,0x00000185,0x00000186, + 0x00050041,0x00000036,0x00000187,0x00000042,0x00000084,0x0004003d,0x00000009,0x00000188, + 0x00000187,0x000500ba,0x00000006,0x00000189,0x00000188,0x0000011a,0x000300f7,0x0000018b, + 0x00000000,0x000400fa,0x00000189,0x0000018a,0x000001a1,0x000200f8,0x0000018a,0x0004003d, + 0x0000000a,0x00000190,0x00000041,0x0003003e,0x0000018f,0x00000190,0x0003003e,0x00000191, + 0x0000018d,0x00080039,0x0000000a,0x00000193,0x0000002e,0x0000003f,0x0000018f,0x00000191, + 0x00000192,0x0004003d,0x0000000a,0x00000194,0x00000192,0x0003003e,0x0000018e,0x00000194, + 0x00050041,0x00000036,0x00000195,0x0000018c,0x00000084,0x00050051,0x00000009,0x00000196, + 0x00000193,0x00000000,0x0003003e,0x00000195,0x00000196,0x00050041,0x00000036,0x00000197, + 0x0000018c,0x000000e2,0x00050051,0x00000009,0x00000198,0x00000193,0x00000001,0x0003003e, + 0x00000197,0x00000198,0x00050041,0x00000036,0x00000199,0x0000018e,0x0000008d,0x0004003d, + 0x00000009,0x0000019a,0x00000199,0x000500ba,0x00000006,0x0000019b,0x0000019a,0x00000106, + 0x000600a9,0x00000009,0x0000019c,0x0000019b,0x000000ec,0x0000011a,0x00050041,0x00000036, + 0x0000019d,0x0000018c,0x00000084,0x0004003d,0x00000009,0x0000019e,0x0000019d,0x00050081, + 0x00000009,0x0000019f,0x0000019e,0x0000019c,0x00050041,0x00000036,0x000001a0,0x0000018c, + 0x00000084,0x0003003e,0x000001a0,0x0000019f,0x000200f9,0x0000018b,0x000200f8,0x000001a1, + 0x00050041,0x00000036,0x000001a2,0x0000018c,0x00000084,0x00050051,0x00000009,0x000001a3, + 0x00000186,0x00000000,0x0003003e,0x000001a2,0x000001a3,0x00050041,0x00000036,0x000001a4, + 0x0000018c,0x000000e2,0x00050051,0x00000009,0x000001a5,0x00000186,0x00000001,0x0003003e, + 0x000001a4,0x000001a5,0x000200f9,0x0000018b,0x000200f8,0x0000018b,0x0004003d,0x0000000a, + 0x000001a8,0x00000041,0x0003003e,0x000001a7,0x000001a8,0x0003003e,0x000001a9,0x000001a6, + 0x00080039,0x0000000a,0x000001ab,0x0000002e,0x0000003f,0x000001a7,0x000001a9,0x000001aa, + 0x0004003d,0x0000000a,0x000001ac,0x000001aa,0x0003003e,0x0000018e,0x000001ac,0x00050041, + 0x00000036,0x000001ad,0x0000018c,0x0000008d,0x00050051,0x00000009,0x000001ae,0x000001ab, + 0x00000000,0x0003003e,0x000001ad,0x000001ae,0x00050041,0x00000036,0x000001af,0x0000018c, + 0x00000014,0x00050051,0x00000009,0x000001b0,0x000001ab,0x00000001,0x0003003e,0x000001af, + 0x000001b0,0x00050041,0x00000036,0x000001b1,0x0000018c,0x00000084,0x0004003d,0x00000009, + 0x000001b2,0x000001b1,0x00050041,0x00000036,0x000001b3,0x0000018c,0x0000008d,0x0004003d, + 0x00000009,0x000001b4,0x000001b3,0x00050081,0x00000009,0x000001b5,0x000001b2,0x000001b4, + 0x000500ba,0x00000006,0x000001b7,0x000001b5,0x000001b6,0x000300f7,0x000001b9,0x00000000, + 0x000400fa,0x000001b7,0x000001b8,0x000001b9,0x000200f8,0x000001b8,0x00050041,0x00000036, + 0x000001bb,0x0000018c,0x00000084,0x0004003d,0x00000009,0x000001bc,0x000001bb,0x0004007f, + 0x00000009,0x000001bd,0x000001bc,0x00050081,0x00000009,0x000001be,0x000001bd,0x0000012b, + 0x00050041,0x00000036,0x000001bf,0x0000018c,0x00000084,0x0004003d,0x00000009,0x000001c0, + 0x000001bf,0x00050041,0x00000036,0x000001c1,0x0000018c,0x0000008d,0x0004003d,0x00000009, + 0x000001c2,0x000001c1,0x00050041,0x00000036,0x000001c3,0x0000018c,0x0000008d,0x0004003d, + 0x00000009,0x000001c4,0x000001c3,0x0004007f,0x00000009,0x000001c5,0x000001c4,0x00050083, + 0x00000009,0x000001c6,0x000001c5,0x0000012b,0x00070050,0x00000012,0x000001c7,0x000001be, + 0x000001c0,0x000001c2,0x000001c6,0x00050041,0x0000009b,0x000001c8,0x00000098,0x0000009a, + 0x0004003d,0x00000012,0x000001c9,0x000001c8,0x0009004f,0x00000012,0x000001ca,0x000001c9, + 0x000001c9,0x00000000,0x00000001,0x00000000,0x00000001,0x0004003d,0x0000000a,0x000001cb, + 0x00000041,0x0009004f,0x00000012,0x000001cc,0x000001cb,0x000001cb,0x00000000,0x00000001, + 0x00000000,0x00000001,0x0008000c,0x00000012,0x000001cd,0x00000001,0x00000032,0x000001c7, + 0x000001ca,0x000001cc,0x0003003e,0x000001ba,0x000001cd,0x0004003d,0x00000027,0x000001cf, + 0x0000003f,0x0004003d,0x00000012,0x000001d0,0x000001ba,0x0007004f,0x0000000a,0x000001d1, + 0x000001d0,0x000001d0,0x00000000,0x00000001,0x00080058,0x00000012,0x000001d5,0x000001cf, + 0x000001d1,0x0000000a,0x0000011a,0x000001d4,0x0007004f,0x0000000a,0x000001d6,0x000001d5, + 0x000001d5,0x00000000,0x00000001,0x00050041,0x00000036,0x000001d7,0x000001ce,0x00000084, + 0x00050051,0x00000009,0x000001d8,0x000001d6,0x00000000,0x0003003e,0x000001d7,0x000001d8, + 0x00050041,0x00000036,0x000001d9,0x000001ce,0x0000008d,0x00050051,0x00000009,0x000001da, + 0x000001d6,0x00000001,0x0003003e,0x000001d9,0x000001da,0x0004003d,0x00000027,0x000001db, + 0x0000003f,0x0004003d,0x00000012,0x000001dc,0x000001ba,0x0007004f,0x0000000a,0x000001dd, + 0x000001dc,0x000001dc,0x00000002,0x00000003,0x00080058,0x00000012,0x000001df,0x000001db, + 0x000001dd,0x0000000a,0x0000011a,0x000001de,0x0007004f,0x0000000a,0x000001e0,0x000001df, + 0x000001df,0x00000000,0x00000001,0x00050041,0x00000036,0x000001e1,0x000001ce,0x000000e2, + 0x00050051,0x00000009,0x000001e2,0x000001e0,0x00000000,0x0003003e,0x000001e1,0x000001e2, + 0x00050041,0x00000036,0x000001e3,0x000001ce,0x00000014,0x00050051,0x00000009,0x000001e4, + 0x000001e0,0x00000001,0x0003003e,0x000001e3,0x000001e4,0x0004003d,0x00000012,0x000001e6, + 0x000001ce,0x0003003e,0x000001e5,0x000001e6,0x00050039,0x00000012,0x000001e7,0x00000024, + 0x000001e5,0x0004003d,0x00000012,0x000001e8,0x000001ce,0x0009004f,0x00000012,0x000001e9, + 0x000001e8,0x000001e7,0x00000005,0x00000004,0x00000007,0x00000006,0x0003003e,0x000001ce, + 0x000001e9,0x0004003d,0x00000012,0x000001ec,0x000001ce,0x0007004f,0x0000000a,0x000001ed, + 0x000001ec,0x000001ec,0x00000000,0x00000002,0x0004003d,0x00000012,0x000001ee,0x000001ce, + 0x0007004f,0x0000000a,0x000001ef,0x000001ee,0x000001ee,0x00000001,0x00000003,0x0008000c, + 0x0000000a,0x000001f0,0x00000001,0x00000032,0x000001eb,0x000001ed,0x000001ef,0x0003003e, + 0x000001ea,0x000001f0,0x0004003d,0x00000012,0x000001f1,0x0000018c,0x0007004f,0x0000000a, + 0x000001f2,0x000001f1,0x000001f1,0x00000002,0x00000003,0x00050050,0x0000000a,0x000001f3, + 0x00000106,0x00000106,0x0007000c,0x0000000a,0x000001f4,0x00000001,0x00000030,0x000001f3, + 0x000001f2,0x000500b7,0x00000007,0x000001f5,0x000001f4,0x00000186,0x0003003e,0x000001f6, + 0x000001f5,0x0004003d,0x0000000a,0x000001f8,0x000001ea,0x0003003e,0x000001f7,0x000001f8, + 0x0003003e,0x000001f9,0x00000186,0x00070039,0x00000002,0x000001fa,0x00000010,0x000001f6, + 0x000001f7,0x000001f9,0x0004003d,0x0000000a,0x000001fb,0x000001f7,0x0003003e,0x000001ea, + 0x000001fb,0x0004003d,0x00000012,0x000001fd,0x0000018c,0x0007004f,0x0000000a,0x000001fe, + 0x000001fd,0x000001fd,0x00000000,0x00000001,0x0003003e,0x000001fc,0x000001fe,0x0004003d, + 0x0000000a,0x00000200,0x000001ea,0x0003003e,0x000001ff,0x00000200,0x00050041,0x00000036, + 0x00000202,0x00000043,0x000000e2,0x0004003d,0x00000009,0x00000203,0x00000202,0x0003003e, + 0x00000201,0x00000203,0x00080039,0x0000000a,0x00000204,0x0000003c,0x00000040,0x000001fc, + 0x000001ff,0x00000201,0x0004003d,0x0000000a,0x00000205,0x00000185,0x00050081,0x0000000a, + 0x00000206,0x00000205,0x00000204,0x0003003e,0x00000185,0x00000206,0x000200f9,0x000001b9, + 0x000200f8,0x000001b9,0x0004003d,0x0000000a,0x00000209,0x00000041,0x0003003e,0x00000208, + 0x00000209,0x0003003e,0x0000020a,0x00000207,0x00080039,0x0000000a,0x0000020c,0x00000034, + 0x0000003f,0x00000208,0x0000020a,0x0000020b,0x0004003d,0x0000000a,0x0000020d,0x0000020b, + 0x0003003e,0x0000018e,0x0000020d,0x00050041,0x00000036,0x0000020e,0x0000018c,0x00000084, + 0x00050051,0x00000009,0x0000020f,0x0000020c,0x00000000,0x0003003e,0x0000020e,0x0000020f, + 0x00050041,0x00000036,0x00000210,0x0000018c,0x000000e2,0x00050051,0x00000009,0x00000211, + 0x0000020c,0x00000001,0x0003003e,0x00000210,0x00000211,0x0004003d,0x00000027,0x00000212, + 0x0000003f,0x0004003d,0x0000000a,0x00000213,0x00000041,0x00080058,0x00000012,0x00000214, + 0x00000212,0x00000213,0x0000000a,0x0000011a,0x000001de,0x00050051,0x00000009,0x00000215, + 0x00000214,0x00000000,0x000500ba,0x00000006,0x00000216,0x00000215,0x0000011a,0x000300f7, + 0x00000218,0x00000000,0x000400fa,0x00000216,0x00000217,0x0000022c,0x000200f8,0x00000217, + 0x0004003d,0x0000000a,0x0000021b,0x00000041,0x0003003e,0x0000021a,0x0000021b,0x0003003e, + 0x0000021c,0x00000219,0x00080039,0x0000000a,0x0000021e,0x00000034,0x0000003f,0x0000021a, + 0x0000021c,0x0000021d,0x0004003d,0x0000000a,0x0000021f,0x0000021d,0x0003003e,0x0000018e, + 0x0000021f,0x00050041,0x00000036,0x00000220,0x0000018c,0x0000008d,0x00050051,0x00000009, + 0x00000221,0x0000021e,0x00000000,0x0003003e,0x00000220,0x00000221,0x00050041,0x00000036, + 0x00000222,0x0000018c,0x00000014,0x00050051,0x00000009,0x00000223,0x0000021e,0x00000001, + 0x0003003e,0x00000222,0x00000223,0x00050041,0x00000036,0x00000224,0x0000018e,0x0000008d, + 0x0004003d,0x00000009,0x00000225,0x00000224,0x000500ba,0x00000006,0x00000226,0x00000225, + 0x00000106,0x000600a9,0x00000009,0x00000227,0x00000226,0x000000ec,0x0000011a,0x00050041, + 0x00000036,0x00000228,0x0000018c,0x0000008d,0x0004003d,0x00000009,0x00000229,0x00000228, + 0x00050081,0x00000009,0x0000022a,0x00000229,0x00000227,0x00050041,0x00000036,0x0000022b, + 0x0000018c,0x0000008d,0x0003003e,0x0000022b,0x0000022a,0x000200f9,0x00000218,0x000200f8, + 0x0000022c,0x00050041,0x00000036,0x0000022d,0x0000018c,0x0000008d,0x00050051,0x00000009, + 0x0000022e,0x00000186,0x00000000,0x0003003e,0x0000022d,0x0000022e,0x00050041,0x00000036, + 0x0000022f,0x0000018c,0x00000014,0x00050051,0x00000009,0x00000230,0x00000186,0x00000001, + 0x0003003e,0x0000022f,0x00000230,0x000200f9,0x00000218,0x000200f8,0x00000218,0x00050041, + 0x00000036,0x00000231,0x0000018c,0x00000084,0x0004003d,0x00000009,0x00000232,0x00000231, + 0x00050041,0x00000036,0x00000233,0x0000018c,0x0000008d,0x0004003d,0x00000009,0x00000234, + 0x00000233,0x00050081,0x00000009,0x00000235,0x00000232,0x00000234,0x000500ba,0x00000006, + 0x00000236,0x00000235,0x000001b6,0x000300f7,0x00000238,0x00000000,0x000400fa,0x00000236, + 0x00000237,0x00000238,0x000200f8,0x00000237,0x00050041,0x00000036,0x0000023a,0x0000018c, + 0x00000084,0x0004003d,0x00000009,0x0000023b,0x0000023a,0x0004007f,0x00000009,0x0000023c, + 0x0000023b,0x00050041,0x00000036,0x0000023d,0x0000018c,0x00000084,0x0004003d,0x00000009, + 0x0000023e,0x0000023d,0x0004007f,0x00000009,0x0000023f,0x0000023e,0x00050041,0x00000036, + 0x00000240,0x0000018c,0x0000008d,0x0004003d,0x00000009,0x00000241,0x00000240,0x00050041, + 0x00000036,0x00000242,0x0000018c,0x0000008d,0x0004003d,0x00000009,0x00000243,0x00000242, + 0x00070050,0x00000012,0x00000244,0x0000023c,0x0000023f,0x00000241,0x00000243,0x00050041, + 0x0000009b,0x00000245,0x00000098,0x0000009a,0x0004003d,0x00000012,0x00000246,0x00000245, + 0x0009004f,0x00000012,0x00000247,0x00000246,0x00000246,0x00000000,0x00000001,0x00000000, + 0x00000001,0x0004003d,0x0000000a,0x00000248,0x00000041,0x0009004f,0x00000012,0x00000249, + 0x00000248,0x00000248,0x00000000,0x00000001,0x00000000,0x00000001,0x0008000c,0x00000012, + 0x0000024a,0x00000001,0x00000032,0x00000244,0x00000247,0x00000249,0x0003003e,0x00000239, + 0x0000024a,0x0004003d,0x00000027,0x0000024c,0x0000003f,0x0004003d,0x00000012,0x0000024d, + 0x00000239,0x0007004f,0x0000000a,0x0000024e,0x0000024d,0x0000024d,0x00000000,0x00000001, + 0x00080058,0x00000012,0x0000024f,0x0000024c,0x0000024e,0x0000000a,0x0000011a,0x000001d4, + 0x00050051,0x00000009,0x00000250,0x0000024f,0x00000001,0x00050041,0x00000036,0x00000251, + 0x0000024b,0x00000084,0x0003003e,0x00000251,0x00000250,0x0004003d,0x00000027,0x00000252, + 0x0000003f,0x0004003d,0x00000012,0x00000253,0x00000239,0x0007004f,0x0000000a,0x00000254, + 0x00000253,0x00000253,0x00000000,0x00000001,0x00080058,0x00000012,0x00000256,0x00000252, + 0x00000254,0x0000000a,0x0000011a,0x00000255,0x00050051,0x00000009,0x00000257,0x00000256, + 0x00000000,0x00050041,0x00000036,0x00000258,0x0000024b,0x0000008d,0x0003003e,0x00000258, + 0x00000257,0x0004003d,0x00000027,0x00000259,0x0000003f,0x0004003d,0x00000012,0x0000025a, + 0x00000239,0x0007004f,0x0000000a,0x0000025b,0x0000025a,0x0000025a,0x00000002,0x00000003, + 0x00080058,0x00000012,0x0000025c,0x00000259,0x0000025b,0x0000000a,0x0000011a,0x000001de, + 0x0007004f,0x0000000a,0x0000025d,0x0000025c,0x0000025c,0x00000001,0x00000000,0x00050041, + 0x00000036,0x0000025e,0x0000024b,0x000000e2,0x00050051,0x00000009,0x0000025f,0x0000025d, + 0x00000000,0x0003003e,0x0000025e,0x0000025f,0x00050041,0x00000036,0x00000260,0x0000024b, + 0x00000014,0x00050051,0x00000009,0x00000261,0x0000025d,0x00000001,0x0003003e,0x00000260, + 0x00000261,0x0004003d,0x00000012,0x00000263,0x0000024b,0x0007004f,0x0000000a,0x00000264, + 0x00000263,0x00000263,0x00000000,0x00000002,0x0004003d,0x00000012,0x00000265,0x0000024b, + 0x0007004f,0x0000000a,0x00000266,0x00000265,0x00000265,0x00000001,0x00000003,0x0008000c, + 0x0000000a,0x00000267,0x00000001,0x00000032,0x000001eb,0x00000264,0x00000266,0x0003003e, + 0x00000262,0x00000267,0x0004003d,0x00000012,0x00000268,0x0000018c,0x0007004f,0x0000000a, + 0x00000269,0x00000268,0x00000268,0x00000002,0x00000003,0x00050050,0x0000000a,0x0000026a, + 0x00000106,0x00000106,0x0007000c,0x0000000a,0x0000026b,0x00000001,0x00000030,0x0000026a, + 0x00000269,0x000500b7,0x00000007,0x0000026c,0x0000026b,0x00000186,0x0003003e,0x0000026d, + 0x0000026c,0x0004003d,0x0000000a,0x0000026f,0x00000262,0x0003003e,0x0000026e,0x0000026f, + 0x0003003e,0x00000270,0x00000186,0x00070039,0x00000002,0x00000271,0x00000010,0x0000026d, + 0x0000026e,0x00000270,0x0004003d,0x0000000a,0x00000272,0x0000026e,0x0003003e,0x00000262, + 0x00000272,0x0004003d,0x00000012,0x00000274,0x0000018c,0x0007004f,0x0000000a,0x00000275, + 0x00000274,0x00000274,0x00000000,0x00000001,0x0003003e,0x00000273,0x00000275,0x0004003d, + 0x0000000a,0x00000277,0x00000262,0x0003003e,0x00000276,0x00000277,0x00050041,0x00000036, + 0x00000279,0x00000043,0x00000014,0x0004003d,0x00000009,0x0000027a,0x00000279,0x0003003e, + 0x00000278,0x0000027a,0x00080039,0x0000000a,0x0000027b,0x0000003c,0x00000040,0x00000273, + 0x00000276,0x00000278,0x0007004f,0x0000000a,0x0000027c,0x0000027b,0x0000027b,0x00000001, + 0x00000000,0x0004003d,0x0000000a,0x0000027d,0x00000185,0x00050081,0x0000000a,0x0000027e, + 0x0000027d,0x0000027c,0x0003003e,0x00000185,0x0000027e,0x000200f9,0x00000238,0x000200f8, + 0x00000238,0x0004003d,0x0000000a,0x0000027f,0x00000185,0x000200fe,0x0000027f,0x00010038, + 0x00050036,0x00000009,0x0000004a,0x00000000,0x00000046,0x00030037,0x00000028,0x00000047, + 0x00030037,0x0000000b,0x00000048,0x00030037,0x00000036,0x00000049,0x000200f8,0x0000004b, + 0x0004003b,0x0000000b,0x00000282,0x00000007,0x0004003b,0x0000000b,0x00000286,0x00000007, + 0x0003003e,0x00000282,0x00000285,0x0004003d,0x00000009,0x00000289,0x00000049,0x00050050, + 0x0000000a,0x0000028a,0x00000289,0x000000ec,0x00050085,0x0000000a,0x0000028b,0x00000288, + 0x0000028a,0x0003003e,0x00000286,0x0000028b,0x0004003d,0x0000000a,0x0000028c,0x00000282, + 0x00050081,0x0000000a,0x0000028d,0x0000028c,0x0000018d,0x0003003e,0x00000282,0x0000028d, + 0x0004003d,0x0000000a,0x00000290,0x00000286,0x00050081,0x0000000a,0x00000291,0x00000290, + 0x0000028f,0x0003003e,0x00000286,0x00000291,0x0004003d,0x0000000a,0x00000295,0x00000282, + 0x00050085,0x0000000a,0x00000296,0x00000295,0x00000294,0x0003003e,0x00000282,0x00000296, + 0x0004003d,0x0000000a,0x00000297,0x00000286,0x00050085,0x0000000a,0x00000298,0x00000297, + 0x00000294,0x0003003e,0x00000286,0x00000298,0x0004003d,0x00000027,0x00000299,0x00000047, + 0x0004003d,0x0000000a,0x0000029a,0x00000282,0x0004003d,0x0000000a,0x0000029b,0x00000048, + 0x0004003d,0x0000000a,0x0000029c,0x00000286,0x0008000c,0x0000000a,0x0000029d,0x00000001, + 0x00000032,0x0000029a,0x0000029b,0x0000029c,0x00070058,0x00000012,0x0000029e,0x00000299, + 0x0000029d,0x00000002,0x0000011a,0x00050051,0x00000009,0x0000029f,0x0000029e,0x00000000, + 0x000200fe,0x0000029f,0x00010038,0x00050036,0x00000009,0x00000051,0x00000000,0x0000004c, + 0x00030037,0x00000028,0x0000004d,0x00030037,0x00000028,0x0000004e,0x00030037,0x0000000b, + 0x0000004f,0x00030037,0x00000036,0x00000050,0x000200f8,0x00000052,0x0004003b,0x0000000b, + 0x000002a2,0x00000007,0x0004003b,0x00000036,0x000002c6,0x00000007,0x0004003b,0x0000000b, + 0x000002c8,0x00000007,0x0004003b,0x00000036,0x000002ca,0x00000007,0x0003003e,0x000002a2, + 0x000002a3,0x000200f9,0x000002a4,0x000200f8,0x000002a4,0x000400f6,0x000002a6,0x000002a7, + 0x00000000,0x000200f9,0x000002a8,0x000200f8,0x000002a8,0x00050041,0x00000036,0x000002a9, + 0x0000004f,0x00000084,0x0004003d,0x00000009,0x000002aa,0x000002a9,0x0004003d,0x00000009, + 0x000002ab,0x00000050,0x000500ba,0x00000006,0x000002ac,0x000002aa,0x000002ab,0x000300f7, + 0x000002ae,0x00000000,0x000400fa,0x000002ac,0x000002ad,0x000002ae,0x000200f8,0x000002ad, + 0x00050041,0x00000036,0x000002af,0x000002a2,0x0000008d,0x0004003d,0x00000009,0x000002b0, + 0x000002af,0x000500ba,0x00000006,0x000002b2,0x000002b0,0x000002b1,0x000200f9,0x000002ae, + 0x000200f8,0x000002ae,0x000700f5,0x00000006,0x000002b3,0x000002ac,0x000002a8,0x000002b2, + 0x000002ad,0x000300f7,0x000002b5,0x00000000,0x000400fa,0x000002b3,0x000002b4,0x000002b5, + 0x000200f8,0x000002b4,0x00050041,0x00000036,0x000002b6,0x000002a2,0x00000084,0x0004003d, + 0x00000009,0x000002b7,0x000002b6,0x000500b4,0x00000006,0x000002b8,0x000002b7,0x0000011a, + 0x000200f9,0x000002b5,0x000200f8,0x000002b5,0x000700f5,0x00000006,0x000002b9,0x000002b3, + 0x000002ae,0x000002b8,0x000002b4,0x000400fa,0x000002b9,0x000002a5,0x000002a6,0x000200f8, + 0x000002a5,0x0004003d,0x00000027,0x000002ba,0x0000004d,0x0004003d,0x0000000a,0x000002bb, + 0x0000004f,0x00070058,0x00000012,0x000002bc,0x000002ba,0x000002bb,0x00000002,0x0000011a, + 0x0007004f,0x0000000a,0x000002bd,0x000002bc,0x000002bc,0x00000000,0x00000001,0x0003003e, + 0x000002a2,0x000002bd,0x00050041,0x0000009b,0x000002c1,0x00000098,0x0000009a,0x0004003d, + 0x00000012,0x000002c2,0x000002c1,0x0007004f,0x0000000a,0x000002c3,0x000002c2,0x000002c2, + 0x00000000,0x00000001,0x0004003d,0x0000000a,0x000002c4,0x0000004f,0x0008000c,0x0000000a, + 0x000002c5,0x00000001,0x00000032,0x000002c0,0x000002c3,0x000002c4,0x0003003e,0x0000004f, + 0x000002c5,0x000200f9,0x000002a7,0x000200f8,0x000002a7,0x000200f9,0x000002a4,0x000200f8, + 0x000002a6,0x0004003d,0x0000000a,0x000002c9,0x000002a2,0x0003003e,0x000002c8,0x000002c9, + 0x0003003e,0x000002ca,0x0000011a,0x00070039,0x00000009,0x000002cb,0x0000004a,0x0000004e, + 0x000002c8,0x000002ca,0x0008000c,0x00000009,0x000002cd,0x00000001,0x00000032,0x000002c7, + 0x000002cb,0x000002cc,0x0003003e,0x000002c6,0x000002cd,0x00060041,0x0000012c,0x000002ce, + 0x00000098,0x0000009a,0x00000084,0x0004003d,0x00000009,0x000002cf,0x000002ce,0x0004003d, + 0x00000009,0x000002d0,0x000002c6,0x00050041,0x00000036,0x000002d1,0x0000004f,0x00000084, + 0x0004003d,0x00000009,0x000002d2,0x000002d1,0x0008000c,0x00000009,0x000002d3,0x00000001, + 0x00000032,0x000002cf,0x000002d0,0x000002d2,0x000200fe,0x000002d3,0x00010038,0x00050036, + 0x00000009,0x00000057,0x00000000,0x0000004c,0x00030037,0x00000028,0x00000053,0x00030037, + 0x00000028,0x00000054,0x00030037,0x0000000b,0x00000055,0x00030037,0x00000036,0x00000056, + 0x000200f8,0x00000058,0x0004003b,0x0000000b,0x000002d6,0x00000007,0x0004003b,0x00000036, + 0x000002f6,0x00000007,0x0004003b,0x0000000b,0x000002f7,0x00000007,0x0004003b,0x00000036, + 0x000002f9,0x00000007,0x0003003e,0x000002d6,0x000002a3,0x000200f9,0x000002d7,0x000200f8, + 0x000002d7,0x000400f6,0x000002d9,0x000002da,0x00000000,0x000200f9,0x000002db,0x000200f8, + 0x000002db,0x00050041,0x00000036,0x000002dc,0x00000055,0x00000084,0x0004003d,0x00000009, + 0x000002dd,0x000002dc,0x0004003d,0x00000009,0x000002de,0x00000056,0x000500b8,0x00000006, + 0x000002df,0x000002dd,0x000002de,0x000300f7,0x000002e1,0x00000000,0x000400fa,0x000002df, + 0x000002e0,0x000002e1,0x000200f8,0x000002e0,0x00050041,0x00000036,0x000002e2,0x000002d6, + 0x0000008d,0x0004003d,0x00000009,0x000002e3,0x000002e2,0x000500ba,0x00000006,0x000002e4, + 0x000002e3,0x000002b1,0x000200f9,0x000002e1,0x000200f8,0x000002e1,0x000700f5,0x00000006, + 0x000002e5,0x000002df,0x000002db,0x000002e4,0x000002e0,0x000300f7,0x000002e7,0x00000000, + 0x000400fa,0x000002e5,0x000002e6,0x000002e7,0x000200f8,0x000002e6,0x00050041,0x00000036, + 0x000002e8,0x000002d6,0x00000084,0x0004003d,0x00000009,0x000002e9,0x000002e8,0x000500b4, + 0x00000006,0x000002ea,0x000002e9,0x0000011a,0x000200f9,0x000002e7,0x000200f8,0x000002e7, + 0x000700f5,0x00000006,0x000002eb,0x000002e5,0x000002e1,0x000002ea,0x000002e6,0x000400fa, + 0x000002eb,0x000002d8,0x000002d9,0x000200f8,0x000002d8,0x0004003d,0x00000027,0x000002ec, + 0x00000053,0x0004003d,0x0000000a,0x000002ed,0x00000055,0x00070058,0x00000012,0x000002ee, + 0x000002ec,0x000002ed,0x00000002,0x0000011a,0x0007004f,0x0000000a,0x000002ef,0x000002ee, + 0x000002ee,0x00000000,0x00000001,0x0003003e,0x000002d6,0x000002ef,0x00050041,0x0000009b, + 0x000002f1,0x00000098,0x0000009a,0x0004003d,0x00000012,0x000002f2,0x000002f1,0x0007004f, + 0x0000000a,0x000002f3,0x000002f2,0x000002f2,0x00000000,0x00000001,0x0004003d,0x0000000a, + 0x000002f4,0x00000055,0x0008000c,0x0000000a,0x000002f5,0x00000001,0x00000032,0x000002f0, + 0x000002f3,0x000002f4,0x0003003e,0x00000055,0x000002f5,0x000200f9,0x000002da,0x000200f8, + 0x000002da,0x000200f9,0x000002d7,0x000200f8,0x000002d9,0x0004003d,0x0000000a,0x000002f8, + 0x000002d6,0x0003003e,0x000002f7,0x000002f8,0x0003003e,0x000002f9,0x0000011e,0x00070039, + 0x00000009,0x000002fa,0x0000004a,0x00000054,0x000002f7,0x000002f9,0x0008000c,0x00000009, + 0x000002fb,0x00000001,0x00000032,0x000002c7,0x000002fa,0x000002cc,0x0003003e,0x000002f6, + 0x000002fb,0x00060041,0x0000012c,0x000002fc,0x00000098,0x0000009a,0x00000084,0x0004003d, + 0x00000009,0x000002fd,0x000002fc,0x0004007f,0x00000009,0x000002fe,0x000002fd,0x0004003d, + 0x00000009,0x000002ff,0x000002f6,0x00050041,0x00000036,0x00000300,0x00000055,0x00000084, + 0x0004003d,0x00000009,0x00000301,0x00000300,0x0008000c,0x00000009,0x00000302,0x00000001, + 0x00000032,0x000002fe,0x000002ff,0x00000301,0x000200fe,0x00000302,0x00010038,0x00050036, + 0x00000009,0x0000005d,0x00000000,0x0000004c,0x00030037,0x00000028,0x00000059,0x00030037, + 0x00000028,0x0000005a,0x00030037,0x0000000b,0x0000005b,0x00030037,0x00000036,0x0000005c, + 0x000200f8,0x0000005e,0x0004003b,0x0000000b,0x00000305,0x00000007,0x0004003b,0x00000036, + 0x00000326,0x00000007,0x0004003b,0x0000000b,0x00000327,0x00000007,0x0004003b,0x00000036, + 0x0000032a,0x00000007,0x0003003e,0x00000305,0x00000306,0x000200f9,0x00000307,0x000200f8, + 0x00000307,0x000400f6,0x00000309,0x0000030a,0x00000000,0x000200f9,0x0000030b,0x000200f8, + 0x0000030b,0x00050041,0x00000036,0x0000030c,0x0000005b,0x0000008d,0x0004003d,0x00000009, + 0x0000030d,0x0000030c,0x0004003d,0x00000009,0x0000030e,0x0000005c,0x000500ba,0x00000006, + 0x0000030f,0x0000030d,0x0000030e,0x000300f7,0x00000311,0x00000000,0x000400fa,0x0000030f, + 0x00000310,0x00000311,0x000200f8,0x00000310,0x00050041,0x00000036,0x00000312,0x00000305, + 0x00000084,0x0004003d,0x00000009,0x00000313,0x00000312,0x000500ba,0x00000006,0x00000314, + 0x00000313,0x000002b1,0x000200f9,0x00000311,0x000200f8,0x00000311,0x000700f5,0x00000006, + 0x00000315,0x0000030f,0x0000030b,0x00000314,0x00000310,0x000300f7,0x00000317,0x00000000, + 0x000400fa,0x00000315,0x00000316,0x00000317,0x000200f8,0x00000316,0x00050041,0x00000036, + 0x00000318,0x00000305,0x0000008d,0x0004003d,0x00000009,0x00000319,0x00000318,0x000500b4, + 0x00000006,0x0000031a,0x00000319,0x0000011a,0x000200f9,0x00000317,0x000200f8,0x00000317, + 0x000700f5,0x00000006,0x0000031b,0x00000315,0x00000311,0x0000031a,0x00000316,0x000400fa, + 0x0000031b,0x00000308,0x00000309,0x000200f8,0x00000308,0x0004003d,0x00000027,0x0000031c, + 0x00000059,0x0004003d,0x0000000a,0x0000031d,0x0000005b,0x00070058,0x00000012,0x0000031e, + 0x0000031c,0x0000031d,0x00000002,0x0000011a,0x0007004f,0x0000000a,0x0000031f,0x0000031e, + 0x0000031e,0x00000000,0x00000001,0x0003003e,0x00000305,0x0000031f,0x00050041,0x0000009b, + 0x00000321,0x00000098,0x0000009a,0x0004003d,0x00000012,0x00000322,0x00000321,0x0007004f, + 0x0000000a,0x00000323,0x00000322,0x00000322,0x00000000,0x00000001,0x0004003d,0x0000000a, + 0x00000324,0x0000005b,0x0008000c,0x0000000a,0x00000325,0x00000001,0x00000032,0x00000320, + 0x00000323,0x00000324,0x0003003e,0x0000005b,0x00000325,0x000200f9,0x0000030a,0x000200f8, + 0x0000030a,0x000200f9,0x00000307,0x000200f8,0x00000309,0x0004003d,0x0000000a,0x00000328, + 0x00000305,0x0007004f,0x0000000a,0x00000329,0x00000328,0x00000328,0x00000001,0x00000000, + 0x0003003e,0x00000327,0x00000329,0x0003003e,0x0000032a,0x0000011a,0x00070039,0x00000009, + 0x0000032b,0x0000004a,0x0000005a,0x00000327,0x0000032a,0x0008000c,0x00000009,0x0000032c, + 0x00000001,0x00000032,0x000002c7,0x0000032b,0x000002cc,0x0003003e,0x00000326,0x0000032c, + 0x00060041,0x0000012c,0x0000032d,0x00000098,0x0000009a,0x0000008d,0x0004003d,0x00000009, + 0x0000032e,0x0000032d,0x0004003d,0x00000009,0x0000032f,0x00000326,0x00050041,0x00000036, + 0x00000330,0x0000005b,0x0000008d,0x0004003d,0x00000009,0x00000331,0x00000330,0x0008000c, + 0x00000009,0x00000332,0x00000001,0x00000032,0x0000032e,0x0000032f,0x00000331,0x000200fe, + 0x00000332,0x00010038,0x00050036,0x00000009,0x00000063,0x00000000,0x0000004c,0x00030037, + 0x00000028,0x0000005f,0x00030037,0x00000028,0x00000060,0x00030037,0x0000000b,0x00000061, + 0x00030037,0x00000036,0x00000062,0x000200f8,0x00000064,0x0004003b,0x0000000b,0x00000335, + 0x00000007,0x0004003b,0x00000036,0x00000355,0x00000007,0x0004003b,0x0000000b,0x00000356, + 0x00000007,0x0004003b,0x00000036,0x00000359,0x00000007,0x0003003e,0x00000335,0x00000306, + 0x000200f9,0x00000336,0x000200f8,0x00000336,0x000400f6,0x00000338,0x00000339,0x00000000, + 0x000200f9,0x0000033a,0x000200f8,0x0000033a,0x00050041,0x00000036,0x0000033b,0x00000061, + 0x0000008d,0x0004003d,0x00000009,0x0000033c,0x0000033b,0x0004003d,0x00000009,0x0000033d, + 0x00000062,0x000500b8,0x00000006,0x0000033e,0x0000033c,0x0000033d,0x000300f7,0x00000340, + 0x00000000,0x000400fa,0x0000033e,0x0000033f,0x00000340,0x000200f8,0x0000033f,0x00050041, + 0x00000036,0x00000341,0x00000335,0x00000084,0x0004003d,0x00000009,0x00000342,0x00000341, + 0x000500ba,0x00000006,0x00000343,0x00000342,0x000002b1,0x000200f9,0x00000340,0x000200f8, + 0x00000340,0x000700f5,0x00000006,0x00000344,0x0000033e,0x0000033a,0x00000343,0x0000033f, + 0x000300f7,0x00000346,0x00000000,0x000400fa,0x00000344,0x00000345,0x00000346,0x000200f8, + 0x00000345,0x00050041,0x00000036,0x00000347,0x00000335,0x0000008d,0x0004003d,0x00000009, + 0x00000348,0x00000347,0x000500b4,0x00000006,0x00000349,0x00000348,0x0000011a,0x000200f9, + 0x00000346,0x000200f8,0x00000346,0x000700f5,0x00000006,0x0000034a,0x00000344,0x00000340, + 0x00000349,0x00000345,0x000400fa,0x0000034a,0x00000337,0x00000338,0x000200f8,0x00000337, + 0x0004003d,0x00000027,0x0000034b,0x0000005f,0x0004003d,0x0000000a,0x0000034c,0x00000061, + 0x00070058,0x00000012,0x0000034d,0x0000034b,0x0000034c,0x00000002,0x0000011a,0x0007004f, + 0x0000000a,0x0000034e,0x0000034d,0x0000034d,0x00000000,0x00000001,0x0003003e,0x00000335, + 0x0000034e,0x00050041,0x0000009b,0x00000350,0x00000098,0x0000009a,0x0004003d,0x00000012, + 0x00000351,0x00000350,0x0007004f,0x0000000a,0x00000352,0x00000351,0x00000351,0x00000000, + 0x00000001,0x0004003d,0x0000000a,0x00000353,0x00000061,0x0008000c,0x0000000a,0x00000354, + 0x00000001,0x00000032,0x0000034f,0x00000352,0x00000353,0x0003003e,0x00000061,0x00000354, + 0x000200f9,0x00000339,0x000200f8,0x00000339,0x000200f9,0x00000336,0x000200f8,0x00000338, + 0x0004003d,0x0000000a,0x00000357,0x00000335,0x0007004f,0x0000000a,0x00000358,0x00000357, + 0x00000357,0x00000001,0x00000000,0x0003003e,0x00000356,0x00000358,0x0003003e,0x00000359, + 0x0000011e,0x00070039,0x00000009,0x0000035a,0x0000004a,0x00000060,0x00000356,0x00000359, + 0x0008000c,0x00000009,0x0000035b,0x00000001,0x00000032,0x000002c7,0x0000035a,0x000002cc, + 0x0003003e,0x00000355,0x0000035b,0x00060041,0x0000012c,0x0000035c,0x00000098,0x0000009a, + 0x0000008d,0x0004003d,0x00000009,0x0000035d,0x0000035c,0x0004007f,0x00000009,0x0000035e, + 0x0000035d,0x0004003d,0x00000009,0x0000035f,0x00000355,0x00050041,0x00000036,0x00000360, + 0x00000061,0x0000008d,0x0004003d,0x00000009,0x00000361,0x00000360,0x0008000c,0x00000009, + 0x00000362,0x00000001,0x00000032,0x0000035e,0x0000035f,0x00000361,0x000200fe,0x00000362, + 0x00010038,0x00050036,0x0000000a,0x0000006b,0x00000000,0x00000065,0x00030037,0x00000028, + 0x00000066,0x00030037,0x0000000b,0x00000067,0x00030037,0x00000036,0x00000068,0x00030037, + 0x00000036,0x00000069,0x00030037,0x00000036,0x0000006a,0x000200f8,0x0000006c,0x0004003b, + 0x0000000b,0x00000365,0x00000007,0x0004003d,0x00000009,0x00000369,0x00000068,0x0004003d, + 0x00000009,0x0000036a,0x00000069,0x00050050,0x0000000a,0x0000036b,0x00000369,0x0000036a, + 0x0005008e,0x0000000a,0x0000036c,0x0000036b,0x00000368,0x0006000c,0x0000000a,0x0000036d, + 0x00000001,0x00000001,0x0000036c,0x0004003d,0x0000000a,0x0000036e,0x00000067,0x0008000c, + 0x0000000a,0x0000036f,0x00000001,0x00000032,0x00000367,0x0000036d,0x0000036e,0x0003003e, + 0x00000365,0x0000036f,0x0004003d,0x0000000a,0x00000370,0x00000365,0x0008000c,0x0000000a, + 0x00000371,0x00000001,0x00000032,0x0000016e,0x00000370,0x00000172,0x0003003e,0x00000365, + 0x00000371,0x0004003d,0x00000009,0x00000372,0x0000006a,0x00050041,0x00000036,0x00000373, + 0x00000365,0x0000008d,0x0004003d,0x00000009,0x00000374,0x00000373,0x0008000c,0x00000009, + 0x00000375,0x00000001,0x00000032,0x00000178,0x00000372,0x00000374,0x00050041,0x00000036, + 0x00000376,0x00000365,0x0000008d,0x0003003e,0x00000376,0x00000375,0x0004003d,0x00000027, + 0x00000377,0x00000066,0x0004003d,0x0000000a,0x00000378,0x00000365,0x00070058,0x00000012, + 0x00000379,0x00000377,0x00000378,0x00000002,0x0000011a,0x0007004f,0x0000000a,0x0000037a, + 0x00000379,0x00000379,0x00000000,0x00000001,0x000200fe,0x0000037a,0x00010038,0x00050036, + 0x00000002,0x00000072,0x00000000,0x0000006d,0x00030037,0x00000028,0x0000006e,0x00030037, + 0x0000000b,0x0000006f,0x00030037,0x00000021,0x00000070,0x00030037,0x0000000b,0x00000071, + 0x000200f8,0x00000073,0x0004003b,0x0000000b,0x0000037d,0x00000007,0x0004003b,0x0000000b, + 0x00000382,0x00000007,0x0004003b,0x0000000b,0x0000038e,0x00000007,0x0004003d,0x0000000a, + 0x0000037e,0x00000071,0x0004003d,0x0000000a,0x0000037f,0x00000071,0x0007004f,0x0000000a, + 0x00000380,0x0000037f,0x0000037f,0x00000001,0x00000000,0x0007000c,0x0000000a,0x00000381, + 0x00000001,0x00000030,0x0000037e,0x00000380,0x0003003e,0x0000037d,0x00000381,0x0004003d, + 0x0000000a,0x00000384,0x0000037d,0x0005008e,0x0000000a,0x00000385,0x00000384,0x00000383, + 0x0003003e,0x00000382,0x00000385,0x00050041,0x00000036,0x00000386,0x0000037d,0x00000084, + 0x0004003d,0x00000009,0x00000387,0x00000386,0x00050041,0x00000036,0x00000388,0x0000037d, + 0x0000008d,0x0004003d,0x00000009,0x00000389,0x00000388,0x00050081,0x00000009,0x0000038a, + 0x00000387,0x00000389,0x0004003d,0x0000000a,0x0000038b,0x00000382,0x00050050,0x0000000a, + 0x0000038c,0x0000038a,0x0000038a,0x00050088,0x0000000a,0x0000038d,0x0000038b,0x0000038c, + 0x0003003e,0x00000382,0x0000038d,0x0003003e,0x0000038e,0x00000219,0x00050041,0x00000036, + 0x0000038f,0x00000382,0x00000084,0x0004003d,0x00000009,0x00000390,0x0000038f,0x0004003d, + 0x00000027,0x00000391,0x0000006e,0x0004003d,0x00000012,0x00000392,0x00000070,0x0007004f, + 0x0000000a,0x00000393,0x00000392,0x00000392,0x00000000,0x00000001,0x00080058,0x00000012, + 0x00000395,0x00000391,0x00000393,0x0000000a,0x0000011a,0x00000394,0x00050051,0x00000009, + 0x00000396,0x00000395,0x00000000,0x00050085,0x00000009,0x00000397,0x00000390,0x00000396, + 0x00050041,0x00000036,0x00000398,0x0000038e,0x00000084,0x0004003d,0x00000009,0x00000399, + 0x00000398,0x00050083,0x00000009,0x0000039a,0x00000399,0x00000397,0x00050041,0x00000036, + 0x0000039b,0x0000038e,0x00000084,0x0003003e,0x0000039b,0x0000039a,0x00050041,0x00000036, + 0x0000039c,0x00000382,0x0000008d,0x0004003d,0x00000009,0x0000039d,0x0000039c,0x0004003d, + 0x00000027,0x0000039e,0x0000006e,0x0004003d,0x00000012,0x0000039f,0x00000070,0x0007004f, + 0x0000000a,0x000003a0,0x0000039f,0x0000039f,0x00000002,0x00000003,0x00080058,0x00000012, + 0x000003a2,0x0000039e,0x000003a0,0x0000000a,0x0000011a,0x000003a1,0x00050051,0x00000009, + 0x000003a3,0x000003a2,0x00000000,0x00050085,0x00000009,0x000003a4,0x0000039d,0x000003a3, + 0x00050041,0x00000036,0x000003a5,0x0000038e,0x00000084,0x0004003d,0x00000009,0x000003a6, + 0x000003a5,0x00050083,0x00000009,0x000003a7,0x000003a6,0x000003a4,0x00050041,0x00000036, + 0x000003a8,0x0000038e,0x00000084,0x0003003e,0x000003a8,0x000003a7,0x00050041,0x00000036, + 0x000003a9,0x00000382,0x00000084,0x0004003d,0x00000009,0x000003aa,0x000003a9,0x0004003d, + 0x00000027,0x000003ab,0x0000006e,0x0004003d,0x00000012,0x000003ac,0x00000070,0x0007004f, + 0x0000000a,0x000003ad,0x000003ac,0x000003ac,0x00000000,0x00000001,0x00080058,0x00000012, + 0x000003b0,0x000003ab,0x000003ad,0x0000000a,0x0000011a,0x000003af,0x00050051,0x00000009, + 0x000003b1,0x000003b0,0x00000000,0x00050085,0x00000009,0x000003b2,0x000003aa,0x000003b1, + 0x00050041,0x00000036,0x000003b3,0x0000038e,0x0000008d,0x0004003d,0x00000009,0x000003b4, + 0x000003b3,0x00050083,0x00000009,0x000003b5,0x000003b4,0x000003b2,0x00050041,0x00000036, + 0x000003b6,0x0000038e,0x0000008d,0x0003003e,0x000003b6,0x000003b5,0x00050041,0x00000036, + 0x000003b7,0x00000382,0x0000008d,0x0004003d,0x00000009,0x000003b8,0x000003b7,0x0004003d, + 0x00000027,0x000003b9,0x0000006e,0x0004003d,0x00000012,0x000003ba,0x00000070,0x0007004f, + 0x0000000a,0x000003bb,0x000003ba,0x000003ba,0x00000002,0x00000003,0x00080058,0x00000012, + 0x000003bd,0x000003b9,0x000003bb,0x0000000a,0x0000011a,0x000003bc,0x00050051,0x00000009, + 0x000003be,0x000003bd,0x00000000,0x00050085,0x00000009,0x000003bf,0x000003b8,0x000003be, + 0x00050041,0x00000036,0x000003c0,0x0000038e,0x0000008d,0x0004003d,0x00000009,0x000003c1, + 0x000003c0,0x00050083,0x00000009,0x000003c2,0x000003c1,0x000003bf,0x00050041,0x00000036, + 0x000003c3,0x0000038e,0x0000008d,0x0003003e,0x000003c3,0x000003c2,0x0004003d,0x0000000a, + 0x000003c4,0x0000038e,0x00050050,0x0000000a,0x000003c5,0x0000011a,0x0000011a,0x00050050, + 0x0000000a,0x000003c6,0x000000ec,0x000000ec,0x0008000c,0x0000000a,0x000003c7,0x00000001, + 0x0000002b,0x000003c4,0x000003c5,0x000003c6,0x0004003d,0x0000000a,0x000003c8,0x0000006f, + 0x00050085,0x0000000a,0x000003c9,0x000003c8,0x000003c7,0x0003003e,0x0000006f,0x000003c9, + 0x000100fd,0x00010038,0x00050036,0x00000002,0x00000078,0x00000000,0x0000006d,0x00030037, + 0x00000028,0x00000074,0x00030037,0x0000000b,0x00000075,0x00030037,0x00000021,0x00000076, + 0x00030037,0x0000000b,0x00000077,0x000200f8,0x00000079,0x0004003b,0x0000000b,0x000003ca, + 0x00000007,0x0004003b,0x0000000b,0x000003cf,0x00000007,0x0004003b,0x0000000b,0x000003da, + 0x00000007,0x0004003d,0x0000000a,0x000003cb,0x00000077,0x0004003d,0x0000000a,0x000003cc, + 0x00000077,0x0007004f,0x0000000a,0x000003cd,0x000003cc,0x000003cc,0x00000001,0x00000000, + 0x0007000c,0x0000000a,0x000003ce,0x00000001,0x00000030,0x000003cb,0x000003cd,0x0003003e, + 0x000003ca,0x000003ce,0x0004003d,0x0000000a,0x000003d0,0x000003ca,0x0005008e,0x0000000a, + 0x000003d1,0x000003d0,0x00000383,0x0003003e,0x000003cf,0x000003d1,0x00050041,0x00000036, + 0x000003d2,0x000003ca,0x00000084,0x0004003d,0x00000009,0x000003d3,0x000003d2,0x00050041, + 0x00000036,0x000003d4,0x000003ca,0x0000008d,0x0004003d,0x00000009,0x000003d5,0x000003d4, + 0x00050081,0x00000009,0x000003d6,0x000003d3,0x000003d5,0x0004003d,0x0000000a,0x000003d7, + 0x000003cf,0x00050050,0x0000000a,0x000003d8,0x000003d6,0x000003d6,0x00050088,0x0000000a, + 0x000003d9,0x000003d7,0x000003d8,0x0003003e,0x000003cf,0x000003d9,0x0003003e,0x000003da, + 0x00000219,0x00050041,0x00000036,0x000003db,0x000003cf,0x00000084,0x0004003d,0x00000009, + 0x000003dc,0x000003db,0x0004003d,0x00000027,0x000003dd,0x00000074,0x0004003d,0x00000012, + 0x000003de,0x00000076,0x0007004f,0x0000000a,0x000003df,0x000003de,0x000003de,0x00000000, + 0x00000001,0x00080058,0x00000012,0x000003e0,0x000003dd,0x000003df,0x0000000a,0x0000011a, + 0x000001de,0x00050051,0x00000009,0x000003e1,0x000003e0,0x00000001,0x00050085,0x00000009, + 0x000003e2,0x000003dc,0x000003e1,0x00050041,0x00000036,0x000003e3,0x000003da,0x00000084, + 0x0004003d,0x00000009,0x000003e4,0x000003e3,0x00050083,0x00000009,0x000003e5,0x000003e4, + 0x000003e2,0x00050041,0x00000036,0x000003e6,0x000003da,0x00000084,0x0003003e,0x000003e6, + 0x000003e5,0x00050041,0x00000036,0x000003e7,0x000003cf,0x0000008d,0x0004003d,0x00000009, + 0x000003e8,0x000003e7,0x0004003d,0x00000027,0x000003e9,0x00000074,0x0004003d,0x00000012, + 0x000003ea,0x00000076,0x0007004f,0x0000000a,0x000003eb,0x000003ea,0x000003ea,0x00000002, + 0x00000003,0x00080058,0x00000012,0x000003ec,0x000003e9,0x000003eb,0x0000000a,0x0000011a, + 0x000003a1,0x00050051,0x00000009,0x000003ed,0x000003ec,0x00000001,0x00050085,0x00000009, + 0x000003ee,0x000003e8,0x000003ed,0x00050041,0x00000036,0x000003ef,0x000003da,0x00000084, + 0x0004003d,0x00000009,0x000003f0,0x000003ef,0x00050083,0x00000009,0x000003f1,0x000003f0, + 0x000003ee,0x00050041,0x00000036,0x000003f2,0x000003da,0x00000084,0x0003003e,0x000003f2, + 0x000003f1,0x00050041,0x00000036,0x000003f3,0x000003cf,0x00000084,0x0004003d,0x00000009, + 0x000003f4,0x000003f3,0x0004003d,0x00000027,0x000003f5,0x00000074,0x0004003d,0x00000012, + 0x000003f6,0x00000076,0x0007004f,0x0000000a,0x000003f7,0x000003f6,0x000003f6,0x00000000, + 0x00000001,0x00080058,0x00000012,0x000003f9,0x000003f5,0x000003f7,0x0000000a,0x0000011a, + 0x000003f8,0x00050051,0x00000009,0x000003fa,0x000003f9,0x00000001,0x00050085,0x00000009, + 0x000003fb,0x000003f4,0x000003fa,0x00050041,0x00000036,0x000003fc,0x000003da,0x0000008d, + 0x0004003d,0x00000009,0x000003fd,0x000003fc,0x00050083,0x00000009,0x000003fe,0x000003fd, + 0x000003fb,0x00050041,0x00000036,0x000003ff,0x000003da,0x0000008d,0x0003003e,0x000003ff, + 0x000003fe,0x00050041,0x00000036,0x00000400,0x000003cf,0x0000008d,0x0004003d,0x00000009, + 0x00000401,0x00000400,0x0004003d,0x00000027,0x00000402,0x00000074,0x0004003d,0x00000012, + 0x00000403,0x00000076,0x0007004f,0x0000000a,0x00000404,0x00000403,0x00000403,0x00000002, + 0x00000003,0x00080058,0x00000012,0x00000406,0x00000402,0x00000404,0x0000000a,0x0000011a, + 0x00000405,0x00050051,0x00000009,0x00000407,0x00000406,0x00000001,0x00050085,0x00000009, + 0x00000408,0x00000401,0x00000407,0x00050041,0x00000036,0x00000409,0x000003da,0x0000008d, + 0x0004003d,0x00000009,0x0000040a,0x00000409,0x00050083,0x00000009,0x0000040b,0x0000040a, + 0x00000408,0x00050041,0x00000036,0x0000040c,0x000003da,0x0000008d,0x0003003e,0x0000040c, + 0x0000040b,0x0004003d,0x0000000a,0x0000040d,0x000003da,0x00050050,0x0000000a,0x0000040e, + 0x0000011a,0x0000011a,0x00050050,0x0000000a,0x0000040f,0x000000ec,0x000000ec,0x0008000c, + 0x0000000a,0x00000410,0x00000001,0x0000002b,0x0000040d,0x0000040e,0x0000040f,0x0004003d, + 0x0000000a,0x00000411,0x00000075,0x00050085,0x0000000a,0x00000412,0x00000411,0x00000410, + 0x0003003e,0x00000075,0x00000412,0x000100fd,0x00010038,0x00050036,0x00000012,0x00000082, + 0x00000000,0x0000007a,0x00030037,0x0000000b,0x0000007b,0x00030037,0x0000000b,0x0000007c, + 0x00030037,0x00000016,0x0000007d,0x00030037,0x00000028,0x0000007e,0x00030037,0x00000028, + 0x0000007f,0x00030037,0x00000028,0x00000080,0x00030037,0x00000021,0x00000081,0x000200f8, + 0x00000083,0x0004003b,0x00000021,0x00000413,0x00000007,0x0004003b,0x0000000b,0x00000415, + 0x00000007,0x0004003b,0x0000000b,0x0000041f,0x00000007,0x0004003b,0x0000000b,0x00000421, + 0x00000007,0x0004003b,0x00000021,0x00000423,0x00000007,0x0004003b,0x000000f1,0x00000432, + 0x00000007,0x0004003b,0x0000000b,0x00000433,0x00000007,0x0004003b,0x00000036,0x00000437, + 0x00000007,0x0004003b,0x0000000b,0x0000043f,0x00000007,0x0004003b,0x00000036,0x00000443, + 0x00000007,0x0004003b,0x0000000b,0x00000449,0x00000007,0x0004003b,0x00000036,0x0000044d, + 0x00000007,0x0004003b,0x0000000b,0x0000045f,0x00000007,0x0004003b,0x00000036,0x00000462, + 0x00000007,0x0004003b,0x0000000b,0x00000468,0x00000007,0x0004003b,0x00000036,0x0000046a, + 0x00000007,0x0004003b,0x00000036,0x0000046c,0x00000007,0x0004003b,0x00000036,0x0000046e, + 0x00000007,0x0004003b,0x0000000b,0x00000479,0x00000007,0x0004003b,0x00000021,0x0000047c, + 0x00000007,0x0004003b,0x0000000b,0x0000047f,0x00000007,0x0004003b,0x000000f1,0x0000048e, + 0x00000007,0x0004003b,0x0000000b,0x0000048f,0x00000007,0x0004003b,0x00000036,0x00000493, + 0x00000007,0x0004003b,0x0000000b,0x0000049b,0x00000007,0x0004003b,0x00000036,0x0000049f, + 0x00000007,0x0004003b,0x0000000b,0x000004a5,0x00000007,0x0004003b,0x00000036,0x000004a9, + 0x00000007,0x0004003b,0x0000000b,0x000004bb,0x00000007,0x0004003b,0x00000036,0x000004be, + 0x00000007,0x0004003b,0x0000000b,0x000004c4,0x00000007,0x0004003b,0x00000036,0x000004c6, + 0x00000007,0x0004003b,0x00000036,0x000004c8,0x00000007,0x0004003b,0x00000036,0x000004ca, + 0x00000007,0x0004003b,0x0000000b,0x000004d5,0x00000007,0x0004003b,0x00000021,0x000004d8, + 0x00000007,0x0004003b,0x0000000b,0x000004db,0x00000007,0x0003003e,0x00000413,0x00000414, + 0x0004003d,0x00000027,0x00000416,0x0000007e,0x0004003d,0x0000000a,0x00000417,0x0000007b, + 0x00050057,0x00000012,0x00000418,0x00000416,0x00000417,0x0007004f,0x0000000a,0x00000419, + 0x00000418,0x00000418,0x00000000,0x00000001,0x0003003e,0x00000415,0x00000419,0x00050041, + 0x00000036,0x0000041a,0x00000415,0x0000008d,0x0004003d,0x00000009,0x0000041b,0x0000041a, + 0x000500ba,0x00000006,0x0000041c,0x0000041b,0x0000011a,0x000300f7,0x0000041e,0x00000000, + 0x000400fa,0x0000041c,0x0000041d,0x0000041e,0x000200f8,0x0000041d,0x0004003d,0x0000000a, + 0x00000420,0x0000007b,0x0003003e,0x0000041f,0x00000420,0x0004003d,0x0000000a,0x00000422, + 0x00000415,0x0003003e,0x00000421,0x00000422,0x0004003d,0x00000012,0x00000424,0x00000081, + 0x0003003e,0x00000423,0x00000424,0x00090039,0x0000000a,0x00000425,0x00000044,0x0000007e, + 0x0000007f,0x0000041f,0x00000421,0x00000423,0x00050041,0x00000036,0x00000426,0x00000413, + 0x00000084,0x00050051,0x00000009,0x00000427,0x00000425,0x00000000,0x0003003e,0x00000426, + 0x00000427,0x00050041,0x00000036,0x00000428,0x00000413,0x0000008d,0x00050051,0x00000009, + 0x00000429,0x00000425,0x00000001,0x0003003e,0x00000428,0x00000429,0x00050041,0x00000036, + 0x0000042a,0x00000413,0x00000084,0x0004003d,0x00000009,0x0000042b,0x0000042a,0x00050041, + 0x00000036,0x0000042c,0x00000413,0x0000008d,0x0004003d,0x00000009,0x0000042d,0x0000042c, + 0x0004007f,0x00000009,0x0000042e,0x0000042d,0x000500b4,0x00000006,0x0000042f,0x0000042b, + 0x0000042e,0x000300f7,0x00000431,0x00000000,0x000400fa,0x0000042f,0x00000430,0x00000487, + 0x000200f8,0x00000430,0x00050041,0x00000021,0x00000434,0x0000007d,0x000000a0,0x0004003d, + 0x00000012,0x00000435,0x00000434,0x0007004f,0x0000000a,0x00000436,0x00000435,0x00000435, + 0x00000000,0x00000001,0x0003003e,0x00000433,0x00000436,0x00060041,0x00000036,0x00000438, + 0x0000007d,0x000000b4,0x00000084,0x0004003d,0x00000009,0x00000439,0x00000438,0x0003003e, + 0x00000437,0x00000439,0x00080039,0x00000009,0x0000043a,0x00000051,0x0000007e,0x00000080, + 0x00000433,0x00000437,0x00050041,0x00000036,0x0000043b,0x00000432,0x00000084,0x0003003e, + 0x0000043b,0x0000043a,0x00060041,0x00000036,0x0000043c,0x0000007d,0x0000009a,0x0000008d, + 0x0004003d,0x00000009,0x0000043d,0x0000043c,0x00050041,0x00000036,0x0000043e,0x00000432, + 0x0000008d,0x0003003e,0x0000043e,0x0000043d,0x00050041,0x00000036,0x00000440,0x00000432, + 0x00000084,0x0004003d,0x00000009,0x00000441,0x00000440,0x00050041,0x00000036,0x00000442, + 0x0000043f,0x00000084,0x0003003e,0x00000442,0x00000441,0x0004003d,0x00000027,0x00000444, + 0x0000007e,0x0004003d,0x000000f0,0x00000445,0x00000432,0x0007004f,0x0000000a,0x00000446, + 0x00000445,0x00000445,0x00000000,0x00000001,0x00070058,0x00000012,0x00000447,0x00000444, + 0x00000446,0x00000002,0x0000011a,0x00050051,0x00000009,0x00000448,0x00000447,0x00000000, + 0x0003003e,0x00000443,0x00000448,0x00050041,0x00000021,0x0000044a,0x0000007d,0x000000a0, + 0x0004003d,0x00000012,0x0000044b,0x0000044a,0x0007004f,0x0000000a,0x0000044c,0x0000044b, + 0x0000044b,0x00000002,0x00000003,0x0003003e,0x00000449,0x0000044c,0x00060041,0x00000036, + 0x0000044e,0x0000007d,0x000000b4,0x0000008d,0x0004003d,0x00000009,0x0000044f,0x0000044e, + 0x0003003e,0x0000044d,0x0000044f,0x00080039,0x00000009,0x00000450,0x00000057,0x0000007e, + 0x00000080,0x00000449,0x0000044d,0x00050041,0x00000036,0x00000451,0x00000432,0x000000e2, + 0x0003003e,0x00000451,0x00000450,0x00050041,0x00000036,0x00000452,0x00000432,0x000000e2, + 0x0004003d,0x00000009,0x00000453,0x00000452,0x00050041,0x00000036,0x00000454,0x0000043f, + 0x0000008d,0x0003003e,0x00000454,0x00000453,0x00050041,0x0000009b,0x00000455,0x00000098, + 0x0000009a,0x0004003d,0x00000012,0x00000456,0x00000455,0x0007004f,0x0000000a,0x00000457, + 0x00000456,0x00000456,0x00000002,0x00000002,0x0004003d,0x0000000a,0x00000458,0x0000043f, + 0x0004003d,0x0000000a,0x00000459,0x0000007c,0x0007004f,0x0000000a,0x0000045a,0x00000459, + 0x00000459,0x00000000,0x00000000,0x0004007f,0x0000000a,0x0000045b,0x0000045a,0x0008000c, + 0x0000000a,0x0000045c,0x00000001,0x00000032,0x00000457,0x00000458,0x0000045b,0x0006000c, + 0x0000000a,0x0000045d,0x00000001,0x00000001,0x0000045c,0x0006000c,0x0000000a,0x0000045e, + 0x00000001,0x00000004,0x0000045d,0x0003003e,0x0000043f,0x0000045e,0x0004003d,0x0000000a, + 0x00000460,0x0000043f,0x0006000c,0x0000000a,0x00000461,0x00000001,0x0000001f,0x00000460, + 0x0003003e,0x0000045f,0x00000461,0x0004003d,0x00000027,0x00000463,0x0000007e,0x0004003d, + 0x000000f0,0x00000464,0x00000432,0x0007004f,0x0000000a,0x00000465,0x00000464,0x00000464, + 0x00000002,0x00000001,0x00080058,0x00000012,0x00000466,0x00000463,0x00000465,0x0000000a, + 0x0000011a,0x000001de,0x00050051,0x00000009,0x00000467,0x00000466,0x00000000,0x0003003e, + 0x00000462,0x00000467,0x0004003d,0x0000000a,0x00000469,0x0000045f,0x0003003e,0x00000468, + 0x00000469,0x0004003d,0x00000009,0x0000046b,0x00000443,0x0003003e,0x0000046a,0x0000046b, + 0x0004003d,0x00000009,0x0000046d,0x00000462,0x0003003e,0x0000046c,0x0000046d,0x00050041, + 0x00000036,0x0000046f,0x00000081,0x0000008d,0x0004003d,0x00000009,0x00000470,0x0000046f, + 0x0003003e,0x0000046e,0x00000470,0x00090039,0x0000000a,0x00000471,0x0000006b,0x0000007f, + 0x00000468,0x0000046a,0x0000046c,0x0000046e,0x00050041,0x00000036,0x00000472,0x00000413, + 0x00000084,0x00050051,0x00000009,0x00000473,0x00000471,0x00000000,0x0003003e,0x00000472, + 0x00000473,0x00050041,0x00000036,0x00000474,0x00000413,0x0000008d,0x00050051,0x00000009, + 0x00000475,0x00000471,0x00000001,0x0003003e,0x00000474,0x00000475,0x00050041,0x00000036, + 0x00000476,0x0000007b,0x0000008d,0x0004003d,0x00000009,0x00000477,0x00000476,0x00050041, + 0x00000036,0x00000478,0x00000432,0x0000008d,0x0003003e,0x00000478,0x00000477,0x0004003d, + 0x00000012,0x0000047a,0x00000413,0x0007004f,0x0000000a,0x0000047b,0x0000047a,0x0000047a, + 0x00000000,0x00000001,0x0003003e,0x00000479,0x0000047b,0x0004003d,0x000000f0,0x0000047d, + 0x00000432,0x0009004f,0x00000012,0x0000047e,0x0000047d,0x0000047d,0x00000000,0x00000001, + 0x00000002,0x00000001,0x0003003e,0x0000047c,0x0000047e,0x0004003d,0x0000000a,0x00000480, + 0x0000043f,0x0003003e,0x0000047f,0x00000480,0x00080039,0x00000002,0x00000481,0x00000072, + 0x0000007e,0x00000479,0x0000047c,0x0000047f,0x0004003d,0x0000000a,0x00000482,0x00000479, + 0x00050041,0x00000036,0x00000483,0x00000413,0x00000084,0x00050051,0x00000009,0x00000484, + 0x00000482,0x00000000,0x0003003e,0x00000483,0x00000484,0x00050041,0x00000036,0x00000485, + 0x00000413,0x0000008d,0x00050051,0x00000009,0x00000486,0x00000482,0x00000001,0x0003003e, + 0x00000485,0x00000486,0x000200f9,0x00000431,0x000200f8,0x00000487,0x00050041,0x00000036, + 0x00000488,0x00000415,0x00000084,0x0003003e,0x00000488,0x0000011a,0x000200f9,0x00000431, + 0x000200f8,0x00000431,0x000200f9,0x0000041e,0x000200f8,0x0000041e,0x00050041,0x00000036, + 0x00000489,0x00000415,0x00000084,0x0004003d,0x00000009,0x0000048a,0x00000489,0x000500ba, + 0x00000006,0x0000048b,0x0000048a,0x0000011a,0x000300f7,0x0000048d,0x00000000,0x000400fa, + 0x0000048b,0x0000048c,0x0000048d,0x000200f8,0x0000048c,0x00050041,0x00000021,0x00000490, + 0x0000007d,0x0000009a,0x0004003d,0x00000012,0x00000491,0x00000490,0x0007004f,0x0000000a, + 0x00000492,0x00000491,0x00000491,0x00000000,0x00000001,0x0003003e,0x0000048f,0x00000492, + 0x00060041,0x00000036,0x00000494,0x0000007d,0x000000b4,0x000000e2,0x0004003d,0x00000009, + 0x00000495,0x00000494,0x0003003e,0x00000493,0x00000495,0x00080039,0x00000009,0x00000496, + 0x0000005d,0x0000007e,0x00000080,0x0000048f,0x00000493,0x00050041,0x00000036,0x00000497, + 0x0000048e,0x0000008d,0x0003003e,0x00000497,0x00000496,0x00060041,0x00000036,0x00000498, + 0x0000007d,0x000000a0,0x00000084,0x0004003d,0x00000009,0x00000499,0x00000498,0x00050041, + 0x00000036,0x0000049a,0x0000048e,0x00000084,0x0003003e,0x0000049a,0x00000499,0x00050041, + 0x00000036,0x0000049c,0x0000048e,0x0000008d,0x0004003d,0x00000009,0x0000049d,0x0000049c, + 0x00050041,0x00000036,0x0000049e,0x0000049b,0x00000084,0x0003003e,0x0000049e,0x0000049d, + 0x0004003d,0x00000027,0x000004a0,0x0000007e,0x0004003d,0x000000f0,0x000004a1,0x0000048e, + 0x0007004f,0x0000000a,0x000004a2,0x000004a1,0x000004a1,0x00000000,0x00000001,0x00070058, + 0x00000012,0x000004a3,0x000004a0,0x000004a2,0x00000002,0x0000011a,0x00050051,0x00000009, + 0x000004a4,0x000004a3,0x00000001,0x0003003e,0x0000049f,0x000004a4,0x00050041,0x00000021, + 0x000004a6,0x0000007d,0x0000009a,0x0004003d,0x00000012,0x000004a7,0x000004a6,0x0007004f, + 0x0000000a,0x000004a8,0x000004a7,0x000004a7,0x00000002,0x00000003,0x0003003e,0x000004a5, + 0x000004a8,0x00060041,0x00000036,0x000004aa,0x0000007d,0x000000b4,0x00000014,0x0004003d, + 0x00000009,0x000004ab,0x000004aa,0x0003003e,0x000004a9,0x000004ab,0x00080039,0x00000009, + 0x000004ac,0x00000063,0x0000007e,0x00000080,0x000004a5,0x000004a9,0x00050041,0x00000036, + 0x000004ad,0x0000048e,0x000000e2,0x0003003e,0x000004ad,0x000004ac,0x00050041,0x00000036, + 0x000004ae,0x0000048e,0x000000e2,0x0004003d,0x00000009,0x000004af,0x000004ae,0x00050041, + 0x00000036,0x000004b0,0x0000049b,0x0000008d,0x0003003e,0x000004b0,0x000004af,0x00050041, + 0x0000009b,0x000004b1,0x00000098,0x0000009a,0x0004003d,0x00000012,0x000004b2,0x000004b1, + 0x0007004f,0x0000000a,0x000004b3,0x000004b2,0x000004b2,0x00000003,0x00000003,0x0004003d, + 0x0000000a,0x000004b4,0x0000049b,0x0004003d,0x0000000a,0x000004b5,0x0000007c,0x0007004f, + 0x0000000a,0x000004b6,0x000004b5,0x000004b5,0x00000001,0x00000001,0x0004007f,0x0000000a, + 0x000004b7,0x000004b6,0x0008000c,0x0000000a,0x000004b8,0x00000001,0x00000032,0x000004b3, + 0x000004b4,0x000004b7,0x0006000c,0x0000000a,0x000004b9,0x00000001,0x00000001,0x000004b8, + 0x0006000c,0x0000000a,0x000004ba,0x00000001,0x00000004,0x000004b9,0x0003003e,0x0000049b, + 0x000004ba,0x0004003d,0x0000000a,0x000004bc,0x0000049b,0x0006000c,0x0000000a,0x000004bd, + 0x00000001,0x0000001f,0x000004bc,0x0003003e,0x000004bb,0x000004bd,0x0004003d,0x00000027, + 0x000004bf,0x0000007e,0x0004003d,0x000000f0,0x000004c0,0x0000048e,0x0007004f,0x0000000a, + 0x000004c1,0x000004c0,0x000004c0,0x00000000,0x00000002,0x00080058,0x00000012,0x000004c2, + 0x000004bf,0x000004c1,0x0000000a,0x0000011a,0x00000394,0x00050051,0x00000009,0x000004c3, + 0x000004c2,0x00000001,0x0003003e,0x000004be,0x000004c3,0x0004003d,0x0000000a,0x000004c5, + 0x000004bb,0x0003003e,0x000004c4,0x000004c5,0x0004003d,0x00000009,0x000004c7,0x0000049f, + 0x0003003e,0x000004c6,0x000004c7,0x0004003d,0x00000009,0x000004c9,0x000004be,0x0003003e, + 0x000004c8,0x000004c9,0x00050041,0x00000036,0x000004cb,0x00000081,0x00000084,0x0004003d, + 0x00000009,0x000004cc,0x000004cb,0x0003003e,0x000004ca,0x000004cc,0x00090039,0x0000000a, + 0x000004cd,0x0000006b,0x0000007f,0x000004c4,0x000004c6,0x000004c8,0x000004ca,0x00050041, + 0x00000036,0x000004ce,0x00000413,0x000000e2,0x00050051,0x00000009,0x000004cf,0x000004cd, + 0x00000000,0x0003003e,0x000004ce,0x000004cf,0x00050041,0x00000036,0x000004d0,0x00000413, + 0x00000014,0x00050051,0x00000009,0x000004d1,0x000004cd,0x00000001,0x0003003e,0x000004d0, + 0x000004d1,0x00050041,0x00000036,0x000004d2,0x0000007b,0x00000084,0x0004003d,0x00000009, + 0x000004d3,0x000004d2,0x00050041,0x00000036,0x000004d4,0x0000048e,0x00000084,0x0003003e, + 0x000004d4,0x000004d3,0x0004003d,0x00000012,0x000004d6,0x00000413,0x0007004f,0x0000000a, + 0x000004d7,0x000004d6,0x000004d6,0x00000002,0x00000003,0x0003003e,0x000004d5,0x000004d7, + 0x0004003d,0x000000f0,0x000004d9,0x0000048e,0x0009004f,0x00000012,0x000004da,0x000004d9, + 0x000004d9,0x00000000,0x00000001,0x00000000,0x00000002,0x0003003e,0x000004d8,0x000004da, + 0x0004003d,0x0000000a,0x000004dc,0x0000049b,0x0003003e,0x000004db,0x000004dc,0x00080039, + 0x00000002,0x000004dd,0x00000078,0x0000007e,0x000004d5,0x000004d8,0x000004db,0x0004003d, + 0x0000000a,0x000004de,0x000004d5,0x00050041,0x00000036,0x000004df,0x00000413,0x000000e2, + 0x00050051,0x00000009,0x000004e0,0x000004de,0x00000000,0x0003003e,0x000004df,0x000004e0, + 0x00050041,0x00000036,0x000004e1,0x00000413,0x00000014,0x00050051,0x00000009,0x000004e2, + 0x000004de,0x00000001,0x0003003e,0x000004e1,0x000004e2,0x000200f9,0x0000048d,0x000200f8, + 0x0000048d,0x0004003d,0x00000012,0x000004e3,0x00000413,0x000200fe,0x000004e3,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 03f33894cb..f17591cb16 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; @@ -333,6 +343,7 @@ volatile int g_hide_shell; volatile int g_zero_copy; static int g_zero_copy_paused; +static int g_mirror_capture; extern volatile int g_display_buffer_driver; extern void droiddeck_on_overlay_planes(int planes); static int g_overlay_planes_told = -1; @@ -826,6 +837,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)) { @@ -841,18 +853,21 @@ 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; @@ -865,6 +880,7 @@ struct surface_state { 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; @@ -873,6 +889,8 @@ static void on_state_buffer_destroyed(struct wl_listener *l, void *data) { 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) { @@ -1185,6 +1203,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; @@ -1450,6 +1469,7 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) { 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(); @@ -1461,6 +1481,8 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) { 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); @@ -1473,6 +1495,7 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) { 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) { @@ -1537,6 +1560,7 @@ static void settle_unwaited(void) { } 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); @@ -1548,6 +1572,8 @@ static void surface_state_merge(struct surface_state *older, struct surface_stat 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) { @@ -1699,6 +1725,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); @@ -1708,6 +1938,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; @@ -2272,6 +2503,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) { @@ -2391,17 +2685,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; @@ -2422,6 +2752,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) @@ -2430,16 +2810,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; } @@ -2542,7 +2962,7 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) { static int said = -1, said_tm = -1; static const char *said_why; const int tm = route != 0 && !droiddeck_color_output(); - if (route == said && tm == said_tm && (route != 1 || hs->why == said_why)) return; + if (route == said && tm == said_tm && (route < 1 || route > 2 || hs->why == said_why)) return; int was = said; said = route; said_why = hs->why; said_tm = tm; char name[160] = "the HDR game"; @@ -2559,6 +2979,10 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) { "BT2020_PQ", name, hs->why ? hs->why : "?", droiddeck_color_sdr_white()); break; case 2: + if (g_mirror_capture) { + droiddeck_log("color", "Mirror: %s is composed through the screen swapchain", name); + break; + } if (tm) droiddeck_log("color", "HDR with frame generation for %s, HDR output switched off: the scene is tone-mapped to " "SDR and presented through an SDR screen swapchain", name); @@ -2779,6 +3203,11 @@ static void render_scene(void) { const int cardboard = vkp_cardboard_active(); struct hdr_scene hs; int hdr_route = hdr_plan(&dl, w, h, fx_on, framegen, &hs); + /* Mirror's PixelCopy cannot see the separate game layer. Keep unimportable frames visible on top. */ + if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) { + hdr_route = 2; + hs.why = "Mirror needs the screen swapchain"; + } const char *hdr_copy = NULL; if (droiddeck_color_hdr_open()) { hdr_note_route(hdr_route, &hs); @@ -2844,16 +3273,16 @@ static void render_scene(void) { else if (rendered && how == 2) droiddeck_color_frame_shown(hs.color, DROIDDECK_HDR_TONEMAPPED, 0); else if (rendered) hdr_copy = "the HDR composition pass is unavailable on this driver"; } - if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on && + if (hdr_route == 0 && !g_mirror_capture && 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; tell_overlay_planes(); - const int fg_layer = framegen && hdr_route == 0 && framegen_fits_layer(); + const int fg_layer = framegen && !g_mirror_capture && hdr_route == 0 && framegen_fits_layer(); g_framegen_layer = fg_layer; - int li = (g_zero_copy && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1; + int li = (g_zero_copy && !g_mirror_capture && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1; int over = li >= 0 ? dl.n - 1 - li : 0; const int fx_blocks = (li >= 0 && fx_on && over > 0); if (fx_blocks) { li = -1; over = 0; } @@ -2882,7 +3311,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; @@ -2910,15 +3342,30 @@ 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 && !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(); - 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); + 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) { @@ -4375,11 +4822,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; @@ -4421,9 +4872,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); @@ -4543,6 +5012,12 @@ const char *droiddeck_client_name(struct wl_client *client) { return client_name struct wl_display *droiddeck_get_display(void) { return g_display; } void droiddeck_request_redraw(void) { schedule_render(); } +void droiddeck_set_mirror_capture(int on) { + if (g_mirror_capture == on) return; + g_mirror_capture = on; + schedule_render(); +} + struct wl_resource *droiddeck_ime_target(void) { struct surface *s; if (g_ime_click && g_ime_click->mapped) return g_ime_click->resource; @@ -4560,6 +5035,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; @@ -4569,6 +5049,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(); @@ -4577,7 +5058,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); } @@ -4778,6 +5260,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..e4ce7e201d 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, HOST_MIRROR_CAPTURE }; 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); } @@ -60,26 +91,179 @@ void droiddeck_host_text_delete(int before, int after) { void droiddeck_host_zero_copy(int on, int live) { host_post(HOST_ZERO_COPY, NULL, 0, on, live); } +void droiddeck_host_mirror_capture(int on) { + host_post(HOST_MIRROR_CAPTURE, NULL, 0, on, 0); +} 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); @@ -90,9 +274,25 @@ static int on_wake(int fd, uint32_t mask, void *data) { case HOST_ZERO_COPY: ahb_swapchain_set_mode(m->a, m->b); break; + case HOST_MIRROR_CAPTURE: + droiddeck_set_mirror_capture(m->a); + break; 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..bc67469eff 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h @@ -15,22 +15,36 @@ 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_mirror_capture(int on); +void droiddeck_set_mirror_capture(int on); 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..90423d2441 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 @@ -21,6 +22,7 @@ #include "smaa_edge_frag.h" #include "smaa_weights_frag.h" #include "smaa_blend_frag.h" +#include "smaa_tables.h" #include "toon_frag.h" #include "toon_color_frag.h" #include "hdr_frag.h" @@ -69,6 +71,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); } @@ -194,6 +197,7 @@ struct pc_sgsr { float ndc[4]; float vp[4]; float edge; }; struct pc_easu { float ndc[4]; uint32_t con0[4], con1[4], con2[4], con3[4]; float outW, outH; }; struct pc_rcas { float ndc[4]; uint32_t con[4]; float outW, outH; }; struct pc_res { float ndc[4]; float res[2]; float extra; float pad; }; +struct pc_smaa { float ndc[4]; float metrics[4]; }; struct pc_color { float ndc[4]; float b, c, g, s; }; struct pc_toon_color { float ndc[4]; float res[2]; float b, c, g, s; @@ -228,20 +232,33 @@ static VkDevice g_dev; static VkPhysicalDevice g_pd; static VkPhysicalDeviceMemoryProperties g_mp; static int g_ready; -static VkRenderPass g_rp, g_smaa_rp; +static VkRenderPass g_rp, g_smaa_edge_rp, g_smaa_weights_rp; static VkDescriptorSetLayout g_dsl; static VkPipelineLayout g_pl; 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, g_smaa_area, g_smaa_search; +static VkBuffer g_smaa_buf; +static VkDeviceMemory g_smaa_mem; /* 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 +266,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) { @@ -298,6 +315,7 @@ static void target_destroy(struct fx_target *t) { #define FX_TARGET_USAGE (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | \ VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT) #define FX_SCRATCH_USAGE (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT) +#define SMAA_EDGE_FORMAT VK_FORMAT_R8G8_UNORM static int target_ensure_format(struct fx_target *t, int w, int h, VkImageUsageFlags usage, const char *what, @@ -305,8 +323,9 @@ static int target_ensure_format(struct fx_target *t, int w, int h, if (t->img && t->w == w && t->h == h) return 0; target_destroy(t); VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, - .flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, .imageType = VK_IMAGE_TYPE_2D, - .format = format, .extent = {(uint32_t)w, (uint32_t)h, 1}, .mipLevels = 1, + /* SMAA's own images need no views in other formats, and the GPU is faster without the flag. */ + .flags = render_pass == g_rp ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0, + .imageType = VK_IMAGE_TYPE_2D, .format = format, .extent = {(uint32_t)w, (uint32_t)h, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL, .usage = usage, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED}; @@ -324,12 +343,16 @@ static int target_ensure_format(struct fx_target *t, int w, int h, (unsigned long long)req.size, (int)r); target_destroy(t); return -1; } - g_vk.BindImageMemory(g_dev, t->img, t->mem, 0); + r = g_vk.BindImageMemory(g_dev, t->img, t->mem, 0); + if (r != VK_SUCCESS) { + droiddeck_log("error", "effects: %s image %dx%d: vkBindImageMemory %d", what, w, h, (int)r); + target_destroy(t); return -1; + } if (!(t->view = make_view(t->img, format))) { target_destroy(t); return -1; } VkFramebufferCreateInfo fi = {.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, .renderPass = render_pass, .attachmentCount = 1, .pAttachments = &t->view, .width = (uint32_t)w, .height = (uint32_t)h, .layers = 1}; - if (g_vk.CreateFramebuffer(g_dev, &fi, NULL, &t->fb) != VK_SUCCESS) { target_destroy(t); return -1; } + if (render_pass && g_vk.CreateFramebuffer(g_dev, &fi, NULL, &t->fb) != VK_SUCCESS) { target_destroy(t); return -1; } if (!(t->ds = alloc_ds(t->view))) { target_destroy(t); return -1; } t->w = w; t->h = h; return 0; @@ -347,7 +370,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) { @@ -402,6 +471,22 @@ static VkPipeline post_pipeline_for_renderpass(VkShaderModule vert, return p; } +/* The mapped memory of a new host-visible buffer. On failure: NULL, and the caller frees what there is. */ +static void *host_buffer(VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer *buf, VkDeviceMemory *mem) { + VkBufferCreateInfo bci = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = size, + .usage = usage, .sharingMode = VK_SHARING_MODE_EXCLUSIVE}; + if (g_vk.CreateBuffer(g_dev, &bci, NULL, buf) != VK_SUCCESS) return NULL; + VkMemoryRequirements req; + g_vk.GetBufferMemoryRequirements(g_dev, *buf, &req); + int idx = memtype(req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + if (idx < 0) return NULL; + VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = req.size, .memoryTypeIndex = (uint32_t)idx}; + if (g_vk.AllocateMemory(g_dev, &mai, NULL, mem) != VK_SUCCESS) return NULL; + if (g_vk.BindBufferMemory(g_dev, *buf, *mem, 0) != VK_SUCCESS) return NULL; + void *p = NULL; + return g_vk.MapMemory(g_dev, *mem, 0, size, 0, &p) == VK_SUCCESS ? p : NULL; +} + static void coef_destroy(void) { if (g_coef_pool) g_vk.DestroyDescriptorPool(g_dev, g_coef_pool, NULL); /* frees g_coef_ds */ if (g_coef_buf) g_vk.DestroyBuffer(g_dev, g_coef_buf, NULL); @@ -423,18 +508,8 @@ static int coef_create(void) { VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 2, .pSetLayouts = sets, .pushConstantRangeCount = 1, .pPushConstantRanges = &pcr}; if (g_vk.CreatePipelineLayout(g_dev, &pli, NULL, &g_pl_nis) != VK_SUCCESS) goto fail; - VkBufferCreateInfo bci = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = 4096, - .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE}; - if (g_vk.CreateBuffer(g_dev, &bci, NULL, &g_coef_buf) != VK_SUCCESS) goto fail; - VkMemoryRequirements req; - g_vk.GetBufferMemoryRequirements(g_dev, g_coef_buf, &req); - int idx = memtype(req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - if (idx < 0) goto fail; - VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = req.size, .memoryTypeIndex = (uint32_t)idx}; - if (g_vk.AllocateMemory(g_dev, &mai, NULL, &g_coef_mem) != VK_SUCCESS) goto fail; - if (g_vk.BindBufferMemory(g_dev, g_coef_buf, g_coef_mem, 0) != VK_SUCCESS) goto fail; - void *p = NULL; - if (g_vk.MapMemory(g_dev, g_coef_mem, 0, 4096, 0, &p) != VK_SUCCESS || !p) goto fail; + void *p = host_buffer(4096, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, &g_coef_buf, &g_coef_mem); + if (!p) goto fail; memcpy(p, kNisCoefScale, sizeof(kNisCoefScale)); memcpy((char *)p + sizeof(kNisCoefScale), kNisCoefUsm, sizeof(kNisCoefUsm)); g_vk.UnmapMemory(g_dev, g_coef_mem); @@ -454,6 +529,29 @@ fail: return -1; } +static void smaa_tables_destroy(void) { + target_destroy(&g_smaa_area); target_destroy(&g_smaa_search); + if (g_smaa_buf) g_vk.DestroyBuffer(g_dev, g_smaa_buf, NULL); + if (g_smaa_mem) g_vk.FreeMemory(g_dev, g_smaa_mem, NULL); + g_smaa_buf = VK_NULL_HANDLE; g_smaa_mem = VK_NULL_HANDLE; +} + +static int smaa_tables_ensure(void) { + if (g_smaa_buf) return 0; + const VkImageUsageFlags usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + unsigned char *p = NULL; + if (target_ensure_format(&g_smaa_area, SMAA_AREA_W, SMAA_AREA_H, usage, "SMAA area table", + VK_FORMAT_R8G8_UNORM, VK_NULL_HANDLE) == 0 && + target_ensure_format(&g_smaa_search, SMAA_SEARCH_W, SMAA_SEARCH_H, usage, "SMAA search table", + VK_FORMAT_R8_UNORM, VK_NULL_HANDLE) == 0) + p = host_buffer(sizeof(kSmaaArea) + sizeof(kSmaaSearch), VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &g_smaa_buf, &g_smaa_mem); + if (!p) { smaa_tables_destroy(); return -1; } + memcpy(p, kSmaaArea, sizeof(kSmaaArea)); + memcpy(p + sizeof(kSmaaArea), kSmaaSearch, sizeof(kSmaaSearch)); + g_vk.UnmapMemory(g_dev, g_smaa_mem); + return 0; +} + /* nis_luma keeps luma in the target's alpha: only formats with at least 8 alpha bits (not the * 2-bit alpha of the 10-bit HDR composition format) can hold it. */ static int fx_alpha_holds_luma(VkFormat f) { @@ -473,19 +571,28 @@ 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); + smaa_tables_destroy(); 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); coef_destroy(); if (g_dsl) g_vk.DestroyDescriptorSetLayout(g_dev, g_dsl, NULL); if (g_sampler) g_vk.DestroySampler(g_dev, g_sampler, NULL); - if (g_smaa_rp) g_vk.DestroyRenderPass(g_dev, g_smaa_rp, NULL); + if (g_smaa_edge_rp) g_vk.DestroyRenderPass(g_dev, g_smaa_edge_rp, NULL); + if (g_smaa_weights_rp) g_vk.DestroyRenderPass(g_dev, g_smaa_weights_rp, NULL); 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_sampler = VK_NULL_HANDLE; g_rp = VK_NULL_HANDLE; + g_smaa_edge_rp = VK_NULL_HANDLE; g_smaa_weights_rp = VK_NULL_HANDLE; + g_nis_fast = 0; g_nis_attempted = 0; g_upscale_half = 0; g_ready = 0; } @@ -505,7 +612,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; } } @@ -536,9 +645,12 @@ static int objects_ensure(void) { VkAttachmentDescription smaa_att = att; smaa_att.format = FX_FORMAT; + smaa_att.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; /* SMAA.hlsl discards pixels without an edge */ VkRenderPassCreateInfo smaa_rci = rci; smaa_rci.pAttachments = &smaa_att; - if (g_vk.CreateRenderPass(g_dev, &smaa_rci, NULL, &g_smaa_rp) != VK_SUCCESS) goto fail; + if (g_vk.CreateRenderPass(g_dev, &smaa_rci, NULL, &g_smaa_weights_rp) != VK_SUCCESS) goto fail; + smaa_att.format = SMAA_EDGE_FORMAT; + if (g_vk.CreateRenderPass(g_dev, &smaa_rci, NULL, &g_smaa_edge_rp) != VK_SUCCESS) goto fail; VkSamplerCreateInfo sci = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_LINEAR, .minFilter = VK_FILTER_LINEAR, .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST, @@ -552,79 +664,21 @@ static int objects_ensure(void) { VkDescriptorSetLayoutCreateInfo dli = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = 1, .pBindings = &b}; if (g_vk.CreateDescriptorSetLayout(g_dev, &dli, NULL, &g_dsl) != VK_SUCCESS) goto fail; VkPushConstantRange pcr = {.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, .offset = 0, .size = PC_MAX_SIZE}; - VkDescriptorSetLayout set_layouts[2] = {g_dsl, g_dsl}; - VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 2, .pSetLayouts = set_layouts, + VkDescriptorSetLayout set_layouts[3] = {g_dsl, g_dsl, g_dsl}; + VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 3, .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 + 4}; 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 + 4, .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 +687,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_edge_rp, g_pl); + MKL(1, P_SMAA_WEIGHTS, smaa_weights_code, "smaa_weights", g_smaa_weights_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, @@ -644,14 +787,32 @@ static void barrier(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkImag g_vk.CmdPipelineBarrier(cmd, src_stage, dst_stage, 0, 0, NULL, 0, NULL, 1, &b); } -static void pass_renderpass(VkCommandBuffer cmd, VkRenderPass render_pass, - VkPipeline p, struct fx_target *dst, VkDescriptorSet src, - const void *pc, uint32_t pcsz) { +/* The tables are copied into place in every frame: a recorded frame can be dropped before it is submitted. */ +static void smaa_tables_copy(VkCommandBuffer cmd) { + const VkBufferImageCopy area = {.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .imageExtent = {SMAA_AREA_W, SMAA_AREA_ROWS, 1}}; + const VkBufferImageCopy search = {.bufferOffset = sizeof(kSmaaArea), .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .imageExtent = {SMAA_SEARCH_W, SMAA_SEARCH_H, 1}}; + const struct { VkImage img; const VkBufferImageCopy *copy; } t[2] = {{g_smaa_area.img, &area}, {g_smaa_search.img, &search}}; + for (int i = 0; i < 2; i++) { + barrier(cmd, t[i].img, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); + g_vk.CmdCopyBufferToImage(cmd, g_smaa_buf, t[i].img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, t[i].copy); + barrier(cmd, t[i].img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT); + } +} + +static void pass_sets(VkCommandBuffer cmd, VkRenderPass render_pass, VkPipeline p, struct fx_target *dst, + const VkDescriptorSet *src, uint32_t count, const void *pc, uint32_t pcsz) { + const VkClearValue clear = {0}; VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = render_pass, .framebuffer = dst->fb, - .renderArea = {{0, 0}, {(uint32_t)dst->w, (uint32_t)dst->h}}}; + .renderArea = {{0, 0}, {(uint32_t)dst->w, (uint32_t)dst->h}}, + .clearValueCount = 1, .pClearValues = &clear}; g_vk.CmdBeginRenderPass(cmd, &rpi, VK_SUBPASS_CONTENTS_INLINE); g_vk.CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, p); - g_vk.CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pl, 0, 1, &src, 0, NULL); + g_vk.CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pl, 0, count, src, 0, NULL); if (g_nis_fast && p == g_pipe[P_NIS] && g_coef_ds) /* nis3: coefficient banks at set 1 */ g_vk.CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pl_nis, 1, 1, &g_coef_ds, 0, NULL); g_vk.CmdPushConstants(cmd, g_pl, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, pcsz, pc); @@ -661,34 +822,38 @@ static void pass_renderpass(VkCommandBuffer cmd, VkRenderPass render_pass, static void pass(VkCommandBuffer cmd, VkPipeline p, struct fx_target *dst, VkDescriptorSet src, const void *pc, uint32_t pcsz) { - pass_renderpass(cmd, g_rp, p, dst, src, pc, pcsz); -} - -static void pass_dual(VkCommandBuffer cmd, VkPipeline p, struct fx_target *dst, - VkDescriptorSet src, VkDescriptorSet second, - const void *pc, uint32_t pcsz) { - VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_rp, .framebuffer = dst->fb, - .renderArea = {{0, 0}, {(uint32_t)dst->w, (uint32_t)dst->h}}}; - VkDescriptorSet sets[2] = {src, second}; - g_vk.CmdBeginRenderPass(cmd, &rpi, VK_SUBPASS_CONTENTS_INLINE); - g_vk.CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, p); - g_vk.CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pl, 0, 2, sets, 0, NULL); - g_vk.CmdPushConstants(cmd, g_pl, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, pcsz, pc); - g_vk.CmdDraw(cmd, 4, 1, 0, 0); - g_vk.CmdEndRenderPass(cmd); + pass_sets(cmd, g_rp, p, dst, &src, 1, pc, pcsz); } 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; +}; + +/* NIS here is the SDR implementation and is documented for <=2x upscales: other outputs run FSR instead. */ +static int nis_falls_back(int scene_w, int scene_h, int cw, int ch) { + return g_scene_is_pq || cw < scene_w || ch < scene_h || (double)cw > (double)scene_w * 2.0 || + (double)ch > (double)scene_h * 2.0; +} + +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; @@ -700,11 +865,7 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce const int upscaling = cw > scene_w || ch > scene_h; int spatial = 0; if (spatial_mode(s->scaling) && (s->scaling == 6 || upscaling)) spatial = s->scaling; - /* NIS here is the SDR implementation and is documented for <=2x upscales. */ - const int nis_fallback = spatial == 7 && - (g_scene_is_pq || cw < scene_w || ch < scene_h || - (double)cw > (double)scene_w * 2.0 || - (double)ch > (double)scene_h * 2.0); + const int nis_fallback = spatial == 7 && nis_falls_back(scene_w, scene_h, cw, ch); static int last_nis_fallback = 0; const int was_nis_fallback = __atomic_exchange_n(&last_nis_fallback, nis_fallback, __ATOMIC_RELAXED); @@ -723,15 +884,16 @@ 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)) { if (s->aa_mode == 2 && (target_ensure_format(&g_smaa_edges, cw, ch, FX_SCRATCH_USAGE, - "SMAA edges", FX_FORMAT, g_smaa_rp) != 0 || + "SMAA edges", SMAA_EDGE_FORMAT, g_smaa_edge_rp) != 0 || target_ensure_format(&g_smaa_weights, cw, ch, FX_SCRATCH_USAGE, - "SMAA weights", FX_FORMAT, g_smaa_rp) != 0)) { + "SMAA weights", FX_FORMAT, g_smaa_weights_rp) != 0 || + smaa_tables_ensure() != 0)) { droiddeck_log("error", "effects: SMAA scratch allocation failed; falling back to FXAA"); snapshot.aa_mode = 1; s = &snapshot; @@ -748,8 +910,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 +973,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 +989,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; } @@ -853,14 +1021,17 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce switch (order[i]) { case FX_FXAA: pass(cmd, g_pipe[P_FXAA], dst, cur_ds, &pr, sizeof(pr)); break; case FX_FXAA_TOON: pass(cmd, g_pipe[P_FXAA_TOON], dst, cur_ds, &pr, sizeof(pr)); break; - case FX_SMAA: - pass_renderpass(cmd, g_smaa_rp, g_pipe[P_SMAA_EDGE], - &g_smaa_edges, cur_ds, &pr, sizeof(pr)); - pass_renderpass(cmd, g_smaa_rp, g_pipe[P_SMAA_WEIGHTS], - &g_smaa_weights, g_smaa_edges.ds, &pr, sizeof(pr)); - pass_dual(cmd, g_pipe[P_SMAA_BLEND], dst, cur_ds, - g_smaa_weights.ds, &pr, sizeof(pr)); + case FX_SMAA: { + struct pc_smaa pc = {.metrics = {1.0f / (float)cw, 1.0f / (float)ch, (float)cw, (float)ch}}; + const VkDescriptorSet weigh[3] = {g_smaa_edges.ds, g_smaa_area.ds, g_smaa_search.ds}; + const VkDescriptorSet blend[2] = {cur_ds, g_smaa_weights.ds}; + SET_NDC(pc); + smaa_tables_copy(cmd); + pass_sets(cmd, g_smaa_edge_rp, g_pipe[P_SMAA_EDGE], &g_smaa_edges, &cur_ds, 1, &pc, sizeof(pc)); + pass_sets(cmd, g_smaa_weights_rp, g_pipe[P_SMAA_WEIGHTS], &g_smaa_weights, weigh, 3, &pc, sizeof(pc)); + pass_sets(cmd, g_rp, g_pipe[P_SMAA_BLEND], dst, blend, 2, &pc, sizeof(pc)); break; + } case FX_TOON: pass(cmd, g_pipe[P_TOON], dst, cur_ds, &pr, sizeof(pr)); break; case FX_TOON_COLOR: { struct pc_toon_color pc = {0}; @@ -907,8 +1078,69 @@ 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(int in_w, int in_h, int out_w, int out_h) { + vkp_effects_sync(); + pthread_mutex_lock(&g_lock); + g_generated_settings = g_cur; + pthread_mutex_unlock(&g_lock); + int spatial = g_generated_settings.scaling; + if (!spatial_mode(spatial) || spatial == 6 || effect_count(&g_generated_settings) != 0) return 0; + /* Build the spatial filter's pipelines now, before frame generation records commands that sample the + * chain's views: one failing later in the same pass would tear the chain down (chain_failed) under a + * recorded command buffer. Build only what effects_run will use for this output, as it decides it: + * NIS on an output it hands to FSR builds FSR, so a NIS that cannot build here costs nothing. */ + int cw = out_w > FX_MAX_DIM ? FX_MAX_DIM : out_w < 1 ? 1 : out_w; + int ch = out_h > FX_MAX_DIM ? FX_MAX_DIM : out_h < 1 ? 1 : out_h; + if (cw <= in_w && ch <= in_h) return 1; /* clamped, it no longer upscales: effects_run builds no filter */ + if (spatial == 7 && nis_falls_back(in_w, in_h, cw, ch)) spatial = 4; + if (objects_ensure() != 0 || pipelines_ensure(spatial, &g_generated_settings) != 0) return 0; + return 1; +} + +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..b85becc0a5 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(int in_w, int in_h, int out_w, int out_h); +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..b402dc0a8a 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; @@ -77,6 +79,24 @@ static int format_refused(VkFormat f) { static _Atomic unsigned g_stat_generated; static uint64_t g_total_generated; + +#define FG_PROVEN_FRAMES 120 +#define FG_HANG_STRIKES 2 +static _Atomic int g_hang_strikes; +static int g_submitted_since_ready; +static uint64_t g_generated_at_ready; + +// A driver that hangs on the engine's shaders loses the device on its first generated frame after every +// recovery, so the compositor would recover and hang again for as long as frame generation stays armed. +static int framegen_loss_strike(int submitted, uint64_t completed_since_ready) { + if (!submitted || completed_since_ready >= FG_PROVEN_FRAMES) { + atomic_store(&g_hang_strikes, 0); + return 0; + } + if (atomic_fetch_add(&g_hang_strikes, 1) + 1 < FG_HANG_STRIKES) return 0; + atomic_store(&g_hang_strikes, 0); + return 1; +} static float g_presented_rate, g_source_rate; static uint32_t g_present_accum, g_source_accum; static int64_t g_window_start_ns; @@ -86,12 +106,49 @@ 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; +static int g_paced_route = 1; + +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); + atomic_store(&g_hang_strikes, 0); } void vkp_framegen_set_armed(int armed, int multiplier, int target_fps) { @@ -117,6 +174,22 @@ 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_paced_route(int composed) { + composed = composed != 0; + if (composed == g_paced_route) return; + g_paced_route = composed; + if (atomic_load(&g_pacer_on)) { + fge_pacer_reset(); + FGLOG("ZeroPacer %s", composed ? "times the layer's frames again (composed route)" + : "waits: the direct route presents the real frame on its own timing"); + } +} + 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 +218,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,16 +259,33 @@ 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); + g_submitted_since_ready = 0; + g_generated_at_ready = g_total_generated; 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"); +} + +// The compositor reports one loss twice: when it happens and again while releasing the lost device. +static int framegen_count_loss(void) { + if (atomic_exchange(&g_dev_lost, 1)) return 0; + int failed = framegen_loss_strike(g_submitted_since_ready, g_total_generated - g_generated_at_ready); + g_submitted_since_ready = 0; + return failed; } void vkp_framegen_device_lost(void) { - atomic_store(&g_dev_lost, 1); + if (framegen_count_loss()) { + int kind = atomic_load(&g_kind); + mark_failed(kind); + FGLOG("%s lost the GPU %d times in a row before its frames completed; frame generation stays off " + "until it is set again", fge_engine_name(kind), FG_HANG_STRIKES); + } atomic_store(&g_dev_ready, 0); fge_device_lost(); if (g_dev) { @@ -226,7 +316,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 +372,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 +468,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 +517,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 && g_paced_route) { + 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 +569,26 @@ 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); + if (n_gen) g_submitted_since_ready = 1; + 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 +598,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..4b7e215446 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,21 @@ 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); +/* 1 when the layer pass presents the real frame itself after its generated frames (the composed route): only + * then can the pacer time the whole group. The direct route keeps the layer's own timing. */ +void vkp_framegen_set_paced_route(int composed); +/* 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..b0da6b2af1 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp @@ -0,0 +1,624 @@ +#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; +// The interpolator keeps per-pair work and the prepared Real by sequence. A pass dropped after recording +// Interpolate never ran on the GPU, so the next pair's A gets a fresh identity no record has seen: nothing the +// dropped pass would have prepared is reused, nor its flow start. The identity is stable for the whole pair, so +// its phases still share their work (and ReallyZero sees one pair, not a first picture per phase). +bool g_interpolate_uncommitted = false; +bool g_record_stale = false; +uint64_t g_pair_anonymous = 0; // the recovery pair's A identity, 0 for an ordinary pair +uint64_t g_anonymous_count = 0; +constexpr uint64_t kAnonymousSequence = 1ull << 63; // above any frame sequence the compositor hands out + +// 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; + // ReallyZero's Resize accepts 64..16384 per side: refuse this frame only, before touching the + // engine's state, so a supported size later still generates. + if (width < 64 || height < 64 || width > 16384 || height > 16384) return 0; + 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; + g_pair_anonymous = g_record_stale ? (kAnonymousSequence | ++g_anonymous_count) : 0; + g_record_stale = false; +} + +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; + if (g_pair_anonymous) previous.sequence = g_pair_anonymous; + g_interpolate_uncommitted = true; + + 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) { + g_interpolate_uncommitted = false; + 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; + if (g_interpolate_uncommitted) g_record_stale = true; + g_interpolate_uncommitted = false; + g_pair_pending = false; +} + +void zfg_forget_targets(void) { + g_pair_pending = false; + if (g_interpolate_uncommitted) g_record_stale = true; + g_interpolate_uncommitted = 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..fb93305e4b 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; } @@ -1075,6 +1138,7 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const if (vkp_update_map(scene_w, scene_h) != 0) return -1; const int deep = hf && !hf->tonemap; if (hf) composed = 1; + vkp_framegen_set_paced_route(composed); if (hf && hf->tonemap) color = NULL; int n = vkp_pass_begin_generate(scene_w, scene_h, draws, n_draws, hf, &rw, &rh); if (n < 0) return -1; @@ -1084,7 +1148,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 +1170,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 +1190,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 +1282,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 +1303,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..8801c87286 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() && + (upscale_w > input_w || upscale_h > input_h) && + vkp_effects_prepare_generated(input_w, input_h, upscale_w, upscale_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,30 @@ 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() && + (mapped_w > input_w || mapped_h > input_h) && + vkp_effects_prepare_generated(input_w, input_h, mapped_w, mapped_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 +3582,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 +3631,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 +3659,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..f22865c110 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) { @@ -432,6 +461,11 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv * __android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : ""); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetMirrorCapture(JNIEnv *env, jclass clazz, jboolean on) { + droiddeck_host_mirror_capture(on ? 1 : 0); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) { g_display_buffer_driver = on ? 1 : 0; @@ -807,6 +841,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 +864,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 +921,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/ProtonMenu.kt b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt index 385081cc7d..b6799bd315 100644 --- a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt @@ -45,6 +45,7 @@ internal class ProtonMenu( var experimentalReleases by Operation.experimentalReleases companion object { const val EXPERIMENTAL = "experimental" + private val REMEMBERED = setOf(ProtonExtras.OWN, ProtonExtras.ANTICHEAT) } @VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) } @VisibleForTesting internal var experimentalRefresh: () -> List? = { ExperimentalProtons.refresh(activity) } @@ -66,7 +67,7 @@ internal class ProtonMenu( ui.post { protonStage = label; protonPercent = value } } }.getOrElse { it.message ?: it.javaClass.simpleName } - if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false) + if (problem == null && !automatic && tool.id in REMEMBERED) ProtonExtras.setDeclined(activity, false, tool.id) if (tool.id == ProtonExtras.OWN) { if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem) Onboarding.recheck(activity) @@ -96,7 +97,7 @@ internal class ProtonMenu( protonPercent = -1 Thread({ if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir) - if (tool.id == ProtonExtras.OWN && ProtonExtras.installedAll(activity, tool).isEmpty()) ProtonExtras.setDeclined(activity, true) + if (tool.id in REMEMBERED && ProtonExtras.installedAll(activity, tool).isEmpty()) ProtonExtras.setDeclined(activity, true, tool.id) ui.post { protonBusyId = null protonStage = null @@ -158,7 +159,7 @@ internal class ProtonMenu( refreshExperimental() protonRows = ProtonExtras.offered(activity).map { val all = ProtonExtras.installedAll(activity, it) - ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it)) + ProtonRow(it.id, if (it.label != 0) activity.getString(it.label) else it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it)) } } 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..732b26620a 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 @@ -99,6 +100,12 @@ import com.droiddeck.launcher.input.SteamControllerBle import com.droiddeck.launcher.input.DirectTouchHold import com.droiddeck.launcher.input.GestureTouchStreamGate import com.droiddeck.launcher.input.PenRouter +import com.droiddeck.launcher.input.AirTrigger +import com.droiddeck.launcher.input.AirTriggerButtons +import com.droiddeck.launcher.input.AirTriggerInput +import com.droiddeck.launcher.input.AirTriggerPrefs +import com.droiddeck.launcher.input.AirTriggerSetup +import com.droiddeck.launcher.input.RedMagicAirTriggers import com.droiddeck.launcher.input.PenStream import com.droiddeck.launcher.input.PointerGestures import com.droiddeck.launcher.input.PointerSpace @@ -162,7 +169,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 +186,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 +239,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) @@ -235,6 +247,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private lateinit var sessionRoot: FrameLayout private var inputRouter: InputRouter? = null private var physicalInputBindings: com.droiddeck.launcher.input.PhysicalInputBindings? = null + private var airTriggerInput: AirTriggerInput? = null + private var airTriggersOpen = false + private var airTriggerMenu by mutableStateOf(null) + private var airTriggerGlow: com.droiddeck.launcher.ui.AirTriggerGlow? = null private var inputSettingsOpen by mutableStateOf(false) @Volatile private var inputUsesLocalActions = false private var inputUsesPointer = false @@ -348,6 +364,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 +567,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 +586,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) @@ -643,6 +671,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var effects by mutableStateOf(ScreenEffects.OFF) private var observedScreenEffectsProfileId by mutableStateOf(null) private var screenEffectsTarget by mutableStateOf(SCREEN_EFFECTS_TARGET_AUTO) + private var screenEffectsProfileRevision by mutableIntStateOf(0) private var cardboard by mutableStateOf(Cardboard.OFF) private var headTracker: HeadTracker? = null private var steamVrStatus by mutableStateOf(null) @@ -703,9 +732,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 +833,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 +876,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() || @@ -956,6 +984,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this)) padBridge = bridge inputRouter = InputRouter(inputOutput).also { bridge.setInputRouter(it); DeckControls.setRouter(it); physicalInputBindings = com.droiddeck.launcher.input.PhysicalInputBindings(it) } + if (RedMagicAirTriggers.supported(this)) { + airTriggerInput = AirTriggerInput(bridge, ::holdOnScreen, ::airTriggerTouched) + RedMagicAirTriggers.restore(this) + } refreshInputProfile() bridge.setOnChordInput(backQamInput::onChordInput) SessionState.padBridge = bridge @@ -979,6 +1011,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 +1020,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) } @@ -1080,6 +1113,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onResolvePointerIcon(event: MotionEvent, pointerIndex: Int): android.view.PointerIcon? = if (platformPointerShown == true) super.onResolvePointerIcon(event, pointerIndex) else null }.apply { addView(sessionOverlay) }) + if (airTriggerInput != null) airTriggerGlow = com.droiddeck.launcher.ui.AirTriggerGlow(this).also { root.addView(it) } setContentView(root) glassesScope.launch { Glasses.state.collect { glasses = it @@ -1192,7 +1226,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 +1296,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, @@ -1361,6 +1398,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } LaunchedEffect(drawerOpen, menuOwnsController, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) { updateOnScreenControls() + refreshAirTriggers() padBridge?.setInputEnabled(resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended) if (!drawerOpen && backTapOpenedDrawer) { backTaps.cancel() @@ -1451,7 +1489,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 +1511,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 +1566,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, @@ -1547,8 +1658,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde effects = effects, screenEffectsTarget = screenEffectsTarget, screenEffectsTargets = screenEffectsTargetOptions(), - screenEffectsCanDelete = screenEffectsProfileIdForTarget(screenEffectsTarget)?.let { - SessionPrefs.hasScreenEffectsOverride(this@SessionActivity, it) + screenEffectsCanDelete = screenEffectsProfileRevision.let { + screenEffectsProfileIdForTarget(screenEffectsTarget)?.let { + SessionPrefs.hasScreenEffectsOverride(this@SessionActivity, it) || + SessionPrefs.hasScreenEffectsUpscalerOverride(this@SessionActivity, it) + } } == true, cardboard = cardboard, cardboardSensor = hasRotationSensor, @@ -1626,6 +1740,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) @@ -1649,6 +1768,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } else { val profileId = screenEffectsProfileIdForTarget(target) SessionPrefs.setScreenEffectsUpscaler(this@SessionActivity, profileId, m) + screenEffectsProfileRevision++ if (target == screenEffectsTarget) { upscaler = m @@ -1684,6 +1804,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } else { val profileId = screenEffectsProfileIdForTarget(target) SessionPrefs.setScreenEffectsUpscaler(this@SessionActivity, profileId, m) + screenEffectsProfileRevision++ if (target == screenEffectsTarget) { upscaler = m if (screenEffectsUpscalerTargetAppliesToLiveOutput(target)) { @@ -1730,7 +1851,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val profileId = screenEffectsProfileIdForTarget(editorTarget) SessionPrefs.setScreenEffects(this@SessionActivity, profileId, e) effects = e - if (screenEffectsTargetAppliesToLiveOutput(editorTarget)) e.push(upscaler) + if (screenEffectsTargetAppliesToLiveOutput(editorTarget)) { + val upscalerAppliesToLiveOutput = + screenEffectsUpscalerTargetAppliesToLiveOutput(editorTarget) + val liveUpscaler = if (upscalerAppliesToLiveOutput) { + SessionPrefs.screenEffectsUpscaler( + this@SessionActivity, + screenEffectsProfileIdForTarget(editorTarget) + ) + } else { + SessionPrefs.screenEffectsUpscaler( + this@SessionActivity, + currentScreenEffectsProfileId() + ) + } + e.push(liveUpscaler) + } } } }, @@ -1787,7 +1923,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(), outputFpsLimit()) }, hdr = hdrWanted, hdrAvailable = hdrAvailable, @@ -1810,21 +1946,45 @@ 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), wowChat = wowChat.remembered, onWowChat = wowChat::choose, controller = controllerSettings, + airTriggers = airTriggerMenu, + onAirTriggers = { on -> AirTriggerPrefs.setEnabled(this@SessionActivity, on); refreshAirTriggers() }, + onAirTriggerButton = { trigger, id -> + AirTriggerPrefs.setButton(this@SessionActivity, primaryInputLayout?.id.orEmpty(), trigger, id) + refreshAirTriggers() + }, + onAirTriggerAction = { trigger, action -> + AirTriggerPrefs.setAction(this@SessionActivity, primaryInputLayout?.id.orEmpty(), trigger, action) + refreshAirTriggers() + }, + onAirTriggerRate = { trigger, rate -> + AirTriggerPrefs.setRate(this@SessionActivity, primaryInputLayout?.id.orEmpty(), trigger, rate) + refreshAirTriggers() + }, + onAirTriggerVibration = { on -> AirTriggerPrefs.setVibration(this@SessionActivity, on); refreshAirTriggers() }, + onAirTriggerScreenLight = { on -> AirTriggerPrefs.setScreenLight(this@SessionActivity, on); refreshAirTriggers() }, + onAirTriggerLed = { led -> + AirTriggerPrefs.setLed(this@SessionActivity, led) + if (airTriggersOpen) RedMagicAirTriggers.open(this@SessionActivity) + refreshAirTriggers() + }, 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 +2059,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 +2105,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 +2122,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 +2160,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 +2257,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 +2296,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 +2306,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 +2337,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) @@ -2515,10 +2706,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val targetUpscaler = SessionPrefs.screenEffectsUpscaler(this, profileId) effects = targetEffects upscaler = targetUpscaler + val upscalerAppliesToLiveOutput = screenEffectsUpscalerTargetAppliesToLiveOutput(target) + val liveUpscaler = if (upscalerAppliesToLiveOutput) { + targetUpscaler + } else { + SessionPrefs.screenEffectsUpscaler(this, currentScreenEffectsProfileId()) + } + if (upscalerAppliesToLiveOutput) { + WaylandCompositor.nativeSetUpscaler(liveUpscaler) + } if (screenEffectsTargetAppliesToLiveOutput(target)) { - WaylandCompositor.nativeSetUpscaler(targetUpscaler) - WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(targetEffects, targetUpscaler)?.name) - targetEffects.push(targetUpscaler) + WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(targetEffects, liveUpscaler)?.name) + targetEffects.push(liveUpscaler) + } else if (upscalerAppliesToLiveOutput) { + val liveEffects = SessionPrefs.screenEffects(this, currentScreenEffectsProfileId()) + WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(liveEffects, liveUpscaler)?.name) } } @@ -2531,6 +2733,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun resetScreenEffectsTarget(target: String) { if (target != screenEffectsTarget) return SessionPrefs.resetScreenEffectsProfile(this, screenEffectsProfileIdForTarget(target)) + screenEffectsProfileRevision++ syncScreenEffectsTarget(target) } @@ -2538,6 +2741,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (target != screenEffectsTarget) return val profileId = screenEffectsProfileIdForTarget(target) ?: return SessionPrefs.deleteScreenEffectsProfile(this, profileId) + screenEffectsProfileRevision++ syncScreenEffectsTarget(target) } @@ -2668,7 +2872,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 +2928,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 +3194,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(), outputFpsLimit(), ) onOutputAttached(holder) if (SessionState.running && size != previous) { @@ -3008,6 +3212,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 +3237,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 +3254,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 +3294,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 +3303,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 +3367,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 +3420,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 +3469,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(), outputFpsLimit()) pushCardboard(activeCardboard) if (changed && ::surfaceView.isInitialized) applyFrameGen() } @@ -3431,19 +3682,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()) @@ -3479,6 +3717,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun onSessionEnded(status: Int) { ended = true + runOnUiThread { refreshAirTriggers() } ++steamVrRequestGeneration if (isInPictureInPictureMode) { runOnUiThread { finish() } @@ -3536,6 +3775,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun releasePads(keepBackTap: Boolean = false) { inputMotion.stop() physicalInputBindings?.release() + airTriggerInput?.release() com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this) backQamInput.cancel(keepTap = keepBackTap) padBridge?.releaseAll() @@ -3655,16 +3895,23 @@ 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 physicalInputAccepted() = resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && + !inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible + + 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 -> { @@ -3683,10 +3930,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } if (penStream.holdsKey(event) || (penSettings.mode != SessionPrefs.PEN_TOUCH && PenStream.isPenKey(event))) return penStream.onKey(event) + if (airTriggerInput?.onKey(event) { physicalInputAccepted() && !pipUi && !appTextFocus } == true) return true if (appTextFocus) return super.dispatchKeyEvent(event) if (!pipUi) { - if (physicalInputBindings?.onKey(event, resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && - !inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true + if (physicalInputBindings?.onKey(event, physicalInputAccepted()) == true) return true if (physicalShortcuts.onKey( event, enabled = resumed && SessionState.running && !SessionState.suspended && @@ -3747,7 +3994,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 +4036,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 +4077,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 +4164,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 { @@ -4911,6 +5158,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde || inputProfile.keys.any { it.action is InputAction.MouseButton } physicalInputBindings?.configure(inputProfile.keys) padBridge?.setInputProfile(inputProfile) + refreshAirTriggers() DeckControls.refresh() onScreenControls?.updateLayout(primaryInputLayout) bottomInputControls?.updateLayout(primaryInputLayout) @@ -4921,6 +5169,32 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde secondScreenPresentation?.refreshControls() } + private fun refreshAirTriggers() { + val input = airTriggerInput ?: return + val layout = primaryInputLayout + val layoutId = layout?.id.orEmpty() + val enabled = AirTriggerPrefs.enabled(this) + val chosen = AirTrigger.entries.associateWith { + AirTriggerSetup(AirTriggerButtons.resolve(layout, it, AirTriggerPrefs.button(this, layoutId, it)), + AirTriggerPrefs.action(this, layoutId, it), AirTriggerPrefs.rate(this, layoutId, it)) + } + val active = enabled && resumed && !ended && !SessionState.suspended + input.configure(if (active) chosen else emptyMap()) + if (active != airTriggersOpen) { + airTriggersOpen = active + if (active) RedMagicAirTriggers.open(this) else RedMagicAirTriggers.restore(this) + } + airTriggerMenu = com.droiddeck.launcher.ui.AirTriggerMenu(enabled, chosen.mapValues { it.value.element.id }, + AirTriggerButtons.options(layout).map { it.id to it.name }, AirTriggerPrefs.vibration(this), AirTriggerPrefs.screenLight(this), + AirTriggerPrefs.led(this), chosen.mapValues { it.value.action }, chosen.mapValues { it.value.rate }) + } + + private fun airTriggerTouched(trigger: AirTrigger, down: Boolean) { + RedMagicAirTriggers.light(if (down) trigger.pressLight else trigger.releaseLight) + if (down && AirTriggerPrefs.vibration(this)) com.droiddeck.launcher.ui.ControllerHaptics.click(this) + airTriggerGlow?.show(trigger, down && AirTriggerPrefs.screenLight(this)) + } + private fun tapQam() { if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam() } @@ -4945,6 +5219,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun refreshControls() { + padConnected = controllerConnected() applyUnfoldedControls() updateOnScreenControls() } @@ -4960,12 +5235,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 +5254,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 +5265,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 +5285,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 +5300,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 +5391,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 +5412,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (text != null && stillOpen()) endGameField() done(text) } - selectGameField(KEY_C) + selectGameField(copy = true) } private fun cancelWowChat() { @@ -5391,10 +5651,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var sessionTouchDown = false private var screenTapsClick = true - private fun onScreenLeftMouseButtonShown(): Boolean = listOfNotNull( + private fun inputSurfaces() = listOfNotNull( onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface, secondScreenPresentation?.controlsView, swappedInputSurface, - ).any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) } + ) + + private fun onScreenLeftMouseButtonShown(): Boolean = + inputSurfaces().any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) } + + private fun holdOnScreen(elementId: String, trigger: AirTrigger, held: Boolean, cancelled: Boolean): Boolean { + val surfaces = inputSurfaces().filter { it.inputRole == InputRole.PRIMARY } + if (held) return surfaces.any { it.isShown && it.hold(elementId, trigger.ordinal, true) } + surfaces.forEach { it.hold(elementId, trigger.ordinal, false, cancelled) } + return true + } override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) } @@ -5851,7 +6121,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 +6230,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 +6330,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 +6407,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) @@ -6181,7 +6461,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun holdComposedOutput(hold: Boolean) { + val wasHeld = composedHolds > 0 composedHolds = (composedHolds + if (hold) 1 else -1).coerceAtLeast(0) + val held = composedHolds > 0 + if (held == wasHeld) return + WaylandCompositor.nativeSetMirrorCapture(held) + // Importable HDR is redirected by the compositor hold. Keep its layer-only fallback available. if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree()) } @@ -6242,6 +6527,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde heldButtons.clear() hidePrimaryKeyboard() sessionClipboard.stop() + sessionTextInput.stop() padMotion?.stop() cursorVisible = false closeSecondScreen(reset = false) @@ -6257,7 +6543,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() @@ -6327,7 +6613,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde displayManager.unregisterDisplayListener(displayListener) com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener) contentResolver.unregisterContentObserver(refreshSettingObserver) - if (!screenIsOff()) closeSecondScreen(reset = false) + // Closing the presentation removes the docked Agent page and unregisters its picker. + if (com.droiddeck.launcher.session.SessionVisibilityPolicy.shouldCloseSecondScreenOnStop( + screenOff = screenIsOff(), + dockedDrawerOpen = menuShownOnBottom(), + attachmentPickerOpen = com.droiddeck.launcher.agent.AgentAttachments.picking, + ) + ) closeSecondScreen(reset = false) + sessionTextInput.stop() startedScreens = (startedScreens - 1).coerceAtLeast(0) updateGlassesScreen() updateBottomGame() @@ -6363,6 +6656,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onResume() { super.onResume() + com.droiddeck.launcher.agent.AgentAttachments.picking = false drawerGameInventoryRevision++ com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event -> com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) } @@ -6385,12 +6679,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 +6702,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) @@ -6474,7 +6770,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde heldButtons.clear() if (!screenOff) { val menuUp = menuShownOnBottom() - drawerOpen = false + if (!com.droiddeck.launcher.agent.AgentAttachments.picking) drawerOpen = false if (menuUp) SessionState.bottomMenu = true pcKeyboardOpen = false achievementsOpen = false @@ -6486,6 +6782,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (::scrollTouch.isInitialized) scrollTouch.cancel() if (::padMouse.isInitialized) padMouse.reset() resumed = false + refreshAirTriggers() boostGpuClock(false) updateKeyboardRoute() updatePointerCapture() @@ -6899,7 +7196,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 }, ) @@ -7076,7 +7376,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!hasFocus) { cancelTouchGestures() releaseHeldGuestInput() + airTriggerInput?.release() } + // Game Space clears the distribute state when the launcher or Game Space itself comes to the front. + if (hasFocus && airTriggersOpen) RedMagicAirTriggers.open(this) if (hasFocus && !pipUi) { retryFieldKeyboard(true) goFullscreen() @@ -7123,6 +7426,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 +7440,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) @@ -7161,6 +7467,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde inputMotion.stop() padBridge?.setInputEnabled(false) physicalInputBindings?.close() + airTriggerInput?.close() + airTriggerInput = null + if (airTriggersOpen) RedMagicAirTriggers.restore(this) padBridge?.stop() DeckControls.clearRouter(inputRouter) inputRouter = null @@ -7247,6 +7556,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/AgentAttachments.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt index b4f9a09dff..9c9dd5c150 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt @@ -19,6 +19,15 @@ object AgentAttachments { /** Guest paths waiting to go with the next message. */ val pending = mutableStateListOf() + /** True while the file picker is open over a session: it answers the drawer's agent page, so the drawer must stay. */ + @Volatile var picking = false + + /** Launches a system screen that answers the agent page, keeping the drawer for it; the result callback clears [picking]. */ + fun pick(launch: () -> Unit) { + picking = true + if (runCatching(launch).isFailure) picking = false + } + private const val NEW = "new" private const val GUEST_DIR = "/root/.cache/droiddeck/attachments" private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp") @@ -35,14 +44,17 @@ object AgentAttachments { val folder = chat ?: NEW val dir = File(hostDir(app), folder).apply { mkdirs() } return uris.mapNotNull { uri -> + var target: File? = null runCatching { val name = displayName(app, uri).replace(Regex("[^A-Za-z0-9._-]"), "_").ifEmpty { "file" } - var target = File(dir, name) + var candidate = File(dir, name) var n = 1 - while (target.exists()) target = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}") - app.contentResolver.openInputStream(uri)!!.use { input -> target.outputStream().use { input.copyTo(it) } } - "$GUEST_DIR/$folder/${target.name}" - }.getOrNull() + // Created atomically, so copies running side by side never pick the same name. + while (!candidate.createNewFile()) candidate = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}") + target = candidate + app.contentResolver.openInputStream(uri)!!.use { input -> candidate.outputStream().use { input.copyTo(it) } } + "$GUEST_DIR/$folder/${candidate.name}" + }.onFailure { target?.delete() }.getOrNull() } } 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/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index 2619aacd1c..4beeec8d45 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -27,6 +27,7 @@ import java.io.File import java.text.SimpleDateFormat import java.util.Date import java.util.Locale +import java.util.TimeZone object DeviceReport { private const val TAG = "DeviceReport" @@ -36,6 +37,10 @@ object DeviceReport { .map { it.substringAfter(':').trim().split(Regex("\\s+")).filter(String::isNotEmpty).joinToString(" ") } .filter(String::isNotEmpty).distinct().joinToString(" | ").ifEmpty { "not reported" } + internal fun buildDate(millis: Long): String? = millis.takeIf { it > 0 }?.let { + SimpleDateFormat("yyyy-MM-dd HH:mm 'UTC'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.format(Date(it)) + } + fun write(context: Context, target: File, mode: String) { try { target.writeText(build(context, mode)) @@ -129,6 +134,7 @@ object DeviceReport { k("Android", "${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})") k("Security patch", Build.VERSION.SECURITY_PATCH) k("Build", Build.DISPLAY) + k("Build date", buildDate(Build.TIME)) k("Fingerprint", Build.FINGERPRINT) k("Kernel", System.getProperty("os.version")) k("ABIs", Build.SUPPORTED_ABIS.joinToString(", ")) 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 fbd14aea93..b7d95c4872 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", "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 f58320bc8e..8bb59ad8e6 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 @@ -187,6 +187,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 @@ -993,13 +999,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 @@ -1034,8 +1047,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) @@ -1065,6 +1080,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) } @@ -1177,13 +1193,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() @@ -1256,8 +1273,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/RedMagicAirTriggers.kt b/app/src/main/java/com/droiddeck/launcher/input/RedMagicAirTriggers.kt new file mode 100644 index 0000000000..051e745945 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/RedMagicAirTriggers.kt @@ -0,0 +1,324 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import android.content.SharedPreferences +import android.net.Uri +import android.os.Build +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.os.Parcel +import android.provider.Settings +import android.util.Log +import android.view.InputDevice +import android.view.KeyEvent +import java.util.EnumMap +import java.util.EnumSet +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit +import org.json.JSONObject + +enum class AirTrigger(val keyCode: Int, val control: InputControl, val pressLight: Int, val releaseLight: Int) { + LEFT(KeyEvent.KEYCODE_F7, InputControl.LT, 106, 107), RIGHT(KeyEvent.KEYCODE_F8, InputControl.RT, 108, 109); + + companion object { + private const val DEVICE_PREFIX = "nubia_tgk" + + internal fun isTriggerDevice(device: InputDevice?): Boolean { + if (device == null) return false + if (device.name.startsWith(DEVICE_PREFIX)) return true + // Some RedMagic firmware merges the trigger sensors with an unnamed built-in keyboard. + return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && + device.name.isEmpty() && !device.isVirtual && !device.isExternal && + device.supportsSource(InputDevice.SOURCE_KEYBOARD) && + device.hasKeys(LEFT.keyCode, RIGHT.keyCode).all { it } + } + + internal fun of(keyCode: Int, device: InputDevice?): AirTrigger? = + entries.firstOrNull { it.keyCode == keyCode }?.takeIf { isTriggerDevice(device) } + } +} + +/** Game Space's single tap holds the button while the trigger is touched; its long press latches it until the next touch. */ +enum class AirTriggerAction { TAP, LATCH, RAPID } + +/** Game Space's rapid fire counts for its low, normal and high click frequency. */ +enum class RapidFireRate(val clicksPerSecond: Int) { LOW(2), NORMAL(5), HIGH(10) } + +/** Game Space's touch atmosphere lamp cases, by their name in RedMagic's shoulder light settings. */ +enum class AirTriggerLed(val effect: String, val fallback: String) { + OFF("close", "02000000"), STEADY("steady", "02101000"), PULSE("pulse", "02102000") +} + +data class AirTriggerSetup( + val element: InputSurfaceElement, + val action: AirTriggerAction = AirTriggerAction.TAP, + val rate: RapidFireRate = RapidFireRate.NORMAL, +) { + /** Long press and rapid fire decide when the button is let go, so they press a toggle button as a plain one. */ + internal val target get() = if (action != AirTriggerAction.TAP && element.toggle) element.copy(toggle = false) else element +} + +object AirTriggerButtons { + fun options(layout: SavedInputLayout?): List { + val placed = layout?.let { (it.elements + it.rotated).distinctBy { element -> element.id } }.orEmpty() + .filter { it.kind == InputElementKind.BUTTON || it.kind == InputElementKind.TRIGGER } + return placed + AirTrigger.entries.filter { trigger -> placed.none { it.control == trigger.control } } + .map { InputSurfaceElement(it.control, 0f, 0f, 0f, 0f) } + } + + fun resolve(layout: SavedInputLayout?, trigger: AirTrigger, chosen: String?): InputSurfaceElement { + val options = options(layout) + return chosen?.let { id -> options.firstOrNull { it.id == id } } ?: options.first { it.control == trigger.control } + } +} + +object AirTriggerPrefs { + private const val FILE = "redmagic-air-triggers" + private const val ENABLED = "enabled" + private const val VIBRATION = "vibration" + private const val SCREEN_LIGHT = "screen-light" + private const val LED = "led" + internal const val OWNED = "distribute-owned" + + fun prefs(context: Context): SharedPreferences = context.getSharedPreferences(FILE, Context.MODE_PRIVATE) + fun enabled(context: Context) = prefs(context).getBoolean(ENABLED, false) + fun setEnabled(context: Context, on: Boolean) = prefs(context).edit().putBoolean(ENABLED, on).apply() + fun button(context: Context, layoutId: String, trigger: AirTrigger): String? = prefs(context).getString(key(layoutId, trigger), null) + fun setButton(context: Context, layoutId: String, trigger: AirTrigger, elementId: String) = + prefs(context).edit().putString(key(layoutId, trigger), elementId).apply() + fun action(context: Context, layoutId: String, trigger: AirTrigger) = read(context, key(layoutId, trigger, "action"), AirTriggerAction.TAP) + fun setAction(context: Context, layoutId: String, trigger: AirTrigger, action: AirTriggerAction) = + prefs(context).edit().putString(key(layoutId, trigger, "action"), action.name).apply() + fun rate(context: Context, layoutId: String, trigger: AirTrigger) = read(context, key(layoutId, trigger, "rate"), RapidFireRate.NORMAL) + fun setRate(context: Context, layoutId: String, trigger: AirTrigger, rate: RapidFireRate) = + prefs(context).edit().putString(key(layoutId, trigger, "rate"), rate.name).apply() + fun vibration(context: Context) = prefs(context).getBoolean(VIBRATION, false) + fun setVibration(context: Context, on: Boolean) = prefs(context).edit().putBoolean(VIBRATION, on).apply() + fun screenLight(context: Context) = prefs(context).getBoolean(SCREEN_LIGHT, false) + fun setScreenLight(context: Context, on: Boolean) = prefs(context).edit().putBoolean(SCREEN_LIGHT, on).apply() + fun led(context: Context) = read(context, LED, AirTriggerLed.STEADY) + fun setLed(context: Context, led: AirTriggerLed) = prefs(context).edit().putString(LED, led.name).apply() + + private inline fun > read(context: Context, key: String, default: E): E = + prefs(context).getString(key, null)?.let { name -> enumValues().firstOrNull { it.name == name } } ?: default + + private fun key(layoutId: String, trigger: AirTrigger, setting: String? = null) = + listOfNotNull(trigger.name.lowercase(), setting).joinToString("-") + ".$layoutId" +} + +/** Game Space's exported provider switches the triggers to plain F7/F8 keys without its panel, and needs no permission. */ +object RedMagicAirTriggers { + private const val TAG = "AirTriggers" + private const val AUTHORITY = "cn.nubia.tgk.data.TgkDataProvider" + private val URI = Uri.parse("content://$AUTHORITY") + private const val OPEN = "openTouchGameKeyDistribute" + private const val CLOSE = "closeTouchGameKeyDistribute" + private const val SHOULDER_LIGHT_ON = 110 + private const val SHOULDER_LIGHT_OFF = 111 + private const val SHOULDER_SETTINGS = "lighting_shoulder_config_json" + private val REAPPLY_MS = longArrayOf(1_000, 5_000) + internal var worker: Executor = ThreadPoolExecutor(0, 1, 10, TimeUnit.SECONDS, LinkedBlockingQueue()) { Thread(it, "air-triggers") } + internal var lights: TriggerLights = ColorfulLights + private val main = Handler(Looper.getMainLooper()) + private var reapply: Runnable? = null + + @Suppress("DEPRECATION") + fun supported(context: Context) = context.packageManager.resolveContentProvider(AUTHORITY, 0) != null && + InputDevice.getDeviceIds().any { AirTrigger.isTriggerDevice(InputDevice.getDevice(it)) } + + /** Call on the main thread. */ + fun open(context: Context) { + val app = context.applicationContext + cancelReapply() + worker.execute { apply(app) } + // Game Space runs its own trigger setup for the app that comes to the front, which switches the trigger keys and lights off again. + val again = Runnable { worker.execute { apply(app) } } + reapply = again + REAPPLY_MS.forEach { main.postDelayed(again, it) } + } + + private fun apply(app: Context) { + val prefs = AirTriggerPrefs.prefs(app) + if (!prefs.getBoolean(AirTriggerPrefs.OWNED, false) && Settings.Global.getInt(app.contentResolver, OPEN, 0) != 1) + prefs.edit().putBoolean(AirTriggerPrefs.OWNED, true).commit() + call(app, OPEN) + if (!prefs.getBoolean(AirTriggerPrefs.OWNED, false)) return + lights.request(SHOULDER_LIGHT_ON) + // The light service drops every trigger light until an effect is set, which Game Space only does from its own view. + lights.setEffect(shoulderEffect(Settings.Global.getString(app.contentResolver, SHOULDER_SETTINGS), AirTriggerPrefs.led(app))) + // Entering the scene turns the lights off; the release actions show the idle light picked in RedMagic's lighting settings. + AirTrigger.entries.forEach { lights.request(it.releaseLight) } + } + + /** The code RedMagic's shoulder light settings give the effect, such as "02101000" for steady. */ + internal fun shoulderEffect(settings: String?, led: AirTriggerLed): String = settings + ?.let { runCatching { JSONObject(it).optJSONObject("shoulder_effects")?.optString(led.effect) }.getOrNull() } + ?.takeIf { it.length == 8 } ?: led.fallback + + /** Closes only what this app opened, so a distribute another app turned on stays on. Call on the main thread. */ + fun restore(context: Context) { + val app = context.applicationContext + cancelReapply() + worker.execute { + val prefs = AirTriggerPrefs.prefs(app) + if (!prefs.getBoolean(AirTriggerPrefs.OWNED, false)) return@execute + lights.request(SHOULDER_LIGHT_OFF) + if (call(app, CLOSE)) prefs.edit().remove(AirTriggerPrefs.OWNED).commit() + } + } + + fun light(code: Int) = worker.execute { lights.request(code) } + + private fun cancelReapply() { + reapply?.let(main::removeCallbacks) + reapply = null + } + + private fun call(context: Context, method: String) = runCatching { context.contentResolver.call(URI, method, null, null) != null } + .onFailure { Log.w(TAG, "$method failed", it) }.getOrDefault(false) +} + +internal interface TriggerLights { + fun request(action: Int) + fun setEffect(effect: String) +} + +private object ColorfulLights : TriggerLights { + private const val TAG = "AirTriggers" + private const val SERVICE = "ColorfulLightService" + private const val INTERFACE = "com.zte.hardware.IColorfulLightManager" + // IColorfulLightManager transaction codes; its ColorfulLightManager wrapper is a blocked hidden API. + private const val REQUEST_LIGHT = IBinder.FIRST_CALL_TRANSACTION + private const val SET_SHOULDER_EFFECT = IBinder.FIRST_CALL_TRANSACTION + 2 + private val binder: IBinder? by lazy { + runCatching { Class.forName("android.os.ServiceManager").getMethod("getService", String::class.java).invoke(null, SERVICE) as IBinder? } + .getOrNull()?.takeIf { runCatching { it.interfaceDescriptor }.getOrNull() == INTERFACE } + } + + override fun request(action: Int) = transact(REQUEST_LIGHT) { writeInt(action) } + override fun setEffect(effect: String) = transact(SET_SHOULDER_EFFECT) { writeString(effect) } + + private fun transact(code: Int, write: Parcel.() -> Unit) { + val binder = binder ?: return + val data = Parcel.obtain() + val reply = Parcel.obtain() + try { + data.writeInterfaceToken(INTERFACE) + data.write() + binder.transact(code, data, reply, 0) + reply.readException() + } catch (e: Exception) { + Log.w(TAG, "light call $code failed", e) + } finally { + data.recycle() + reply.recycle() + } + } +} + +/** Presses the chosen button on screen when it is shown, so it animates and keeps one toggle state; otherwise uses a source of its own. */ +class AirTriggerInput( + private val pad: PadBridge, + private val onScreen: (elementId: String, trigger: AirTrigger, held: Boolean, cancelled: Boolean) -> Boolean = { _, _, _, _ -> false }, + private val touched: (AirTrigger, Boolean) -> Unit = { _, _ -> }, + private val handler: Handler = Handler(Looper.getMainLooper()), +) { + private val sources = EnumMap(AirTrigger::class.java) + private val setups = EnumMap(AirTrigger::class.java) + private val held = EnumSet.noneOf(AirTrigger::class.java) + private val pressed = EnumSet.noneOf(AirTrigger::class.java) + private val heldOnScreen = EnumMap(AirTrigger::class.java) + private val timers = EnumMap(AirTrigger::class.java) + + fun configure(setups: Map) { + for (trigger in AirTrigger.entries) { + val setup = setups[trigger] + if (this.setups[trigger] == setup) continue + stop(trigger) + if (sources[trigger]?.element != setup?.target) { + pressed.remove(trigger) + heldOnScreen.remove(trigger)?.let { onScreen(it, trigger, false, true) } + sources.remove(trigger)?.close() + if (setup != null) sources[trigger] = InputSurfaceSource(pad, InputRole.PRIMARY, setup.target) + } else if (trigger in pressed) unpress(trigger, cancelled = true) + if (setup != null) this.setups[trigger] = setup else this.setups.remove(trigger) + } + } + + fun onKey(event: KeyEvent, enabled: () -> Boolean): Boolean { + if (event.keyCode != AirTrigger.LEFT.keyCode && event.keyCode != AirTrigger.RIGHT.keyCode) return false + val trigger = AirTrigger.of(event.keyCode, event.device) ?: return false + return onKey(trigger, event.action, event.repeatCount, event.action == KeyEvent.ACTION_DOWN && enabled()) + } + + fun onKey(trigger: AirTrigger, action: Int, repeatCount: Int, enabled: Boolean): Boolean { + val source = sources[trigger] + when (action) { + KeyEvent.ACTION_DOWN -> if (source != null && enabled && repeatCount == 0 && held.add(trigger)) { + touched(trigger, true) + val setup = setups[trigger] + if (setup?.action == AirTriggerAction.LATCH && trigger in pressed) unpress(trigger, cancelled = false) + else if (trigger !in pressed) { + press(trigger, source) + if (setup?.action == AirTriggerAction.RAPID) rapid(trigger, 500L / setup.rate.clicksPerSecond) + } + } + KeyEvent.ACTION_UP -> if (held.remove(trigger)) { + touched(trigger, false) + if (setups[trigger]?.action != AirTriggerAction.LATCH) { + stop(trigger) + if (trigger in pressed) unpress(trigger, cancelled = false) + } + return true + } + } + return source != null + } + + private fun rapid(trigger: AirTrigger, halfPeriod: Long) { + val tick = object : Runnable { + override fun run() { + if (trigger in pressed) unpress(trigger, cancelled = false) else sources[trigger]?.let { press(trigger, it) } + handler.postDelayed(this, halfPeriod) + } + } + timers[trigger] = tick + handler.postDelayed(tick, halfPeriod) + } + + private fun stop(trigger: AirTrigger) { + timers.remove(trigger)?.let(handler::removeCallbacks) + } + + private fun press(trigger: AirTrigger, source: InputSurfaceSource) { + pressed += trigger + if (source.element == setups[trigger]?.element && onScreen(source.element.id, trigger, true, false)) { + heldOnScreen[trigger] = source.element.id + // The router counts held keys, so a toggle latched while its button was hidden is released before the button takes over. + if (source.latched) source.release() + } else source.update(1f) + } + + private fun unpress(trigger: AirTrigger, cancelled: Boolean) { + pressed -= trigger + heldOnScreen.remove(trigger)?.let { onScreen(it, trigger, false, cancelled) } + ?: sources[trigger]?.let { if (cancelled) it.cancel() else it.update(0f) } + } + + fun release() { + AirTrigger.entries.forEach(::stop) + held.toList().forEach { held.remove(it); touched(it, false) } + pressed.toList().forEach { unpress(it, cancelled = true) } + sources.values.forEach { it.release() } + } + + fun close() { + release() + sources.values.forEach { it.close() } + sources.clear() + setups.clear() + } +} 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/EnhancedSessionLogShare.kt b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt index c9c55f9c27..566f2bf20f 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt @@ -268,7 +268,7 @@ internal object EnhancedSessionLogShare { val out = outputDirectory.apply { deleteRecursively(); mkdirs() } val redactionLearningComplete = LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context)) val discovery = collect(context, folder, limits.maxDiscoveredFiles, legacy = true) - val candidates = discovery.candidates.filter { it.linePrefix == null } + val candidates = discovery.candidates.filter { it.linePrefix == null }.sortedBy(::sharePriority) if (candidates.isEmpty()) { out.deleteRecursively() return null @@ -697,15 +697,6 @@ internal object EnhancedSessionLogShare { Category.GAMES, "DROIDDECK_DIAGNOSTICS event=game_", ) } - if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) { - val steam = File(SessionPrefs.activeSteamRoot(context), "logs") - val scan = directFiles(steam, remaining(maxFiles, out.size)) - truncated = truncated || scan.truncated - partial = partial || scan.partial - scan.files.forEach { - add(it, steam, "${folder.name}/steam/${it.name}", "live-steam") - } - } val logs = LinuxRuntime.logDir(context) for ((name, root) in listOf(SessionLogShare.STORES_DIR to File(logs, SessionLogShare.STORES_DIR), SessionPaths.TOOLS_DIR to File(logs, SessionPaths.TOOLS_DIR))) { val scan = directFiles(root, STORE_LOG_SCAN) @@ -742,9 +733,24 @@ internal object EnhancedSessionLogShare { if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach add(file, folder, "${folder.name}/$relative", "session") } + if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) { + val steam = File(SessionPrefs.activeSteamRoot(context), "logs") + val scan = directFiles(steam, remaining(maxFiles, out.size)) + truncated = truncated || scan.truncated + partial = partial || scan.partial + scan.files.forEach { + add(it, steam, "${folder.name}/steam/${it.name}", "live-steam") + } + } return CollectionResult(out.values.toList(), truncated, partial) } + private fun sharePriority(candidate: Candidate): Int = when { + candidate.origin == "session-critical" -> 0 + candidate.origin == "session" && candidate.category == Category.GAMES -> 1 + else -> 2 + } + private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0) private fun walk(root: File, limit: Int): ScanResult { 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/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt index 412fc79627..756a721a7a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -9,6 +9,8 @@ import com.droiddeck.launcher.core.Downloader import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.NativeGuest +import com.droiddeck.launcher.storage.SteamStorage +import com.droiddeck.launcher.stores.steam.SteamClient import java.io.File import java.util.Locale import org.json.JSONArray @@ -34,7 +36,9 @@ object ProtonExtras { private var replacing = false class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex, - val prereleases: Boolean = false) + val prereleases: Boolean = false, val x86_64: Boolean = false, val label: Int = 0) { + val arch: String get() = if (x86_64) "x86-64" else "ARM64" + } internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long, val sha256: String? = null, val releaseName: String = tag) @@ -42,11 +46,13 @@ object ProtonExtras { const val OWN = "droiddeck" const val BIONIC = "bionic" + const val ANTICHEAT = "anticheat" val tools = listOf( Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")), Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")), Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*aarch64\\.tar\\.(gz|xz)$")), + Tool(ANTICHEAT, "DroidDeck-Proton x86-64", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*x86_64\\.tar\\.(gz|xz)$"), x86_64 = true, label = R.string.pextra_anticheat), // Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases. No-proot only. Tool(BIONIC, "DroidDeck-Bionic", "DroidDeck-Bionic", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Bionic-.*aarch64\\.tar\\.(gz|xz)$"), prereleases = true), ) @@ -66,11 +72,14 @@ object ProtonExtras { internal fun installedIn(dir: File, tool: Tool): List = dir.listFiles() - ?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && usable(it) } + ?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && x86_64Build(it) == tool.x86_64 && usable(it) } ?.map { it.name } ?.sortedWith { a, b -> compareVersions(a, b) } ?: emptyList() + internal fun x86_64Build(dir: File): Boolean = + File(dir, "files/lib/wine/x86_64-unix").isDirectory && !File(dir, "files/bin-arm64").isDirectory + private fun usable(dir: File): Boolean { val manifest = runCatching { File(dir, "toolmanifest.vdf").readText() }.getOrNull() ?: return false val command = Regex("\\\"commandline\\\"\\s+\\\"/?([^\\\" ]+)").find(manifest)?.groupValues?.getOrNull(1) ?: return false @@ -108,15 +117,31 @@ object ProtonExtras { fun update(context: Context, tool: Tool): String? = updateFor(installedTags(context, tool), cachedLatest(context, tool)) - fun missing(context: Context, tool: Tool): String? = - if (tool.id == OWN && !declined(context) && installedAll(context, tool).isEmpty()) cachedLatest(context, tool) else null + fun missing(context: Context, tool: Tool): String? = missing(context, tool) { antiCheatRuntimeInstalled(context) } + + internal fun missing(context: Context, tool: Tool, antiCheat: () -> Boolean): String? = when { + declined(context, tool.id) || installedAll(context, tool).isNotEmpty() -> null + tool.id == OWN || tool.id == ANTICHEAT && antiCheat() -> cachedLatest(context, tool) + else -> null + } + + private fun antiCheatRuntimeInstalled(context: Context): Boolean = + antiCheatRuntimeIn(listOf("arm64", SteamClient.X86_64).flatMap { arch -> + runCatching { SteamClient.libraries(context, arch).map { it.host } }.getOrDefault(emptyList()) + } + listOfNotNull(GameStorage.effective(context)?.let { File(it.path) }, GameStorage.x64CardLibrary(context))) + + internal fun antiCheatRuntimeIn(libraries: List): Boolean = libraries.any { library -> + ANTICHEAT_RUNTIMES.any { File(library, "steamapps/appmanifest_$it.acf").isFile } + } + + private val ANTICHEAT_RUNTIMES = listOf(SteamStorage.EAC_RUNTIME, SteamStorage.BATTLEYE_RUNTIME) private fun choices(context: Context) = context.getSharedPreferences("proton-auto-updates", Context.MODE_PRIVATE) - fun declined(context: Context): Boolean = choices(context).getBoolean("$OWN.declined", false) + fun declined(context: Context, id: String = OWN): Boolean = choices(context).getBoolean("$id.declined", false) - fun setDeclined(context: Context, declined: Boolean) { - choices(context).edit().putBoolean("$OWN.declined", declined).apply() + fun setDeclined(context: Context, declined: Boolean, id: String = OWN) { + choices(context).edit().putBoolean("$id.declined", declined).apply() } fun cachedLatest(context: Context, tool: Tool): String? = @@ -220,8 +245,8 @@ object ProtonExtras { if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue - // DroidDeck-Bionic only: the guest finds no default for a deleted Bionic build and falls back to DroidDeck-Proton - if (tool.id == BIONIC && runCatching { ProtonDefault.moveDefault(context, setOf(old), newest) }.onFailure { Log.w(TAG, "default pick of $old", it) }.isFailure) continue + // DroidDeck-Bionic and the x86-64 build: the guest finds no default for a deleted build and falls back to DroidDeck-Proton + if ((tool.id == BIONIC || tool.id == ANTICHEAT) && runCatching { ProtonDefault.moveDefault(context, setOf(old), newest) }.onFailure { Log.w(TAG, "default pick of $old", it) }.isFailure) continue if (deleteTool(context, old)) ComponentsManager.forgetProton(context, old) else Log.w(TAG, "could not remove $old") } @@ -288,7 +313,7 @@ object ProtonExtras { } private fun prefetchNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { - val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name) + val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name, tool.arch) val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() } val archive = File(downloads, "${tool.id}-${asset.name}") if (asset.size > 0 && archive.length() > asset.size) archive.delete() @@ -305,7 +330,7 @@ object ProtonExtras { if (SessionState.running) return context.getString(R.string.pextra_stop_session) if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required) - val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name) + val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name, tool.arch) val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() } val archive = File(downloads, "${tool.id}-${asset.name}") if (asset.size > 0 && archive.length() > asset.size) archive.delete() @@ -374,7 +399,7 @@ object ProtonExtras { archive.delete() unqueue(context, tool) record(context, tool, placed, asset.tag) - if (tool.id == OWN || tool.id == BIONIC) replaceOlder(context, tool) + if (tool.id == OWN || tool.id == BIONIC || tool.id == ANTICHEAT) replaceOlder(context, tool) if (EsyncPacks.enabled(context)) { onProgress(context.getString(R.string.esync_fetching), -1) try { 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 0858e6fefd..d28ae192db 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( @@ -130,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", @@ -154,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", @@ -332,6 +340,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") @@ -358,6 +367,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") @@ -417,6 +427,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 @@ -880,6 +926,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..24ed5f199b 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,18 @@ 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 } + fun layerFrameRate(ownLimit: Int, refreshHz: Float, blackFrameInsertion: Boolean): Float = + if (ownLimit > 0 && !blackFrameInsertion) ownLimit.toFloat() else refreshHz + + /** 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", @@ -1912,24 +2014,84 @@ object SessionPrefs { sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply() } + private const val GAME_UPSCALER_OVERRIDES_KEY = "upscaler.gameOverrides" + + private fun gameUpscalerOverrides(context: Context): JSONObject = runCatching { + JSONObject(prefs(context).getString(GAME_UPSCALER_OVERRIDES_KEY, null) ?: "{}") + }.getOrDefault(JSONObject()) + + private fun legacyScreenEffectsUpscaler(context: Context, profileId: String): Int? = + runCatching { + val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") + val profile = profiles.optJSONObject(profileId) + if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) { + profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1).takeIf { it >= 0 } + } else null + }.getOrNull()?.let(::canonicalUpscaler) + + private fun clearLegacyScreenEffectsUpscaler(context: Context, profileId: String) { + val sessionPrefs = prefs(context) + val profiles = runCatching { + JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") + }.getOrNull() ?: return + val profile = profiles.optJSONObject(profileId) ?: return + if (!profile.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)) return + profile.remove(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) + if (profile.length() == 0) profiles.remove(profileId) + sessionPrefs.edit().apply { + if (profiles.length() == 0) remove(SCREEN_EFFECTS_PROFILES_KEY) + else putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()) + }.apply() + } + + fun hasGameUpscalerOverride(context: Context, gameId: String): Boolean { + if (gameId.isBlank()) return false + val stored = gameUpscalerOverrides(context) + return (stored.has(gameId) && stored.optInt(gameId, -1) >= 0) || + legacyScreenEffectsUpscaler(context, "game:$gameId") != null + } + + fun setGameUpscaler(context: Context, gameId: String, mode: Int) { + if (gameId.isBlank()) return + val overrides = gameUpscalerOverrides(context) + overrides.put(gameId, canonicalUpscaler(mode)) + prefs(context).edit().putString(GAME_UPSCALER_OVERRIDES_KEY, overrides.toString()).apply() + clearLegacyScreenEffectsUpscaler(context, "game:$gameId") + } + + fun clearGameUpscaler(context: Context, gameId: String) { + if (gameId.isBlank()) return + val sessionPrefs = prefs(context) + val overrides = gameUpscalerOverrides(context) + if (overrides.has(gameId)) { + overrides.remove(gameId) + sessionPrefs.edit().apply { + if (overrides.length() == 0) remove(GAME_UPSCALER_OVERRIDES_KEY) + else putString(GAME_UPSCALER_OVERRIDES_KEY, overrides.toString()) + }.apply() + } + clearLegacyScreenEffectsUpscaler(context, "game:$gameId") + } + fun hasScreenEffectsUpscalerOverride(context: Context, profileId: String?): Boolean { if (profileId.isNullOrBlank()) return false - return runCatching { - val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") - profiles.optJSONObject(profileId)?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true - }.getOrDefault(false) + if (profileId.startsWith("game:")) { + return hasGameUpscalerOverride(context, profileId.removePrefix("game:")) + } + return legacyScreenEffectsUpscaler(context, profileId) != null } fun screenEffectsUpscaler(context: Context, profileId: String?): Int { if (profileId.isNullOrBlank()) return upscaler(context) - val stored = runCatching { - val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") - val profile = profiles.optJSONObject(profileId) - if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) { - profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1) - } else -1 - }.getOrDefault(-1) - return if (stored >= 0) canonicalUpscaler(stored) else upscaler(context) + if (profileId.startsWith("game:")) { + val gameId = profileId.removePrefix("game:") + val overrides = gameUpscalerOverrides(context) + if (overrides.has(gameId)) { + val stored = overrides.optInt(gameId, -1) + if (stored >= 0) return canonicalUpscaler(stored) + } + } + return legacyScreenEffectsUpscaler(context, profileId) ?: upscaler(context) } fun setScreenEffectsUpscaler(context: Context, profileId: String?, mode: Int) { @@ -1937,6 +2099,10 @@ object SessionPrefs { setUpscaler(context, mode) return } + if (profileId.startsWith("game:")) { + setGameUpscaler(context, profileId.removePrefix("game:"), mode) + return + } val sessionPrefs = prefs(context) val profiles = runCatching { JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") @@ -1973,6 +2139,7 @@ object SessionPrefs { val profiles = runCatching { JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") }.getOrElse { JSONObject() } + if (profileId.startsWith("game:")) clearGameUpscaler(context, profileId.removePrefix("game:")) if (!profiles.has(profileId)) return profiles.remove(profileId) sessionPrefs.edit().apply { @@ -2117,6 +2284,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 aa25698c28..8a019a0401 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) @@ -897,11 +945,15 @@ class SessionService : Service() { return } if (gen == sessionGen && SessionState.running) { + val workers = ownWorkers suspendController = SessionSuspendController( sessionRoot = { sessionPid }, + // Programs handed off to worker processes are not descendants of the session root, and + // the clock shift applied at resume would move their monotonic time backwards. helperRoots = { components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } + - listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 }) + listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 }) + + (if (workers > 0) com.droiddeck.launcher.runtime.GuestWorkers.guestPids(workers) else emptyList()) }, suspendAudio = { if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink") @@ -993,7 +1045,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)) @@ -1111,7 +1164,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 +1590,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 +1615,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 +1790,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 +2387,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 +2457,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 +2467,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 +2786,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 +2796,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 +2807,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/SessionVisibilityPolicy.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt index 90630ebbcd..79cc595af9 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt @@ -1,6 +1,12 @@ package com.droiddeck.launcher.session internal object SessionVisibilityPolicy { + fun shouldCloseSecondScreenOnStop( + screenOff: Boolean, + dockedDrawerOpen: Boolean, + attachmentPickerOpen: Boolean, + ): Boolean = !screenOff && !(dockedDrawerOpen && attachmentPickerOpen) + fun isHidden( activityStarted: Boolean, defaultDisplayOn: Boolean, 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/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/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..b2793e5ba1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -5,7 +5,9 @@ import android.content.ContextWrapper import android.os.Build import android.view.KeyEvent import android.view.WindowManager +import androidx.activity.compose.BackHandler import androidx.activity.compose.LocalActivityResultRegistryOwner +import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.expandVertically @@ -50,12 +52,12 @@ import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.Send import androidx.compose.material.icons.outlined.Extension -import androidx.compose.material.icons.outlined.PhotoCamera import androidx.compose.material.icons.outlined.MicOff import androidx.compose.material.icons.outlined.Mic import androidx.compose.material.icons.outlined.Add import androidx.compose.material.icons.outlined.ArrowDownward import androidx.compose.material.icons.outlined.AttachFile +import androidx.compose.material.icons.outlined.Keyboard import androidx.compose.material.icons.outlined.Terminal import androidx.compose.material.icons.outlined.Build import androidx.compose.material.icons.outlined.Close @@ -79,6 +81,7 @@ import androidx.compose.runtime.MutableState import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -108,6 +111,7 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.testTag @@ -301,7 +305,7 @@ private fun AgentPageContent( readingBack = false scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) } } - val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() && + val hidden = !composer.focused && !composer.tray && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() && AgentHost.approvals.isEmpty() var listHeight by remember { mutableIntStateOf(0) } Box( @@ -319,6 +323,7 @@ private fun AgentPageContent( awaitEachGesture { awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE + composer.tray = false // Forced: the unforced path walks the focus chain and throws ("ActiveParent with no focused child") when a tap lands while focus is moving. if (composer.focused) focusManager.clearFocus(force = true) } @@ -344,6 +349,12 @@ private fun AgentPageContent( @Stable private class ComposerState { var focused by mutableStateOf(false) + /** The photo tray stands in for the keyboard, at the height the keyboard last had. */ + var tray by mutableStateOf(false) + var keyboardHeight by mutableStateOf(0.dp) + /** Tray photos copied, or being copied, for this conversation, so reopening the tray keeps their marks and copies nothing twice. */ + val photoCopies = mutableStateMapOf() + val photosCopying = mutableStateMapOf() var focusRequests by mutableIntStateOf(0) private set private var consumedFocusRequests by mutableIntStateOf(0) @@ -390,7 +401,7 @@ private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstCon .clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"), ) { val mode = AgentHost.harness.permissions.drop(1).firstOrNull { it.id == AgentHost.permission }?.let { stringResource(it.label) } - val parts = if (compact) listOfNotNull(mode ?: model) + val parts = if (compact) listOf(model) else listOfNotNull( AgentHost.harness.name, model, AgentHost.effort, mode, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans }, @@ -532,7 +543,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) @@ -748,6 +759,8 @@ private fun AgentComposer( if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send AgentHost.send(context, text, AgentAttachments.pending.toList()) AgentAttachments.pending.clear() + composer.photosCopying.clear() + composer.tray = false onSent() } } @@ -813,7 +826,34 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState composer.keyboardHeight) composer.keyboardHeight = height + } + LaunchedEffect(hideAttach) { if (hideAttach) composer.tray = false } + LaunchedEffect(AgentHost.chat) { + composer.photoCopies.clear() + composer.photosCopying.clear() + } + // BackHandler throws where the host provides no back dispatcher: the front end and the floating pet. + if (LocalOnBackPressedDispatcherOwner.current != null) BackHandler(composer.tray) { composer.tray = false } + val focusManager = LocalFocusManager.current + val files = if (picks) rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { + AgentAttachments.picking = false + attachUris(context, it) + } else null + val toggleTray = { + if (composer.tray) { + composer.tray = false + composer.open() + } else { + focusManager.clearFocus(force = true) + composer.tray = true + } + } BoxWithConstraints( Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface) .border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp), @@ -841,6 +881,7 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState 0.dp) composer.keyboardHeight else 280.dp).coerceAtLeast(160.dp).coerceAtMost(most) + AgentPhotoTray(height, composer.photoCopies, composer.photosCopying, files?.let { { AgentAttachments.pick { it.launch(arrayOf("*/*")) } } }) + } } /** @@ -974,51 +1018,15 @@ private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit, onSend: () -> Un } } -/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */ +/** Opens the photo tray in place of the keyboard; while it is open, brings the keyboard back. */ @Composable -private fun GameFrameButton() { - val context = LocalContext.current +private fun AttachButton(trayOpen: Boolean, onClick: () -> Unit) { val pal = LocalPalette.current - RoundButton(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), pal.surfaceVariant, pal.onBackground, "agent-game-frame") { - val grab = AgentAttachments.gameFrame ?: return@RoundButton - val chat = AgentHost.chat - grab frame@{ frame -> - if (frame == null) { - android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show() - return@frame - } - Thread({ - val path = AgentAttachments.saveFrame(context, chat, frame) - frame.recycle() - android.os.Handler(android.os.Looper.getMainLooper()).post { - when { - path == null -> android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show() - AgentHost.chat == chat -> AgentAttachments.pending.add(path) - else -> AgentAttachments.discard(context, listOf(path)) - } - } - }, "agent-game-frame").start() - } - } -} - -@Composable -private fun AttachButton() { - val context = LocalContext.current - val pal = LocalPalette.current - val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> - if (uris.isEmpty()) return@rememberLauncherForActivityResult - val chat = AgentHost.chat - Thread({ - val paths = AgentAttachments.copy(context, chat, uris) - android.os.Handler(android.os.Looper.getMainLooper()).post { - if (AgentHost.chat == chat) AgentAttachments.pending.addAll(paths) else AgentAttachments.discard(context, paths) - } - }, "agent-attach").start() - } - RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") { - runCatching { picker.launch(arrayOf("*/*")) } - } + RoundButton( + if (trayOpen) Icons.Outlined.Keyboard else Icons.Outlined.AttachFile, + stringResource(if (trayOpen) R.string.agent_keyboard else R.string.agent_attach), + if (trayOpen) pal.primary else pal.surfaceVariant, if (trayOpen) pal.onPrimary else pal.onBackground, "agent-attach", onClick = onClick, + ) } @Composable 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/AgentPhotoTray.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPhotoTray.kt new file mode 100644 index 0000000000..d6c5dabe68 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPhotoTray.kt @@ -0,0 +1,280 @@ +package com.droiddeck.launcher.ui + +import android.Manifest +import android.content.ContentUris +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import android.provider.Settings +import android.widget.Toast +import androidx.activity.compose.LocalActivityResultRegistryOwner +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.GridItemSpan +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Check +import androidx.compose.material.icons.outlined.FolderOpen +import androidx.compose.material.icons.outlined.PhotoCamera +import androidx.compose.material.icons.outlined.PhotoLibrary +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.SnapshotStateMap +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.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalLifecycleOwner +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import coil.compose.AsyncImage +import coil.request.ImageRequest +import com.droiddeck.launcher.R +import com.droiddeck.launcher.agent.AgentAttachments +import com.droiddeck.launcher.agent.AgentHost +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** The device's photos, newest first, as MediaStore lets the app see them. */ +internal object AgentPhotos { + enum class Access { NONE, SELECTED, ALL } + + /** Android stops showing the request after repeated denials and answers it at once, so a denied request sends later ones to Settings. */ + var refused = false + + fun permissions(sdk: Int = Build.VERSION.SDK_INT): Array = when { + sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) + sdk >= Build.VERSION_CODES.TIRAMISU -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES) + else -> arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE) + } + + fun access(context: Context): Access { + fun granted(permission: String) = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED + val all = permissions().first() + return when { + Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager() -> Access.ALL + granted(all) -> Access.ALL + Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && granted(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) -> Access.SELECTED + else -> Access.NONE + } + } + + class Photo(val uri: Uri, val name: String) + + fun recent(context: Context, limit: Int = 300): List = runCatching { + val images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI + context.contentResolver.query( + images, arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME), null, null, "${MediaStore.Images.Media.DATE_ADDED} DESC", + )?.use { c -> + buildList { + while (size < limit && c.moveToNext()) add(Photo(ContentUris.withAppendedId(images, c.getLong(0)), c.getString(1).orEmpty())) + } + }.orEmpty() + }.getOrDefault(emptyList()) +} + +/** + * Copies [uris] into the conversation's attachments off the main thread, then hands [onCopied] what was attached: nothing if the + * conversation changed meanwhile or [current] says the copy was superseded. + */ +internal fun attachUris(context: Context, uris: List, current: () -> Boolean = { true }, onCopied: (List>) -> Unit = {}) { + if (uris.isEmpty()) return + val chat = AgentHost.chat + Thread({ + val copied = uris.mapNotNull { uri -> AgentAttachments.copy(context, chat, listOf(uri)).firstOrNull()?.let { uri to it } } + android.os.Handler(android.os.Looper.getMainLooper()).post { + val paths = copied.map { it.second } + if (AgentHost.chat == chat && current()) { + AgentAttachments.pending.addAll(paths) + onCopied(copied) + } else { + AgentAttachments.discard(context, paths) + onCopied(emptyList()) + } + } + }, "agent-attach").start() +} + +/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */ +private fun attachGameFrame(context: Context) { + val grab = AgentAttachments.gameFrame ?: return + val chat = AgentHost.chat + grab frame@{ frame -> + if (frame == null) { + Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show() + return@frame + } + Thread({ + val path = AgentAttachments.saveFrame(context, chat, frame) + frame.recycle() + android.os.Handler(android.os.Looper.getMainLooper()).post { + when { + path == null -> Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show() + AgentHost.chat == chat -> AgentAttachments.pending.add(path) + else -> AgentAttachments.discard(context, listOf(path)) + } + } + }, "agent-game-frame").start() + } +} + +/** Shown in place of the keyboard: recent photos to tap onto the message, and the system picker for anything else. */ +@Composable +internal fun AgentPhotoTray(height: Dp, copies: SnapshotStateMap, copying: SnapshotStateMap, onFiles: (() -> Unit)?) { + val context = LocalContext.current + val pal = LocalPalette.current + var access by remember { mutableStateOf(AgentPhotos.access(context)) } + var photos by remember { mutableStateOf?>(null) } + var reloads by remember { mutableStateOf(0) } + // A window no activity owns (the floating pet's chat) cannot ask for a permission, so it sends the user to the app's settings. + val launcher = if (LocalActivityResultRegistryOwner.current != null) { + rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { + AgentAttachments.picking = false + access = AgentPhotos.access(context) + if (access == AgentPhotos.Access.NONE) AgentPhotos.refused = true + reloads++ + } + } else null + val request = { + if (launcher != null && !AgentPhotos.refused) { + AgentAttachments.pick { launcher.launch(AgentPhotos.permissions()) } + } else { + val details = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.packageName)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + runCatching { context.startActivity(details) } + } + Unit + } + // Access can change in Settings, and new pictures arrive, while the app is in the background. + val lifecycle = LocalLifecycleOwner.current.lifecycle + DisposableEffect(lifecycle) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) { + access = AgentPhotos.access(context) + reloads++ + } + } + lifecycle.addObserver(observer) + onDispose { lifecycle.removeObserver(observer) } + } + LaunchedEffect(access, reloads) { + photos = if (access == AgentPhotos.Access.NONE) emptyList() else withContext(Dispatchers.IO) { AgentPhotos.recent(context) } + } + LazyVerticalGrid( + GridCells.Adaptive(96.dp), + Modifier.fillMaxWidth().height(height).padding(top = 8.dp).testTag("agent-photo-tray"), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + if (AgentAttachments.gameFrame != null) item { + TrayTile(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), "agent-game-frame") { attachGameFrame(context) } + } + if (onFiles != null) item { TrayTile(Icons.Outlined.FolderOpen, stringResource(R.string.agent_attach_files), "agent-attach-files", onFiles) } + if (access != AgentPhotos.Access.ALL) item { + TrayTile( + Icons.Outlined.PhotoLibrary, + stringResource(if (access == AgentPhotos.Access.NONE) R.string.agent_photos_allow else R.string.agent_photos_more), + "agent-photos-allow", + onClick = request, + ) + } + val list = photos + if (list != null && list.isEmpty() && access != AgentPhotos.Access.NONE) item(span = { GridItemSpan(maxLineSpan) }) { + Text( + stringResource(R.string.agent_photos_empty), fontSize = 13.sp, color = pal.onSurfaceVariant, textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth().padding(16.dp), + ) + } + items(list.orEmpty(), key = { it.uri.toString() }) { photo -> + val uri = photo.uri + val path = copies[uri] + val selected = path != null && path in AgentAttachments.pending + Box( + Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant) + .then(if (selected) Modifier.border(3.dp, pal.primary, Shape12) else Modifier) + .clickable { + when { + selected -> AgentAttachments.pending.remove(path) + path != null && AgentAttachments.host(context, path).exists() -> AgentAttachments.pending.add(path) + uri in copying -> Unit + else -> { + // Leaving the conversation clears the markers, so a copy started before that is no longer current even back in it. + val copy = Any() + copying[uri] = copy + attachUris(context, listOf(uri), current = { copying[uri] === copy }) { copied -> + copied.forEach { (u, p) -> copies[u] = p } + if (copying[uri] === copy) copying.remove(uri) + } + } + } + }.semantics { + contentDescription = photo.name + this.selected = selected + }.testTag("agent-photo"), + ) { + AsyncImage( + model = ImageRequest.Builder(context).data(uri).size(320).build(), contentDescription = null, + contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize(), + ) + if (selected) Box( + contentAlignment = Alignment.Center, + modifier = Modifier.align(Alignment.TopEnd).padding(6.dp).size(22.dp).clip(CircleShape).background(pal.primary), + ) { + Icon(Icons.Outlined.Check, null, tint = pal.onPrimary, modifier = Modifier.size(16.dp)) + } + } + } + } +} + +@Composable +private fun TrayTile(icon: ImageVector, label: String, tag: String, onClick: () -> Unit) { + val pal = LocalPalette.current + Column( + horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, + modifier = Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant).clickable(onClick = onClick).padding(8.dp).testTag(tag), + ) { + Icon(icon, null, tint = pal.onBackground, modifier = Modifier.size(26.dp)) + Text( + label, fontSize = 12.sp, color = pal.onBackground, textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(top = 6.dp), + ) + } +} 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/AirTriggerGlow.kt b/app/src/main/java/com/droiddeck/launcher/ui/AirTriggerGlow.kt new file mode 100644 index 0000000000..d4d734fa02 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AirTriggerGlow.kt @@ -0,0 +1,62 @@ +package com.droiddeck.launcher.ui + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.LinearGradient +import android.graphics.Paint +import android.graphics.Shader +import android.view.View +import android.widget.FrameLayout +import com.droiddeck.launcher.input.AirTrigger +import java.util.EnumMap +import java.util.EnumSet + +@SuppressLint("ViewConstructor") +class AirTriggerGlow(context: Context) : View(context) { + private val lit = EnumSet.noneOf(AirTrigger::class.java) + private val density = resources.displayMetrics.density + private val paints = EnumMap(AirTrigger::class.java) + + init { + isClickable = false + isFocusable = false + importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO + layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT) + val top = TOP_DP * density + for ((trigger, look) in mapOf(AirTrigger.LEFT to LEFT, AirTrigger.RIGHT to RIGHT)) { + val (color, fade) = look + paints[trigger] = Paint().apply { + shader = LinearGradient(0f, top, 0f, top + HEIGHT_DP * density, + fade.map { Color.argb(it, Color.red(color), Color.green(color), Color.blue(color)) }.toIntArray(), + STOPS, Shader.TileMode.CLAMP) + } + } + } + + fun show(trigger: AirTrigger, on: Boolean) { + if (if (on) lit.add(trigger) else lit.remove(trigger)) invalidate() + } + + override fun onDraw(canvas: Canvas) { + val width = WIDTH_DP * density + val margin = SIDE_DP * density + val top = TOP_DP * density + for (trigger in lit) { + val left = if (trigger == AirTrigger.LEFT) margin else this.width - margin - width + canvas.drawRect(left, top, left + width, top + HEIGHT_DP * density, paints.getValue(trigger)) + } + } + + private companion object { + // Game Space's tgk_*_top_pressed images and their landscape placement on a 2688 x 1216 RedMagic screen. + const val WIDTH_DP = 78f + const val HEIGHT_DP = 33f + const val SIDE_DP = 37f + const val TOP_DP = 2f + val STOPS = floatArrayOf(0f, 0.04f, 0.05f, 0.2f, 0.4f, 0.6f, 0.8f, 1f) + val LEFT = Color.rgb(230, 23, 57) to listOf(255, 255, 150, 102, 55, 36, 18, 0) + val RIGHT = Color.rgb(23, 91, 230) to listOf(255, 255, 151, 94, 41, 27, 14, 0) + } +} 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/ControllerHaptics.kt b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt index da1d8d4bb4..b954512fff 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt @@ -24,7 +24,11 @@ object ControllerHaptics { tick(context) } - fun tick(context: Context) { + fun tick(context: Context) = vibrate(context, VibrationEffect.EFFECT_TICK, 10) + + fun click(context: Context) = vibrate(context, VibrationEffect.EFFECT_CLICK, 20) + + private fun vibrate(context: Context, predefined: Int, fallbackMs: Long) { val vibrator = if (Build.VERSION.SDK_INT >= 31) { context.getSystemService(VibratorManager::class.java)?.defaultVibrator } else { @@ -32,11 +36,11 @@ object ControllerHaptics { } ?: return if (!vibrator.hasVibrator()) return if (Build.VERSION.SDK_INT >= 29) { - vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK)) + vibrator.vibrate(VibrationEffect.createPredefined(predefined)) } else if (Build.VERSION.SDK_INT >= 26) { - vibrator.vibrate(VibrationEffect.createOneShot(10, VibrationEffect.DEFAULT_AMPLITUDE)) + vibrator.vibrate(VibrationEffect.createOneShot(fallbackMs, VibrationEffect.DEFAULT_AMPLITUDE)) } else { - @Suppress("DEPRECATION") vibrator.vibrate(10) + @Suppress("DEPRECATION") vibrator.vibrate(fallbackMs) } } } 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 d14086ffc5..22367d7205 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 fcfc591951..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) 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 d804a4fa56..4047781350 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 @@ -813,12 +881,80 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost com.droiddeck.launcher.gpu.FrameGen.hasGameOverride(context, it) } ?: false) } + val scalingFilterChoices = SessionPrefs.upscalerChoices(context) + var gameUpscaler by remember(frameGenProfileKey) { + mutableStateOf(frameGenProfileKey?.let { + SessionPrefs.screenEffectsUpscaler(context, "game:$it") + } ?: SessionPrefs.upscaler(context)) + } + var gameUpscalerOverride by remember(frameGenProfileKey) { + mutableStateOf(frameGenProfileKey?.let { SessionPrefs.hasGameUpscalerOverride(context, it) } ?: false) + } + val lifecycleOwner = LocalLifecycleOwner.current + DisposableEffect(lifecycleOwner, frameGenProfileKey) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) { + frameGenProfileKey?.let { key -> + gameUpscaler = SessionPrefs.screenEffectsUpscaler(context, "game:$key") + gameUpscalerOverride = SessionPrefs.hasGameUpscalerOverride(context, key) + } + } + } + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + } var wincompOpen by remember(wincompKey) { mutableStateOf(null) } val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() } val steamScope = game?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) } 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 scalingFilterMenuContent: @Composable () -> Unit = { + val key = frameGenProfileKey + if (key != null) ScalingFilterMenu( + mode = gameUpscaler, + options = scalingFilterChoices, + hasGameOverride = gameUpscalerOverride, + onPick = { mode -> + SessionPrefs.setGameUpscaler(context, key, mode) + gameUpscaler = SessionPrefs.screenEffectsUpscaler(context, "game:$key") + gameUpscalerOverride = SessionPrefs.hasGameUpscalerOverride(context, key) + }, + onResetGame = { + SessionPrefs.clearGameUpscaler(context, key) + gameUpscaler = SessionPrefs.upscaler(context) + gameUpscalerOverride = false + }, + gameName = game?.name, + ) + } 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 +976,18 @@ 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 (frameGenProfileKey != null) add { m -> + Box(m) { + SettingCard( + stringResource(R.string.display_filter), + scalingFilterChoices.firstOrNull { it.first == gameUpscaler }?.second ?: scalingFilterChoices.first().second, + "card:scaling-filter", Modifier.fillMaxSize(), + ) { + host.open = if (host.open == "scaling-filter") null else "scaling-filter" + } } } 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 +1019,16 @@ 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() + } + } + if (host.open == "scaling-filter") { + Box(Modifier.fillMaxWidth().padding(top = 4.dp)) { + scalingFilterMenuContent() + } + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt index 4245236747..adfa9eebcd 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -308,7 +308,8 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo Box( contentAlignment = Alignment.Center, modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (pill) 40.dp else if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(shape).background(fill).glideBorder(hot, shape, pal.signal, if (pill) Color.White.copy(alpha = 0.14f) else pal.line2) - .alpha(if (enabled) 1f else 0.5f) + // The label always gets a layer of its own: sharing one with the fill and outline, they did not draw under the agent's latest reply. + .graphicsLayer { alpha = if (enabled) 1f else 0.5f } .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = if (pill) 16.dp else if (compact) 10.dp else 16.dp, vertical = if (pill) 8.dp else if (compact) 7.dp else 11.dp), 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..b57dddc10d 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) } @@ -135,7 +137,7 @@ class InputSurfaceView( val views = owners.values.distinct() owners.clear() for (view in views) { - if (view is HoldButton) { view.cancel(); continue } + if (view is HoldButton) { view.cancelTouches(); continue } val cancel = MotionEvent.obtain(event.downTime, event.eventTime, MotionEvent.ACTION_CANCEL, 0f, 0f, 0) try { view.dispatchTouchEvent(cancel) } finally { cancel.recycle() } } @@ -174,10 +176,23 @@ class InputSurfaceView( val now = android.os.SystemClock.uptimeMillis() val cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0) try { cancelOwners(cancel) } finally { cancel.recycle() } + customCanvas?.let { canvas -> for (i in 0 until canvas.childCount) (canvas.getChildAt(i) as? HoldButton)?.cancel() } forwardedPointers = 0 elementSources.forEach { it.release() } } + /** Presses a button as a finger would, for input from outside the screen; [holder] tells holds apart. */ + fun hold(elementId: String, holder: Int, held: Boolean, cancelled: Boolean = false): Boolean { + val canvas = customCanvas ?: return false + for (i in 0 until canvas.childCount) { + val button = canvas.getChildAt(i) as? HoldButton ?: continue + if ((button.tag as? InputSurfaceElement)?.id != elementId) continue + button.press(-1 - holder, held, cancelled) + return true + } + return false + } + override fun onVisibilityChanged(changedView: View, visibility: Int) { super.onVisibilityChanged(changedView, visibility) if (visibility != VISIBLE) releaseInputs() @@ -185,6 +200,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 +219,7 @@ class InputSurfaceView( child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight) } updateArtworkDpad(this) + updateCrossDpad(this) } override fun dispatchDraw(canvas: Canvas) { @@ -244,11 +261,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 +303,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 +329,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) } @@ -449,17 +495,22 @@ class InputSurfaceView( fun press(pointer: Int, pressed: Boolean, cancelled: Boolean = false) { if (pressed) pointers.add(pointer) else pointers.remove(pointer) - set(pointers.isNotEmpty(), cancelled) + set(pointers.isNotEmpty(), cancelled, touch = pointer >= 0) } fun cancel() { pointers.clear(); set(false, cancelled = true); source?.release() } + fun cancelTouches() { + pointers.removeAll { it >= 0 } + if (pointers.isEmpty()) cancel() + } + override fun onDetachedFromWindow() { cancel(); super.onDetachedFromWindow() } - private fun set(pressed: Boolean, cancelled: Boolean = false) { + private fun set(pressed: Boolean, cancelled: Boolean = false, touch: Boolean = true) { if (down == pressed) return down = pressed - if (pressed) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY) + if (pressed && touch) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY) if (!pressed && cancelled) source?.cancel() else source?.update(if (pressed) 1f else 0f) invalidate() if (artwork != null && this in artworkDpad) customCanvas?.invalidate() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LabBuilds.kt b/app/src/main/java/com/droiddeck/launcher/ui/LabBuilds.kt index 8bfc59306b..c813b4fa1c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LabBuilds.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LabBuilds.kt @@ -3,6 +3,9 @@ package com.droiddeck.launcher.ui import android.text.format.DateUtils import androidx.compose.foundation.background import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -26,8 +29,11 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -41,7 +47,7 @@ import com.droiddeck.launcher.lab.LabOverlay * [onRebuild] offers to build a kept one again for this install, when something can. */ @Composable -internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.Info) -> Unit)? = null) { +internal fun LabBuilds(sessionRunning: Boolean = false, header: (@Composable () -> Unit)? = null, onRebuild: ((LabOverlay.Info) -> Unit)? = null) { val context = LocalContext.current var version by remember { mutableIntStateOf(0) } var busy by remember { mutableStateOf(false) } @@ -54,6 +60,7 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay. val paused = active == null && current != null && LabOverlay.skipped == LabOverlay.SKIPPED_APP_IMAGE val restartFailed = stringResource(R.string.lab_restart_failed) val canRestart = !busy && !sessionRunning + var showKept by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf(false) } /** Android may have given the APK an app image again, which a Lab build cannot load over. */ fun restart() { @@ -73,8 +80,8 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay. val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - Column(Modifier.fillMaxWidth().padding(top = 18.dp)) { - Text( + Column(Modifier.fillMaxWidth().padding(top = if (header == null) 18.dp else 0.dp)) { + if (header != null) header() else Text( stringResource(R.string.lab_builds).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 10.dp), ) @@ -99,7 +106,29 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay. PrimaryButton(stringResource(R.string.lab_restart), compact = true, enabled = canRestart) { restart() } } } - for (build in saved) rows += { + val foldKept = (current != null || pending != null) && saved.isNotEmpty() + if (foldKept) rows += { + val src = remember { MutableInteractionSource() } + val toggle = { showKept = !showKept } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().paneItem("lab:kept") + .background(if (rememberHot(src)) pal.signal.copy(alpha = 0.14f) else Color.Transparent) + .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = toggle) + .controllerConfirm(onClick = toggle) + .padding(horizontal = 14.dp, vertical = 12.dp), + ) { + Text( + pluralStringResource(R.plurals.lab_kept_count, saved.size, saved.size), fontSize = 14.sp, + color = colors.onSurfaceVariant, modifier = Modifier.weight(1f), + ) + Text( + stringResource(if (showKept) R.string.common_hide else R.string.common_show), fontSize = 13.5.sp, + fontWeight = FontWeight.SemiBold, color = pal.signal, + ) + } + } + if (!foldKept || showKept) for (build in saved) rows += { var armed by remember(build.dir) { mutableStateOf(false) } val info = build.info BuildRow( 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/ScalingFilterMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScalingFilterMenu.kt new file mode 100644 index 0000000000..b012bb1292 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScalingFilterMenu.kt @@ -0,0 +1,69 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +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.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.R + +@Composable +internal fun ScalingFilterMenu( + mode: Int, + options: List>, + hasGameOverride: Boolean, + onPick: (Int) -> Unit, + onResetGame: () -> Unit, + gameName: String? = null, +) { + val colors = MaterialTheme.colorScheme + Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) { + val selectedLabel = options.firstOrNull { it.first == mode }?.second ?: mode.toString() + Text( + stringResource( + if (hasGameOverride) R.string.display_filter_game_profile else R.string.display_filter_default_profile, + if (hasGameOverride) gameName.orEmpty() else selectedLabel, + selectedLabel, + ), + color = colors.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(bottom = 6.dp), + ) + options.forEachIndexed { index, (option, label) -> + val selected = mode == option + val pick = { onPick(option) } + OutlinedButton( + onClick = pick, + modifier = Modifier.fillMaxWidth() + .padding(top = if (index == 0) 0.dp else 6.dp) + .controllerConfirm(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) } + } + Text( + stringResource(R.string.display_filter_note), + color = colors.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(top = 6.dp), + ) + OutlinedButton( + onClick = onResetGame, + modifier = Modifier.fillMaxWidth().padding(top = 6.dp) + .controllerConfirm(onClick = onResetGame), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + ) { + Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" 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 ae00595556..a2647da77f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -16,11 +16,15 @@ import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.layout.Layout 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 +41,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 @@ -72,6 +77,7 @@ import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight @@ -81,6 +87,7 @@ 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.systemGestureExclusion import androidx.compose.foundation.ScrollState import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.rememberScrollState @@ -88,6 +95,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 +103,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 +116,11 @@ 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.AirTrigger +import com.droiddeck.launcher.input.AirTriggerAction +import com.droiddeck.launcher.input.AirTriggerLed +import com.droiddeck.launcher.input.RapidFireRate +import com.droiddeck.launcher.input.ControllerPrefs import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.Spring @@ -152,6 +166,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 +190,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 +204,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 +222,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 @@ -219,6 +242,12 @@ private class DrawerFocus { fun forget(page: SessionDrawerPage) { last.remove(page) } } +data class AirTriggerMenu( + val enabled: Boolean, val selected: Map, val buttons: List>, + val vibration: Boolean = false, val screenLight: Boolean = false, val led: AirTriggerLed = AirTriggerLed.STEADY, + val actions: Map = emptyMap(), val rates: Map = emptyMap(), +) + class DrawerActions( val steam: Boolean, val desktop: Boolean, @@ -258,6 +287,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 +336,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,13 +343,24 @@ 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 airTriggers: AirTriggerMenu? = null, + val onAirTriggers: (Boolean) -> Unit = {}, + val onAirTriggerButton: (AirTrigger, String) -> Unit = { _, _ -> }, + val onAirTriggerAction: (AirTrigger, AirTriggerAction) -> Unit = { _, _ -> }, + val onAirTriggerRate: (AirTrigger, RapidFireRate) -> Unit = { _, _ -> }, + val onAirTriggerVibration: (Boolean) -> Unit = {}, + val onAirTriggerScreenLight: (Boolean) -> Unit = {}, + val onAirTriggerLed: (AirTriggerLed) -> Unit = {}, val onSuspendPolicy: (String) -> Unit, val onSteamDownloadsInBackground: (Boolean) -> Unit = {}, val onBackActionsInverted: (Boolean) -> Unit, @@ -378,6 +419,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 +461,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,37 +471,32 @@ 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 airTriggersShown by remember { mutableStateOf(false) } var sheetCoords by remember { mutableStateOf(null) } val widthContext = LocalContext.current 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 val focusManager = LocalFocusManager.current // A page kept inside More is one step deeper than the strip: back returns to More before it closes the menu. val insideMore = page in pages.inMore() + val airPanel = airTriggersShown && page == SessionDrawerPage.CONTROLLER && a.airTriggers != null BackHandler(enabled = open) { when { host.open != null -> host.open = null + airPanel -> airTriggersShown = false insideMore -> onPageChange(SessionDrawerPage.MORE) else -> a.onClose() } } BackHandler(enabled = open && confirmStop) { confirmStop = false } - val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore) + val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore || airPanel) LaunchedEffect(layerOpen) { onLayerChange(layerOpen) } var seenBackRequest by remember { mutableStateOf(backRequest) } LaunchedEffect(backRequest) { @@ -468,10 +506,30 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont confirmStop -> confirmStop = false appToChooseDisplay != null -> appToChooseDisplay = null host.open != null -> host.open = null + airPanel -> airTriggersShown = false insideMore -> onPageChange(SessionDrawerPage.MORE) } } - LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false } + LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false; airTriggersShown = false } + var airPanelFocused by remember { mutableStateOf(airPanel) } + LaunchedEffect(airPanel) { + val moved = airPanel != airPanelFocused + airPanelFocused = airPanel + if (!moved || !open || !controllerActive) return@LaunchedEffect + val target = if (airPanel) "air-triggers-toggle" else "air-triggers" + repeat(24) { + androidx.compose.runtime.withFrameNanos { } + focus.request(target) + if (focus.focused == target) return@LaunchedEffect + } + } + 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 +550,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 +559,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 } } } @@ -533,8 +586,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) { val short = maxHeight < 440.dp - // The handle keeps a strip on the left free, so a sheet dragged wide can always be dragged back. - val maxSheet = (maxWidth - DRAWER_EDGE_GAP).coerceAtLeast(0.dp) + // At full width the handle's strip sits on the screen's left edge, so the sheet can still be dragged back. + val maxSheet = (maxWidth - DRAWER_HANDLE_STRIP).coerceAtLeast(0.dp) val minSheet = minOf(DRAWER_MIN_WIDTH, maxSheet) val defaultSheet = minOf(420.dp, maxWidth * 0.92f) val sheetWidth = if (docked) maxWidth else (savedWidth?.dp ?: defaultSheet).coerceIn(minSheet, maxSheet) @@ -555,6 +608,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont .controllerBack { when { host.open != null -> host.open = null + airPanel -> airTriggersShown = false managing -> DrawerPages.heldFrom?.let { held -> DrawerPages.rearrange(drawerContext, held) releaseSignal++ @@ -587,13 +641,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 +673,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), @@ -644,16 +685,14 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), 1)) } } - if (insideMore && !managing) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) } + if (insideMore && !managing && !airPanel) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) } + if (airPanel && !managing) DrawerMoreBack(stringResource(R.string.air_triggers_title), focus.track(page, "air-triggers-back"), + parent = stringResource(page.title)) { host.open = null; airTriggersShown = false } 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,377 +702,31 @@ 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) { + DrawerColumns(two = sheetWidth >= DRAWER_TWO_COLUMN_WIDTH && page.inColumns) { 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) }) - } + val airTriggers = a.airTriggers + if (airPanel && airTriggers != null) AirTriggersPanel(host, airTriggers, a, track) + else DrawerControllerPage(host, a, a.controllerConnected || controllerActive, track) { host.open = null; airTriggersShown = true } } - 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) 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.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() } - } - } + } } } } } @@ -1078,6 +771,443 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } +@Composable +private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: Boolean, track: (String) -> Modifier, onAirTriggers: () -> Unit) { + 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) + val airTriggers = a.airTriggers + val airTriggersLabel = stringResource(R.string.air_triggers_title) + if (a.padType != null || c != null || airTriggers != 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}" }, + airTriggers?.let { "$airTriggersLabel ${if (it.enabled) 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) + } + airTriggers?.let { + ActionRow(airTriggersLabel, if (it.enabled) on else off, stringResource(R.string.air_triggers_open), onAirTriggers, + modifier = track("air-triggers")) + } + } + 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) + 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 @@ -1219,7 +1349,16 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List Unit) { +private fun DrawerMoreBack(title: String, modifier: Modifier, parent: String = stringResource(R.string.drawer_page_more), onBack: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val source = remember { MutableInteractionSource() } val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value val shape = RoundedCornerShape(12.dp) - val label = stringResource(R.string.drawer_more_back, stringResource(R.string.drawer_page_more)) + val label = stringResource(R.string.drawer_more_back, parent) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = modifier.padding(top = 8.dp, start = 14.dp, end = 14.dp).fillMaxWidth().heightIn(min = 44.dp).clip(shape) @@ -1253,18 +1392,112 @@ private fun DrawerMoreBack(title: String, modifier: Modifier, onBack: () -> Unit .padding(horizontal = 8.dp), ) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp)) - Text(stringResource(R.string.drawer_page_more), fontSize = 13.sp, color = colors.onSurfaceVariant) + Text(parent, fontSize = 13.sp, color = colors.onSurfaceVariant) Text("·", fontSize = 13.sp, color = colors.onSurfaceVariant) Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1) } } +@Composable +private fun AirTriggersPanel(host: MenuHost, t: AirTriggerMenu, a: DrawerActions, track: (String) -> Modifier) { + CompositionLocalProvider(LocalDrawerSections provides null) { SettingsGroup(stringResource(R.string.air_triggers_title)) { + ToggleRow(host, "air-triggers-toggle", stringResource(R.string.air_triggers_use), stringResource(R.string.air_triggers_use_hint), t.enabled, + chipModifier = track("air-triggers-toggle"), onChange = a.onAirTriggers) + ToggleRow(host, "air-triggers-vibration", stringResource(R.string.air_triggers_vibration), stringResource(R.string.air_triggers_vibration_hint), + t.vibration, enabled = t.enabled, chipModifier = track("air-triggers-vibration"), onChange = a.onAirTriggerVibration) + ToggleRow(host, "air-triggers-screen-light", stringResource(R.string.air_triggers_screen_light), stringResource(R.string.air_triggers_screen_light_hint), + t.screenLight, enabled = t.enabled, chipModifier = track("air-triggers-screen-light"), onChange = a.onAirTriggerScreenLight) + val leds = listOf(AirTriggerLed.OFF to R.string.air_triggers_led_off, AirTriggerLed.STEADY to R.string.air_triggers_led_steady, + AirTriggerLed.PULSE to R.string.air_triggers_led_pulse).map { (led, text) -> led to stringResource(text) } + ChoiceRow(host, "air-triggers-led", stringResource(R.string.air_triggers_led), null, leds, t.led, + enabled = t.enabled, chipModifier = track("air-triggers-led"), onPick = a.onAirTriggerLed) + for (trigger in AirTrigger.entries) { + val key = "air-trigger-${trigger.name.lowercase()}" + val left = trigger == AirTrigger.LEFT + val label = stringResource(if (left) R.string.air_trigger_left else R.string.air_trigger_right) + ChoiceRow(host, key, label, stringResource(R.string.air_trigger_button_hint), t.buttons, t.selected.getValue(trigger), + enabled = t.enabled, chipModifier = track(key)) { a.onAirTriggerButton(trigger, it) } + AirTriggerActionRow(host, "$key-action", stringResource(if (left) R.string.air_trigger_left_action else R.string.air_trigger_right_action), + t.actions[trigger] ?: AirTriggerAction.TAP, t.rates[trigger] ?: RapidFireRate.NORMAL, t.enabled, track("$key-action"), + onAction = { a.onAirTriggerAction(trigger, it) }, onRate = { a.onAirTriggerRate(trigger, it) }) + } + } } +} + +@Composable +private fun AirTriggerActionRow( + host: MenuHost, key: String, label: String, action: AirTriggerAction, rate: RapidFireRate, enabled: Boolean, chipModifier: Modifier, + onAction: (AirTriggerAction) -> Unit, onRate: (RapidFireRate) -> Unit, +) { + val open = host.open == key + var rateOpen by remember { mutableStateOf(false) } + LaunchedEffect(open) { if (!open) rateOpen = false } + val actions = listOf(AirTriggerAction.TAP to R.string.air_trigger_action_tap, AirTriggerAction.LATCH to R.string.air_trigger_action_hold, + AirTriggerAction.RAPID to R.string.air_trigger_action_rapid).map { (value, text) -> value to stringResource(text) } + val rates = listOf(R.string.air_trigger_rate_low, R.string.air_trigger_rate_normal, R.string.air_trigger_rate_high).map { stringResource(it) } + val rapidLabel = actions.last().second + val frequency = stringResource(R.string.air_trigger_rapid_frequency) + SettingsRow(label, null, highlighted = open) { Box { + ValueChip(actions.first { it.first == action }.second, open, enabled, modifier = chipModifier.testTag("setting-$key")) { + host.open = if (open) null else key + } + AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = if (rateOpen) null else label) { first -> + val arrowFocus = remember { FocusRequester() } + val keyboard = LocalInputModeManager.current.inputMode == InputMode.Keyboard + var shown by remember { mutableStateOf(rateOpen) } + LaunchedEffect(rateOpen) { + if (shown == rateOpen) return@LaunchedEffect + shown = rateOpen + withFrameNanos { } + if (keyboard) runCatching { (if (rateOpen) first else arrowFocus).requestFocus() } + } + if (rateOpen) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 10.dp)) { + Text(rapidLabel.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f)) + MenuGlyphButton("✕", stringResource(R.string.common_close), Modifier.testTag("$key-rate-close")) { rateOpen = false } + } + ValueSlider(rate.ordinal, 0..RapidFireRate.entries.lastIndex, 1, true, frequency, { rates[it] }, + modifier = Modifier.focusRequester(first).testTag("$key-rate")) { if (it != rate.ordinal) onRate(RapidFireRate.entries[it]) } + } else actions.forEachIndexed { index, (value, text) -> + val pick = { onAction(value); host.open = null } + if (value != AirTriggerAction.RAPID) MenuItem(text, checked = value == action, focusRequester = if (index == 0) first else null, onClick = pick) + else Row(verticalAlignment = Alignment.CenterVertically) { + MenuItem(text, checked = value == action, modifier = Modifier.weight(1f), onClick = pick) + MenuGlyphButton("›", stringResource(R.string.air_trigger_rapid_settings), + Modifier.focusRequester(arrowFocus).testTag("$key-rate-open")) { rateOpen = true } + } + } + } + } } +} + +@Composable +private fun MenuGlyphButton(glyph: String, description: String, modifier: Modifier = Modifier, onClick: () -> Unit) { + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value + val shape = RoundedCornerShape(8.dp) + Box( + contentAlignment = Alignment.Center, + modifier = modifier.size(40.dp).clip(shape) + .background(if (hot) Color.White.copy(alpha = 0.07f) else Color.Transparent) + .glideBorder(hot, shape, pal.signal) + .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) + .controllerConfirm(onClick = onClick) + .semantics { contentDescription = description }, + ) { + Text(glyph, fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground) + } +} + /** 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), @@ -1288,23 +1521,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, @@ -1358,31 +1591,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)) } @@ -1404,7 +1619,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 @@ -1437,7 +1653,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) { @@ -1486,7 +1703,44 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole private val DRAWER_MIN_WIDTH = 300.dp private val DRAWER_HANDLE_STRIP = 24.dp -private val DRAWER_EDGE_GAP = 80.dp +private val DRAWER_COLUMN_GAP = 10.dp +// Two columns once each would be as wide as the narrowest single-column sheet. +private val DRAWER_TWO_COLUMN_WIDTH = DRAWER_MIN_WIDTH * 2 + DRAWER_COLUMN_GAP + +private val SessionDrawerPage.inColumns: Boolean + get() = this != SessionDrawerPage.MORE && this != SessionDrawerPage.ACHIEVEMENTS + +/** + * On a wide sheet, lays a page's groups out in two columns, the first half on the left. The split is by count, not + * height, so a group keeps its column while others fold and unfold. + */ +@Composable +internal fun DrawerColumns(two: Boolean, content: @Composable () -> Unit) { + // Keep a single composition so resizing only remeasures existing children. + Layout(content, Modifier.fillMaxWidth()) { measurables, constraints -> + val width = constraints.maxWidth + if (!two || measurables.size < 2) { + val placeables = measurables.map { it.measure(constraints.copy(minWidth = 0, minHeight = 0)) } + return@Layout layout(width, placeables.sumOf { it.height }) { + var y = 0 + placeables.forEach { it.placeRelative(0, y); y += it.height } + } + } + val gap = DRAWER_COLUMN_GAP.roundToPx() + val column = ((width - gap) / 2).coerceAtLeast(0) + val child = Constraints(maxWidth = column) + val placeables = measurables.map { it.measure(child) } + val half = (placeables.size + 1) / 2 + val left = placeables.take(half) + val right = placeables.drop(half) + layout(width, maxOf(left.sumOf { it.height }, right.sumOf { it.height })) { + var y = 0 + left.forEach { it.placeRelative(0, y); y += it.height } + y = 0 + right.forEach { it.placeRelative(column + gap, y); y += it.height } + } + } +} /** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */ @Composable @@ -1508,6 +1762,8 @@ private fun DrawerResizeHandle(width: Dp, min: Dp, max: Dp, onWidth: (Dp) -> Uni contentAlignment = Alignment.Center, modifier = modifier.width(24.dp).height(96.dp) .onGloballyPositioned { coords = it } + // On the screen's edge, Android's back swipe would take the drag. + .systemGestureExclusion() .focusable(true, source) .onPreviewKeyEvent { event -> val key = event.nativeKeyEvent @@ -1563,7 +1819,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), @@ -1643,7 +1900,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, @@ -1660,7 +1918,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", @@ -1799,7 +2057,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 @@ -1809,7 +2067,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, @@ -1819,7 +2077,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin } return } - SettingsGroup(stringResource(R.string.drawer_page_components)) { + DrawerComponentSettingsGroup(stringResource(R.string.drawer_game_components_note, gameProfile.name)) { DrawerStackedChoice( host = host, key = "game-cmp-proton", @@ -1862,17 +2120,11 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin ) } } - Text( - stringResource(R.string.drawer_game_components_note, gameProfile.name), - fontSize = 12.sp, - color = colors.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp), - ) return } 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 @@ -1902,13 +2154,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)) { + DrawerComponentSettingsGroup(stringResource(R.string.drawer_components_note)) { DrawerStackedChoice( host, "cmp-proton", stringResource(R.string.comp_proton), listOfNotNull( @@ -1944,10 +2196,16 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin ) } } - Text( - stringResource(R.string.drawer_components_note), - fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp), - ) +} + +@Composable +internal fun DrawerComponentSettingsGroup(note: String, content: @Composable ColumnScope.() -> Unit) { + // The note stays visible when collapsed, but both belong to one drawer column item. + Column(Modifier.fillMaxWidth()) { + SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components", content = content) + Text(note, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp)) + } } @Composable @@ -1965,7 +2223,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/SettingsJump.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsJump.kt new file mode 100644 index 0000000000..cf50f10701 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsJump.kt @@ -0,0 +1,62 @@ +package com.droiddeck.launcher.ui + +import android.os.SystemClock +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.tween +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind + +/** The row a settings search result opens, so the page it lands on can scroll to it and flash it. */ +internal object SettingsJump { + class Target(val label: String, val at: Long = SystemClock.uptimeMillis()) + + var target: Target? by mutableStateOf(null) + + fun to(label: String) { target = Target(label) } +} + +private const val JUMP_WINDOW_MS = 5_000L + +/** False in the search results, whose rows carry the same labels as the rows they open. */ +internal val LocalSearchTargets = staticCompositionLocalOf { true } + +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) +@Composable +internal fun Modifier.searchTarget(label: String): Modifier { + val pal = LocalPalette.current + val flash = remember { Animatable(0f) } + val reveal = remember { BringIntoViewRequester() } + var claimed by remember { mutableStateOf(null) } + val target = SettingsJump.target.takeIf { LocalSearchTargets.current } + if (target != null && target.label == label) SideEffect { + if (SettingsJump.target === target) { + SettingsJump.target = null + if (SystemClock.uptimeMillis() - target.at <= JUMP_WINDOW_MS) claimed = target + } + } + claimed?.let { mine -> + LaunchedEffect(mine) { + withFrameNanos { } + reveal.bringIntoView() + repeat(2) { + flash.animateTo(1f, tween(220)) + flash.animateTo(0f, tween(420)) + } + claimed = null + } + } + return bringIntoViewRequester(reveal).drawBehind { + if (flash.value > 0f) drawRect(pal.signal.copy(alpha = 0.28f * flash.value)) + } +} 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..b76a5157f9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt @@ -96,14 +96,14 @@ 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 } - Column { + androidx.compose.runtime.CompositionLocalProvider(LocalSearchTargets provides false) { Column { found.groupBy { it.place }.forEach { (place, entries) -> SettingsGroup(stringResource(place.title)) { entries.forEach { entry -> @@ -112,9 +112,10 @@ internal fun SettingsSearchResults(query: String, onOpen: (SettingsSection) -> U val section = entry.section val tab = entry.tab if (section != null) { - ActionRow(title, within, stringResource(R.string.store_open), onClick = { onOpen(section) }) + ActionRow(title, within, stringResource(R.string.store_open), onClick = { SettingsJump.to(title); onOpen(section) }) } else if (tab != null) { ActionRow(title, within, stringResource(R.string.store_open), onClick = { + SettingsJump.to(title) if (tab == NavTabs.MORE) MoreTabs.editing = true if (tab == "downloads") DownloadsNav.showSettings = true RailRequest.key = tab @@ -125,5 +126,5 @@ internal fun SettingsSearchResults(query: String, onOpen: (SettingsSection) -> U } } } - } + } } } 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..53a617b31b 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( } } } - } + } } } } @@ -397,12 +456,13 @@ fun MenuItem( .padding(horizontal = 10.dp, vertical = 9.dp), ) { Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f).clearAndSetSemantics {}) + val ink = if (checked) pal.signal else colors.onBackground if (leading != null) { - leading() + androidx.compose.runtime.CompositionLocalProvider(androidx.compose.material3.LocalContentColor provides ink) { leading() } Spacer(Modifier.width(8.dp)) } Column(modifier = Modifier.weight(1f)) { - Text(label, fontSize = 13.5.sp, color = if (checked) pal.signal else colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(label, fontSize = 13.5.sp, color = ink, maxLines = 2, overflow = TextOverflow.Ellipsis) if (detail != null) Text(detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis) } if (trailing != null) { Spacer(Modifier.width(8.dp)); trailing() } @@ -443,7 +503,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 +526,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 @@ -473,7 +537,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint minLines = hintLines ?: 1, maxLines = hintLines ?: Int.MAX_VALUE, overflow = TextOverflow.Ellipsis) } if (compact && !stacked) Column( - modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 10.dp, vertical = 6.dp), + modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(horizontal = 10.dp, vertical = 6.dp), ) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Text(label, fontSize = 13.sp, lineHeight = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, @@ -482,18 +546,18 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint } if (hint != null || hintLines != null) hintText(11.sp) } else if (stacked || LocalNarrowPane.current) Column( - modifier = Modifier.fillMaxWidth().background(bg).padding( + modifier = Modifier.searchTarget(label).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), + modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp), ) { Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) { Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) @@ -597,7 +661,7 @@ fun SliderRow( ) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - Column(Modifier.fillMaxWidth()) { + Column(Modifier.searchTarget(label).fillMaxWidth()) { ValueSlider(value, range, step, enabled, label, format, modifier = modifier.padding(horizontal = 6.dp, vertical = 3.dp), onChange = onChange) if (hint != null) Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, 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..1a05328069 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt @@ -0,0 +1,111 @@ +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) androidx.compose.runtime.CompositionLocalProvider(androidx.compose.material3.LocalContentColor provides colors.onBackground) { + 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..f15b69287b 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 @@ -21,10 +20,14 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.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 +47,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,49 +113,49 @@ 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)) { - if (stacked) { - StatusPanel(s, u, ua, me) + 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)) + val installed: @Composable () -> Unit = { + SectionLabel(stringResource(R.string.upd_installed_label)) + InstalledCard(s, u, me) + CheckRow(u, ua) + LabBuilds(s.sessionRunning, header = { SectionLabel(stringResource(R.string.lab_builds)) }, 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) + } + val channel: @Composable () -> Unit = { + SectionLabel(stringResource(R.string.upd_channel)) + ChannelPicker(u, ua) { StatusPanel(s, u, ua, me, embedded = it) } + } + val testers: @Composable () -> Unit = { + 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() } + } + if (stacked) { + Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + installed() 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(1.15f)) { StatusPanel(s, u, ua, me) } - } + channel() + testers() } - 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() } + } else { + Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(24.dp)) { + Column(Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + installed() + testers() + } + Column(Modifier.weight(1.15f).fillMaxHeight().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + channel() + } } } } @@ -169,8 +173,114 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie ) } +private val TEST_TINT = Color(0xFF9B6CFF) + @Composable -private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed) { +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, embedded: Boolean = false) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val catalog = u.catalog @@ -196,17 +306,24 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m else -> Look(pal.good, stringResource(R.string.upd_current_status), stringResource(R.string.upd_current_headline, name), null) } Column( - modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(18.dp), + modifier = if (embedded) Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, bottom = 14.dp) + else Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(18.dp), ) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) { Box(Modifier.size(7.dp).clip(CircleShape).background(look.tint)) Text(look.status, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = look.tint) - if (offered) Text(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 (!embedded) 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 +345,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 +357,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 +434,77 @@ 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, status: @Composable (embedded: Boolean) -> Unit) { 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))) { - TestList(tests, me, u, ua) + 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 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) + 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) + if (!listing) status(false) + 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, status) + } + } +} + +@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), + ) } } @@ -514,7 +691,7 @@ private fun LinkPill(label: String, url: String) { } @Composable -private fun TestList(tests: List, me: AppUpdates.Installed, u: UpdatesState, ua: UpdatesActions) { +private fun TestList(tests: List, me: AppUpdates.Installed, u: UpdatesState, ua: UpdatesActions, status: @Composable (embedded: Boolean) -> Unit) { val colors = MaterialTheme.colorScheme var query by rememberSaveable { mutableStateOf("") } val needle = query.trim().removePrefix("#").removePrefix("@") @@ -525,58 +702,30 @@ private fun TestList(tests: List, me: AppUpdates.Installed, u: UpdatesS val (ready, old) = matches.partition { it.versionCode >= me.versionCode } val followedOld = u.follow.channel == Channel.TEST && old.any { it.pr == u.follow.pr } var showOld by rememberSaveable { mutableStateOf(false) } - Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { - if (tests.size > 5 || query.isNotEmpty()) AdbTextField( - value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find), - keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, compact = true, showLabel = false, - placeholder = stringResource(R.string.upd_tests_find), modifier = Modifier.fillMaxWidth(), - ) - if (matches.isEmpty()) Text(stringResource(R.string.upd_tests_no_match), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(4.dp)) - ready.forEach { t -> TestRow(t, u.follow.pr == t.pr && u.follow.channel == Channel.TEST) { ua.onFollow(Follow(Channel.TEST, t.pr)) } } - if (old.isNotEmpty()) { - MoreLink(stringResource(R.string.upd_tests_old, old.size, me.versionCode), "tests:old") { showOld = !showOld } - if (showOld || followedOld || needle.isNotEmpty()) old.forEach { t -> - TestRow(t, u.follow.pr == t.pr && u.follow.channel == Channel.TEST, tooOld = true) { ua.onFollow(Follow(Channel.TEST, t.pr)) } + val oldShown = showOld || followedOld || needle.isNotEmpty() + val followed = u.follow.pr.takeIf { u.follow.channel == Channel.TEST } + val rowShown = followed != null && (ready.any { it.pr == followed } || (oldShown && old.any { it.pr == followed })) + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + // A followed test's row carries the status; browsing Tests while following Stable or Preview shows it only for an install running or failed. + if (if (followed != null) !rowShown else u.stage != null || u.error != null) status(false) + Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + if (tests.size > 5 || query.isNotEmpty()) AdbTextField( + value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find), + keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, compact = true, showLabel = false, + placeholder = stringResource(R.string.upd_tests_find), modifier = Modifier.fillMaxWidth(), + ) + if (matches.isEmpty()) Text(stringResource(R.string.upd_tests_no_match), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(4.dp)) + ready.forEach { t -> TestRow(t, followed == t.pr, status = status) { ua.onFollow(Follow(Channel.TEST, t.pr)) } } + if (old.isNotEmpty()) { + MoreLink(stringResource(R.string.upd_tests_old, old.size, me.versionCode), "tests:old") { showOld = !showOld } + if (oldShown) old.forEach { t -> + TestRow(t, followed == t.pr, tooOld = true, status = status) { ua.onFollow(Follow(Channel.TEST, t.pr)) } + } } } } } -@Composable -private fun ChannelCard( - icon: ImageVector, title: String, hint: String, latest: String?, selected: Boolean, - enabled: Boolean = true, onClick: () -> Unit, -) { - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - val src = remember { MutableInteractionSource() } - val hot = rememberHot(src) - 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 @@ -586,40 +735,46 @@ private fun RadioDot(selected: Boolean, size: androidx.compose.ui.unit.Dp = 22.d } @Composable -private fun TestRow(t: Release, selected: Boolean, tooOld: Boolean = false, onClick: () -> Unit) { +private fun TestRow(t: Release, selected: Boolean, tooOld: Boolean = false, status: @Composable (embedded: Boolean) -> Unit, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val src = remember { MutableInteractionSource() } val hot = rememberHot(src) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - modifier = Modifier.fillMaxWidth().paneItem("test:${t.pr}") - .heightIn(min = 52.dp) - .clip(Shape12) - .background(colors.surface).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) - .glideBorder(hot, Shape12, pal.signal, pal.line) - .alpha(if (tooOld && !selected) 0.6f else 1f) - .hoverable(src) - .clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick) - .controllerConfirm(onClick = onClick) - .padding(horizontal = 12.dp, vertical = 8.dp), + Column( + Modifier.fillMaxWidth().clip(Shape12).background(colors.surface) + .glideBorder(hot, Shape12, pal.signal, if (selected) pal.signal.copy(alpha = 0.5f) else pal.line), ) { - Text("#${t.pr}", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (selected) pal.signal else colors.onSurfaceVariant) - Column(Modifier.weight(1f)) { - Text(changeTitle(t.title.ifBlank { stringResource(R.string.upd_pr, t.pr) }), fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) - val detail = when { - t.apk == null -> stringResource(R.string.upd_not_built) - tooOld -> stringResource(R.string.upd_tests_old_row, t.versionCode) - else -> stringResource(R.string.upd_updated, ago(t.builtAt.takeIf { it > 0 } ?: t.publishedAt)) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().paneItem("test:${t.pr}") + .heightIn(min = 52.dp) + .background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) + .alpha(if (tooOld && !selected) 0.6f else 1f) + .hoverable(src) + .clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick) + .controllerConfirm(onClick = onClick) + .padding(horizontal = 12.dp, vertical = 8.dp), + ) { + Text("#${t.pr}", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (selected) pal.signal else colors.onSurfaceVariant) + Column(Modifier.weight(1f)) { + Text(changeTitle(t.title.ifBlank { stringResource(R.string.upd_pr, t.pr) }), fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + val detail = when { + t.apk == null -> stringResource(R.string.upd_not_built) + tooOld -> stringResource(R.string.upd_tests_old_row, t.versionCode) + else -> stringResource(R.string.upd_updated, ago(t.builtAt.takeIf { it > 0 } ?: t.publishedAt)) + } + Text( + listOfNotNull(detail, t.author.takeIf { it.isNotEmpty() }?.let { "@$it" }, t.shortCommit).joinToString(" · "), + fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + if (t.newerCommitPushed) Text(stringResource(R.string.upd_newer_commit_short), fontSize = 12.sp, color = AttentionAmber, maxLines = 1, overflow = TextOverflow.Ellipsis) } - Text( - listOfNotNull(detail, t.author.takeIf { it.isNotEmpty() }?.let { "@$it" }, t.shortCommit).joinToString(" · "), - fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, - ) - if (t.newerCommitPushed) Text(stringResource(R.string.upd_newer_commit_short), fontSize = 12.sp, color = AttentionAmber, maxLines = 1, overflow = TextOverflow.Ellipsis) + RadioDot(selected, 20.dp) + } + AnimatedVisibility(selected, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) { + status(true) } - RadioDot(selected, 20.dp) } } 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/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index d9d2eb111f..d193c2b025 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -67,13 +67,14 @@ object CompositorHost { outputHeight: Int, refreshHz: Float, fpsLimit: Int, + layerFpsLimit: Int = fpsLimit, ): Boolean { WaylandCompositor.nativeSetClockControl(java.io.File(context.filesDir, "${com.droiddeck.launcher.runtime.LinuxRuntime.DIR}/tmp/.dd-clock").path) ownVsyncThread = SessionPrefs.vsyncThread(context) WaylandCompositor.nativeSetRenderOnCommit(SessionPrefs.renderOnCommit(context)) blackFrameInsertion = SessionPrefs.blackFrameInsertion(context) WaylandCompositor.nativeSetBlackFrameInsertion(blackFrameInsertion) - pace(refreshHz, fpsLimit) + pace(refreshHz, fpsLimit, layerFpsLimit) if (!SessionState.running) WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight) if (started) { attached = surface @@ -95,23 +96,23 @@ object CompositorHost { private var blackFrameInsertion = false private var pictureHolds = 0 - private fun pace(refreshHz: Float, fpsLimit: Int) { + private fun pace(refreshHz: Float, fpsLimit: Int, layerFpsLimit: Int) { WaylandCompositor.nativeSetFpsLimit(fpsLimit) - WaylandCompositor.nativeSetLayerFrameRate(if (fpsLimit > 0 && !blackFrameInsertion) fpsLimit.toFloat() else refreshHz) + WaylandCompositor.nativeSetLayerFrameRate(SessionPrefs.layerFrameRate(layerFpsLimit, refreshHz, blackFrameInsertion)) WaylandCompositor.nativeSetOutputRefreshRate(refreshHz) SessionState.refreshHz = refreshHz } @Synchronized - fun updatePacing(refreshHz: Float, fpsLimit: Int) { - if (started) pace(refreshHz, fpsLimit) + fun updatePacing(refreshHz: Float, fpsLimit: Int, layerFpsLimit: Int = fpsLimit) { + if (started) pace(refreshHz, fpsLimit, layerFpsLimit) } @Synchronized - fun setBlackFrameInsertion(on: Boolean, refreshHz: Float, fpsLimit: Int) { + fun setBlackFrameInsertion(on: Boolean, refreshHz: Float, fpsLimit: Int, layerFpsLimit: Int = fpsLimit) { blackFrameInsertion = on WaylandCompositor.nativeSetBlackFrameInsertion(on) - if (started) pace(refreshHz, fpsLimit) + if (started) pace(refreshHz, fpsLimit, layerFpsLimit) } /** Presents only pictures until the matching release; false when nothing is strobing. */ 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..a2676304d9 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); @@ -290,6 +333,8 @@ public final class WaylandCompositor { public static native void nativeSetZeroCopy(boolean on); + public static native void nativeSetMirrorCapture(boolean on); + public static native void nativeSetDisplayBufferDriver(boolean on); public static native int nativeZeroCopyFrames(); @@ -417,12 +462,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..f72526ba2e 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 مهيَّأ لإنهاء هذه الجلسة مثبّت متاح للتنزيل @@ -1188,6 +1180,11 @@ أدوات الوكيل غير مثبتة: %1$s لا تُرسل إرفاق + الملفات + السماح بالوصول إلى الصور + اختيار المزيد من الصور + لا توجد صور بعد + لوحة المفاتيح إزالة الافتراضي جهد الاستدلال @@ -1265,6 +1262,11 @@ تحضير تعذّر الوصول إلى تصحيح الأخطاء اللاسلكي؛ زر الاقتران يشغّله اقتران + لا يحتوي Quest على شاشة اقتران. من حاسوب، شغّل مرة واحدة: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS و adb tcpip 5555. ثم اضغط «السماح» واقبل الطلب في النظارة + السماح + اقبل «السماح بتصحيح الأخطاء؟» في النظارة مع تحديد «السماح دائمًا» + تعذّر الاتصال. اقبل طلب تصحيح الأخطاء في النظارة، وإن لم يظهر، شغّل adb tcpip 5555 من حاسوب ثم حاول مجددًا + تعذّر الوصول إلى تصحيح الأخطاء اللاسلكي. اضغط «السماح» لإعداده من جديد تثبيت تسجيل الدخول PR #%1$d @@ -1335,6 +1337,31 @@ حجم الأزرار عصي تكيّفية اهتزاز اللعبة + Redmagic Air Triggers + فتح + استخدام Air Triggers + يشغّل أزرار الكتف دون لوحة الأزرار أو العلامات من RedMagic، وتضغط بدلاً من ذلك أزرار تخطيط اللمس. + Air Trigger الأيسر + Air Trigger الأيمن + محفوظ لهذا التخطيط + الاهتزاز + يهتز عند لمس Air Trigger + تأثير الإضاءة على الشاشة + يضيء حافة الشاشة أسفل Air Trigger عند لمسه + تأثيرات إضاءة LED عند اللمس + إيقاف + ثابت + نبض + إجراء Air Trigger الأيسر + إجراء Air Trigger الأيمن + نقرة واحدة + ضغط مطوّل + إطلاق سريع + إعدادات الإطلاق السريع + معدل النقر + منخفض + عادي + مرتفع المنطقة الميتة لعصا التحكم زر Steam زر QAM @@ -1342,6 +1369,16 @@ أجهزة Joy-Con كوحدات تحكم VR أثناء تشغيل SteamVR، يصبح كل Joy-Con يدًا. وجّهه إلى الأمام واضغط مطولًا على Home أو Capture لإعادة توسيطه. الرسوم المتحركة + مصنفر + يعرض خلفية الشاشة مموّهة خلف المشغّل. يستهلك طاقة بطارية أكثر. + خلفية مصنفرة + بطاقات مصنفرة + تُظهر البطاقات والمجموعات قليلًا من الخلفية. تبقى القوائم والحوارات معتمة. + يتطلب الخلفية المصنفرة. + شفافية الخلفية + مقدار ما يظهر من الخلفية. + شفافية البطاقات + مقدار ما يظهر من الخلفية عبر البطاقات. التحذير عند انخفاض مساحة التخزين اسأل قبل تشغيل Steam عندما تكون المساحة الحرة أقل من 10 جيجابايت. التخطيط @@ -2231,6 +2268,7 @@ يسار وسط يمين + مقسّم قائمة الوصول السريع في Steam غير متاحة بعد. إحصاءات داخل اللعبة مؤشرات الشاشة السفلية @@ -2408,7 +2446,8 @@ جارٍ تنزيل عميل Steam · %1$s يوجد تثبيت لأداة توافق قيد التنفيذ بالفعل أوقِف الجلسة النشطة قبل تثبيت أدوات التوافق - تعذّر العثور على إصدار ARM64 لـ %1$s + تعذّر العثور على إصدار %2$s لـ %1$s + مكافحة الغش يلزم توفُّر 4 GB على الأقل بالإضافة إلى حجم التنزيل لتثبيت %1$s جارٍ تنزيل %1$s %2$s جارٍ إعادة محاولة التنزيل · المحاولة %1$d من %2$d @@ -2545,6 +2584,8 @@ %1$s إذا لم يكن ذلك ممكنًا، وصِّل هذا الجهاز بكمبيوتر يستخدم ADB ونفِّذ الأمر أدناه. عُد إلى هنا وتحقَّق مرة أخرى. يمكن بدء جلسات Steam. لا يستخدم إصدار Android هذا هذا الحدّ. + يتولى DroidDeck حد العمليات الفرعية + يشغّل DroidDeck معظم برامج الجلسة في عمليات لا يحتسبها Android، ما يبقي الجلسة دون الحد بكثير، لذا يمكن إبقاء خيارات المطوّرين متوقفة. ما زال Steam وبعض أدواته المساعدة محتسبة. فعِّل «إيقاف القيود المفروضة على العمليات الثانوية» في خيارات المطوّرين، واترك خيارات المطوّرين مفعَّلة بعد ذلك. لا يحتوي إصدار Android هذا على مفتاح لذلك. استخدِم تصحيح الأخطاء اللاسلكي لتغييره من هذا الجهاز. لا يتوفّر تنزيل لهذا الإصدار الخاص بهذه النسخة من DroidDeck. @@ -3319,9 +3360,11 @@ %1$s س %1$d د موضع الصورة + موضع الصورة (أفقي) + موضع الصورة (عمودي) أعلى أسفل - الوسط (افتراضي) + الوسط يسار يمين التخزين @@ -4310,4 +4353,9 @@ تثبّت هذه اللعبة إصدار Linux الخاص بها. ثبّتها من Steam. تكبير اللعبة اضبط تكبير اللعبة من 100% إلى 300% + اختصار داخل اللعبة + إظهار اختصار النظارات الذكية + إظهار زر النظارات الذكية العائم فوق اللعبة. + استخدام ملف تعريف %1$s: %2$s + استخدام الملف التعريفي الافتراضي: %1$s 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..1a4a746fa1 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 @@ -1206,6 +1198,11 @@ Herramientas del agente sin instalar: %1$s No enviar Adjuntar + Archivos + Permitir acceso a fotos + Elegir más fotos + Aún no hay fotos + Teclado Quitar Predeterminado Esfuerzo de razonamiento @@ -1280,6 +1277,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 @@ -1341,6 +1343,31 @@ Tamaño de botones Sticks adaptables Vibración en juegos + Redmagic Air Triggers + Abrir + Usar los Air Triggers + Activa los gatillos de hombro sin el panel ni los marcadores de RedMagic. En su lugar, presionan botones de la disposición táctil. + Air Trigger izquierdo + Air Trigger derecho + Se guarda para esta disposición + Vibración + Vibra al tocar un Air Trigger + Efecto de luz en pantalla + Ilumina el borde de la pantalla debajo de un Air Trigger al tocarlo + Efectos LED de ambiente al tocar + Apagado + Fijo + Pulso + Acción del Air Trigger izquierdo + Acción del Air Trigger derecho + Toque único + Mantener presionado + Disparo rápido + Configuración de disparo rápido + Frecuencia de clics + Baja + Normal + Alta Zona muerta de la palanca Botón Steam Botón QAM @@ -1391,6 +1418,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 +2263,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 @@ -2400,7 +2438,8 @@ Descargando el cliente de Steam · %1$s Ya se está instalando una herramienta de compatibilidad Detén la sesión activa antes de instalar herramientas de compatibilidad - No se encontró una versión ARM64 de %1$s + No se encontró una versión %2$s de %1$s + Antitrampas Para instalar %1$s se necesitan al menos 4 GB libres más el tamaño de la descarga Descargando %1$s %2$s Reintentando la descarga · intento %1$d de %2$d @@ -2537,6 +2576,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 +3236,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 +4231,9 @@ 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. + Usando el perfil %1$s: %2$s + Usando el perfil predeterminado: %1$s diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 0eeec70877..f1ccdd13bc 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 е настроен да прекратява тази сесия Инсталиран Налично за изтегляне @@ -1176,6 +1168,11 @@ Инструментите на агента не са инсталирани: %1$s Не изпращай Прикачи + Файлове + Разрешаване на достъп до снимки + Избор на още снимки + Все още няма снимки + Клавиатура Премахни По подразбиране Усилие за разсъждение @@ -1249,6 +1246,11 @@ Подготви Безжичното отстраняване на грешки не е достъпно; сдвояването го включва Сдвой + Quest няма екран за сдвояване. От компютър изпълнете веднъж: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS и adb tcpip 5555. След това докоснете „Разреши“ и приемете запитването в шлема + Разреши + Приемете „Разрешаване на отстраняването на грешки?“ в шлема с отметка „Винаги разрешавай“ + Неуспешно свързване. Приемете запитването за отстраняване на грешки в шлема, а ако не се е появило, изпълнете adb tcpip 5555 от компютър и опитайте отново + Безжичното отстраняване на грешки не е достъпно. Докоснете „Разреши“, за да го настроите отново Инсталирай Влез PR #%1$d @@ -1307,6 +1309,31 @@ Размер на бутоните Адаптивни стикове Вибрация от играта + Redmagic Air Triggers + Отвори + Използвай Air Triggers + Включва раменните спусъци без панела и маркерите на RedMagic. Вместо това те натискат бутони от сензорното разположение. + Ляв Air Trigger + Десен Air Trigger + Запазва се за това разположение + Вибрация + Вибрира при докосване на Air Trigger + Светлинен ефект на екрана + Осветява ръба на екрана под Air Trigger при докосване + LED ефекти на атмосферата при докосване + Изключено + Постоянно + Пулсиране + Действие на левия Air Trigger + Действие на десния Air Trigger + Еднократно докосване + Продължително натискане + Бърза стрелба + Настройки за бърза стрелба + Честота на щракване + Ниска + Нормална + Висока Мъртва зона на стика Бутон Steam Бутон QAM @@ -1314,6 +1341,16 @@ Joy-Con като VR контролери Докато SteamVR работи, всеки Joy-Con става ръка. Насочете го напред и задръжте Home или Capture, за да го центрирате отново. Анимации + Матово + Показва тапета ви размазан зад лаунчъра. Изразходва повече батерия. + Матов тапет + Матови карти + Картите и групите пропускат малко от тапета. Менютата и диалозите остават плътни. + Изисква матов тапет. + Прозрачност на тапета + Колко от тапета се вижда. + Прозрачност на картите + Колко от тапета се вижда през картите. Предупреждение при малко място Питай преди стартиране на Steam, когато свободното място е под 10 GB. Разположение @@ -2131,6 +2168,7 @@ Вляво В центъра Вдясно + Разделено Менюто за бърз достъп на Steam още не е налично. Статистика в играта HUD на долния екран @@ -2304,7 +2342,8 @@ Изтегляне на клиента на Steam · %1$s Вече тече инсталация на инструмент за съвместимост Спри активната сесия, преди да инсталираш инструменти за съвместимост - Не беше намерена ARM64 версия на %1$s + Не беше намерена %2$s версия на %1$s + Анти-чийт За инсталирането на %1$s са необходими поне 4 GB свободно място плюс размера на изтеглянето Изтегляне на %1$s %2$s Повторен опит за изтегляне · опит %1$d от %2$d @@ -2441,6 +2480,8 @@ %1$s Ако това не е възможно, свържи устройството с компютър с ADB и изпълни командата отдолу. Върни се тук и провери отново. Сесиите на Steam могат да стартират. Тази версия на Android не използва това ограничение. + DroidDeck се справя с ограничението за дъщерни процеси + DroidDeck изпълнява повечето програми на сесията в процеси, които Android не отчита, така че сесията остава далеч под лимита и опциите за програмисти могат да останат изключени. Steam и някои от помощните му процеси все още се отчитат. Включи „Деактивиране на ограниченията за дъщерните процеси“ в Опции за програмисти и остави Опции за програмисти включени след това. Тази версия на Android няма превключвател за това. Използвай безжично отстраняване на грешки, за да го промениш от това устройство. Тази версия няма изтегляне за това копие на DroidDeck. @@ -3199,9 +3240,11 @@ %1$s ч %1$d мин Позиция на картината + Позиция на картината (Хоризонтална) + Позиция на картината (Вертикална) Горе Долу - В средата (по подразбиране) + В средата Наляво Надясно Съхранение @@ -4150,4 +4193,9 @@ Тази игра инсталира версията си за Linux. Инсталирайте я от Steam. Мащабиране на играта Регулирайте увеличението на играта от 100% до 300% + Пряк път в играта + Показване на прекия път за Smart Glasses + Показва плаващия бутон за Smart Glasses върху играта. + Използва се профил %1$s: %2$s + Използва се профилът по подразбиране: %1$s diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 833c403b0d..0b68d95cf7 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í @@ -1182,6 +1174,11 @@ Nástroje agenta nejsou nainstalované: %1$s Neposílat Přiložit + Soubory + Povolit přístup k fotkám + Vybrat další fotky + Zatím žádné fotky + Klávesnice Odebrat Výchozí Náročnost uvažování @@ -1257,6 +1254,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 @@ -1321,6 +1323,31 @@ Velikost tlačítek Adaptivní páčky Vibrace ve hře + Redmagic Air Triggers + Otevřít + Používat Air Triggers + Zapne ramenní triggery bez panelu a značek RedMagic. Místo toho mačkají tlačítka dotykového rozložení. + Levý Air Trigger + Pravý Air Trigger + Uloženo pro toto rozložení + Vibrace + Při dotyku Air Triggeru zavibruje + Světelný efekt na obrazovce + Při dotyku rozsvítí okraj obrazovky pod Air Triggerem + LED efekty atmosféry při dotyku + Vypnuto + Stálé + Pulzování + Akce levého Air Triggeru + Akce pravého Air Triggeru + Jedno klepnutí + Dlouhé stisknutí + Rychlá palba + Nastavení rychlé palby + Frekvence kliknutí + Nízká + Normální + Vysoká Mrtvá zóna páčky Tlačítko Steam Tlačítko QAM @@ -1328,6 +1355,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 +2218,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 @@ -2356,7 +2394,8 @@ Stahování klienta Steam · %1$s Instalace nástroje kompatibility už běží Před instalací nástrojů kompatibility zastavte aktivní relaci - Nepodařilo se najít vydání ARM64 pro %1$s + Nepodařilo se najít vydání %2$s pro %1$s + Anti-cheat Pro instalaci %1$s je potřeba alespoň 4 GB volného místa navíc k velikosti stahování Stahování %1$s %2$s Opakování stahování · pokus %1$d z %2$d @@ -2493,6 +2532,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 +3300,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 +4273,9 @@ 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. + Používá se profil %1$s: %2$s + Používá se výchozí profil: %1$s diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 6efe122eb6..a15253a46f 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 @@ -1176,6 +1168,11 @@ Agentens værktøjer er ikke installeret: %1$s Send ikke Vedhæft + Filer + Tillad adgang til billeder + Vælg flere billeder + Ingen billeder endnu + Tastatur Fjern Standard Ræsonneringsindsats @@ -1249,6 +1246,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 @@ -1307,6 +1309,31 @@ Knapstørrelse Adaptive styrepinde Spilvibration + Redmagic Air Triggers + Åbn + Brug Air Triggers + Tænder skuldertriggerne uden RedMagics triggerpanel eller markører. De trykker i stedet på knapper i touch-layoutet. + Venstre Air Trigger + Højre Air Trigger + Gemt for dette layout + Vibration + Vibrerer, når en Air Trigger berøres + Lyseffekt på skærmen + Lyser skærmkanten op under en Air Trigger, når den berøres + LED-stemningseffekter ved berøring + Fra + Konstant + Puls + Handling for venstre Air Trigger + Handling for højre Air Trigger + Enkelt tryk + Langt tryk + Hurtig affyring + Indstillinger for hurtig affyring + Klikfrekvens + Lav + Normal + Høj Dødzone for styrepind Steam-knap QAM-knap @@ -1314,6 +1341,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 +2168,7 @@ Venstre Midte Højre + Delt Steams menu til hurtig adgang er ikke tilgængelig endnu. Statistik i spillet HUD på nederste skærm @@ -2304,7 +2342,8 @@ Downloader Steam-klienten · %1$s En installation af et kompatibilitetsværktøj er allerede i gang Stop den aktive session, før du installerer kompatibilitetsværktøjer - Kunne ikke finde en ARM64-udgivelse af %1$s + Kunne ikke finde en %2$s-udgivelse af %1$s + Anti-cheat Mindst 4 GB ledig plads plus downloadets størrelse er nødvendig for at installere %1$s Downloader %1$s %2$s Forsøger download igen · forsøg %1$d af %2$d @@ -2441,6 +2480,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 +3240,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 +4193,9 @@ 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. + Bruger profilen %1$s: %2$s + Bruger standardprofilen: %1$s diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 31d8914d6c..a050e14efe 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 @@ -1168,6 +1160,11 @@ Agent-Werkzeuge nicht installiert: %1$s Nicht senden Anhängen + Dateien + Zugriff auf Fotos erlauben + Weitere Fotos auswählen + Noch keine Fotos + Tastatur Entfernen Standard Denkaufwand @@ -1241,6 +1238,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 @@ -1299,6 +1301,31 @@ Tastengröße Adaptive Sticks Spielvibration + Redmagic Air Triggers + Öffnen + Air Triggers verwenden + Schaltet die Schultertrigger ohne das Trigger-Panel und die Markierungen von RedMagic ein. Sie drücken stattdessen Tasten des Touch-Layouts. + Linker Air Trigger + Rechter Air Trigger + Für dieses Layout gespeichert + Vibration + Vibriert, wenn ein Air Trigger berührt wird + Lichteffekt auf dem Bildschirm + Lässt den Bildschirmrand unter einem Air Trigger aufleuchten, wenn er berührt wird + LED-Atmosphäreneffekte bei Berührung + Aus + Dauerhaft + Pulsieren + Aktion des linken Air Triggers + Aktion des rechten Air Triggers + Einmal tippen + Lange drücken + Dauerfeuer + Dauerfeuer-Einstellungen + Klickfrequenz + Niedrig + Normal + Hoch Stick-Totzone Steam-Taste QAM-Taste @@ -1306,6 +1333,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 +2160,7 @@ Links Mitte Rechts + Geteilt Das Schnellzugriffsmenü von Steam ist noch nicht verfügbar. Spielstatistiken HUD für den unteren Bildschirm @@ -2296,7 +2334,8 @@ Steam-Client wird heruntergeladen · %1$s Es läuft bereits die Installation eines Kompatibilitätstools Beende die aktive Sitzung, bevor du Kompatibilitätstools installierst - Kein ARM64-Release für %1$s gefunden + Kein %2$s-Release für %1$s gefunden + Anti-Cheat Zum Installieren von %1$s werden mindestens 4 GB freier Speicherplatz plus die Downloadgröße benötigt %1$s %2$s wird heruntergeladen Download wird wiederholt · Versuch %1$d von %2$d @@ -2433,6 +2472,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 +3240,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 +4193,9 @@ 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. + Profil %1$s wird verwendet: %2$s + Standardprofil wird verwendet: %1$s diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 5cad897424..bb2561f6b1 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 είναι ρυθμισμένο να διακόπτει αυτή τη συνεδρία Εγκατεστημένο Διαθέσιμο για λήψη @@ -1176,6 +1168,11 @@ Τα εργαλεία του πράκτορα δεν εγκαταστάθηκαν: %1$s Να μην σταλεί Επισύναψη + Αρχεία + Να επιτρέπεται η πρόσβαση στις φωτογραφίες + Επιλογή περισσότερων φωτογραφιών + Δεν υπάρχουν φωτογραφίες ακόμα + Πληκτρολόγιο Αφαίρεση Προεπιλογή Προσπάθεια συλλογισμού @@ -1249,6 +1246,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 @@ -1307,6 +1309,31 @@ Μέγεθος κουμπιών Προσαρμοστικοί μοχλοί Κραδασμός παιχνιδιού + Redmagic Air Triggers + Άνοιγμα + Χρήση Air Triggers + Ενεργοποιεί τις σκανδάλες ώμου χωρίς τον πίνακα ή τους δείκτες του RedMagic. Αντί γι\' αυτό πατούν κουμπιά της διάταξης αφής. + Αριστερό Air Trigger + Δεξί Air Trigger + Αποθηκεύεται για αυτή τη διάταξη + Δόνηση + Δονείται όταν αγγίζετε ένα Air Trigger + Εφέ φωτισμού οθόνης + Φωτίζει την άκρη της οθόνης κάτω από ένα Air Trigger όταν το αγγίζετε + Εφέ ατμόσφαιρας LED με την αφή + Ανενεργό + Σταθερό + Παλμός + Ενέργεια αριστερού Air Trigger + Ενέργεια δεξιού Air Trigger + Μονό πάτημα + Παρατεταμένο πάτημα + Ταχεία βολή + Ρυθμίσεις ταχείας βολής + Συχνότητα κλικ + Χαμηλή + Κανονική + Υψηλή Νεκρή ζώνη μοχλού Κουμπί Steam Κουμπί QAM @@ -1314,6 +1341,16 @@ Joy-Con ως χειριστήρια VR Όσο εκτελείται το SteamVR, κάθε Joy-Con γίνεται χέρι. Στρέψτε το μπροστά και κρατήστε πατημένο το Home ή το Capture για να το επανακεντράρετε. Κινήσεις + Θαμπό + Εμφανίζει την ταπετσαρία σας θολή πίσω από τον εκκινητή. Καταναλώνει περισσότερη μπαταρία. + Θαμπή ταπετσαρία + Θαμπές κάρτες + Οι κάρτες και οι ομάδες αφήνουν να φαίνεται λίγη από την ταπετσαρία. Τα μενού και οι διάλογοι μένουν συμπαγείς. + Χρειάζεται θαμπή ταπετσαρία. + Διαφάνεια ταπετσαρίας + Πόση από την ταπετσαρία φαίνεται. + Διαφάνεια καρτών + Πόση από την ταπετσαρία φαίνεται μέσα από τις κάρτες. Προειδοποίηση για χαμηλό χώρο αποθήκευσης Ερώτηση πριν από την εκκίνηση του Steam όταν ο ελεύθερος χώρος είναι κάτω από 10 GB. Διάταξη @@ -2131,6 +2168,7 @@ Αριστερά Κέντρο Δεξιά + Διαιρεμένο Το μενού γρήγορης πρόσβασης του Steam δεν είναι ακόμη διαθέσιμο. Στατιστικά παιχνιδιού HUD κάτω οθόνης @@ -2304,7 +2342,8 @@ Λήψη του πελάτη Steam · %1$s Μια εγκατάσταση εργαλείου συμβατότητας εκτελείται ήδη Διακόψτε την ενεργή συνεδρία πριν εγκαταστήσετε εργαλεία συμβατότητας - Δεν βρέθηκε κυκλοφορία ARM64 για το %1$s + Δεν βρέθηκε κυκλοφορία %2$s για το %1$s + Anti-cheat Απαιτούνται τουλάχιστον 4 GB ελεύθερα συν το μέγεθος της λήψης για να εγκατασταθεί το %1$s Λήψη %1$s %2$s Επανάληψη λήψης · προσπάθεια %1$d από %2$d @@ -2441,6 +2480,8 @@ %1$s Αν αυτό δεν είναι δυνατό, συνδέστε αυτή τη συσκευή σε έναν υπολογιστή με ADB και εκτελέστε την παρακάτω εντολή. Επιστρέψτε εδώ και ελέγξτε ξανά. Οι συνεδρίες Steam μπορούν να ξεκινήσουν. Αυτή η έκδοση Android δεν χρησιμοποιεί αυτό το όριο. + Το DroidDeck χειρίζεται το όριο θυγατρικών διεργασιών + Το DroidDeck εκτελεί τα περισσότερα προγράμματα της συνεδρίας σε διεργασίες που το Android δεν μετράει, ώστε η συνεδρία να μένει πολύ κάτω από το όριο και οι Επιλογές για προγραμματιστές να μπορούν να μείνουν απενεργοποιημένες. Το Steam και ορισμένες βοηθητικές διεργασίες του εξακολουθούν να μετράνε. Ενεργοποιήστε την «Απενεργοπ. περιορισμών σε θυγατρικές διεργασίες» στις Επιλογές προγραμματιστή και αφήστε τις Επιλογές προγραμματιστή ενεργές μετά. Αυτή η έκδοση Android δεν έχει διακόπτη για αυτό. Χρησιμοποιήστε τον ασύρματο εντοπισμό σφαλμάτων για να το αλλάξετε από αυτή τη συσκευή. Αυτή η έκδοση δεν έχει λήψη για αυτό το αντίγραφο του DroidDeck. @@ -3199,9 +3240,11 @@ %1$s ώ. %1$d λεπ. Θέση εικόνας + Θέση εικόνας (Οριζόντιος προσανατολισμός) + Θέση εικόνας (Κατακόρυφος) Πάνω Κάτω - Κέντρο (προεπιλογή) + Κέντρο Αριστερά Δεξιά Αποθήκευση @@ -4150,4 +4193,9 @@ Αυτό το παιχνίδι εγκαθιστά την έκδοσή του για Linux. Εγκαταστήστε το από το Steam. Ζουμ παιχνιδιού Ρυθμίστε τη μεγέθυνση του παιχνιδιού από 100% έως 300% + Συντόμευση μέσα στο παιχνίδι + Εμφάνιση συντόμευσης Smart Glasses + Εμφάνιση του αιωρούμενου κουμπιού Smart Glasses πάνω από το παιχνίδι. + Χρήση προφίλ %1$s: %2$s + Χρήση προεπιλεγμένου προφίλ: %1$s diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index c055194828..0e1d1ae717 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 @@ -1179,6 +1171,11 @@ Herramientas del agente sin instalar: %1$s No enviar Adjuntar + Archivos + Permitir acceso a las fotos + Elegir más fotos + Aún no hay fotos + Teclado Quitar Predeterminado Esfuerzo de razonamiento @@ -1253,6 +1250,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 @@ -1314,6 +1316,31 @@ Tamaño de botones Sticks adaptables Vibración en juegos + Redmagic Air Triggers + Abrir + Usar los Air Triggers + Activa los gatillos de hombro sin el panel ni los marcadores de RedMagic. En su lugar, pulsan botones de la disposición táctil. + Air Trigger izquierdo + Air Trigger derecho + Se guarda para esta disposición + Vibración + Vibra al tocar un Air Trigger + Efecto de luz en pantalla + Ilumina el borde de la pantalla debajo de un Air Trigger al tocarlo + Efectos LED de ambiente al tocar + Apagado + Fijo + Pulso + Acción del Air Trigger izquierdo + Acción del Air Trigger derecho + Toque único + Mantener pulsado + Disparo rápido + Ajustes de disparo rápido + Frecuencia de clics + Baja + Normal + Alta Zona muerta de la palanca Botón Steam Botón QAM @@ -1321,6 +1348,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 +2193,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 @@ -2330,7 +2368,8 @@ Descargando el cliente de Steam · %1$s Ya se está instalando una herramienta de compatibilidad Detén la sesión activa antes de instalar herramientas de compatibilidad - No se encontró una versión ARM64 de %1$s + No se encontró una versión %2$s de %1$s + Antitrampas Para instalar %1$s se necesitan al menos 4 GB libres más el tamaño de la descarga Descargando %1$s %2$s Reintentando la descarga · intento %1$d de %2$d @@ -2467,6 +2506,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 +3270,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 +4233,9 @@ 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. + Usando el perfil %1$s: %2$s + Usando el perfil predeterminado: %1$s diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 4fac8b737d..f50c60b125 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 @@ -1176,6 +1168,11 @@ Agentin työkaluja ei ole asennettu: %1$s Älä lähetä Liitä + Tiedostot + Salli kuvien käyttö + Valitse lisää kuvia + Ei vielä kuvia + Näppäimistö Poista Oletus Päättelyteho @@ -1249,6 +1246,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 @@ -1307,6 +1309,31 @@ Painikkeiden koko Mukautuvat sauvat Pelin tärinä + Redmagic Air Triggers + Avaa + Käytä Air Triggereitä + Ottaa olkaliipaisimet käyttöön ilman RedMagicin liipaisinpaneelia tai merkkejä. Ne painavat sen sijaan kosketusasettelun painikkeita. + Vasen Air Trigger + Oikea Air Trigger + Tallennetaan tälle asettelulle + Värinä + Värisee, kun Air Triggeriä kosketetaan + Näytön valoefekti + Valaisee näytön reunan Air Triggerin alla, kun sitä kosketetaan + Kosketuksen tunnelma-LED-efektit + Pois + Tasainen + Sykkivä + Vasemman Air Triggerin toiminto + Oikean Air Triggerin toiminto + Yksi napautus + Pitkä painallus + Sarjatuli + Sarjatulen asetukset + Napsautustiheys + Matala + Normaali + Korkea Ohjaussauvan kuollut alue Steam-painike QAM-painike @@ -1314,6 +1341,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 +2168,7 @@ Vasen Keskellä Oikea + Jaettu Steamin pikavalikko ei ole vielä käytettävissä. Pelinsisäiset tilastot Alanäytön HUD @@ -2304,7 +2342,8 @@ Ladataan Steam-asiakasohjelmaa · %1$s Yhteensopivuustyökalun asennus on jo käynnissä Pysäytä käynnissä oleva istunto ennen yhteensopivuustyökalujen asentamista - ARM64-julkaisua kohteelle %1$s ei löytynyt + %2$s-julkaisua kohteelle %1$s ei löytynyt + Huijauksenesto Kohteen %1$s asentaminen vaatii vähintään 4 GB vapaata tilaa latauksen koon lisäksi Ladataan %1$s %2$s Yritetään latausta uudelleen · yritys %1$d/%2$d @@ -2441,6 +2480,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 +3240,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 +4193,9 @@ 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. + Käytössä profiili %1$s: %2$s + Käytössä oletusprofiili: %1$s diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 05ed77da3c..fa2b370772 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 @@ -1179,6 +1171,11 @@ Outils de l’agent non installés : %1$s Ne pas envoyer Joindre + Fichiers + Autoriser l\'accès aux photos + Choisir d\'autres photos + Aucune photo pour l\'instant + Clavier Supprimer Par défaut Effort de raisonnement @@ -1252,6 +1249,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 @@ -1313,6 +1315,31 @@ Taille des boutons Joystick adaptatif Vibration du jeu + Redmagic Air Triggers + Ouvrir + Utiliser les Air Triggers + Active les gâchettes d\'épaule sans le panneau ni les repères de RedMagic. Elles appuient à la place sur des boutons de la disposition tactile. + Air Trigger gauche + Air Trigger droit + Enregistré pour cette disposition + Vibration + Vibre quand un Air Trigger est touché + Effet lumineux à l\'écran + Illumine le bord de l\'écran sous un Air Trigger quand il est touché + Effets LED d\'ambiance au toucher + Désactivé + Fixe + Pulsation + Action de l\'Air Trigger gauche + Action de l\'Air Trigger droit + Appui simple + Appui long + Tir rapide + Réglages du tir rapide + Fréquence des clics + Faible + Normale + Élevée Zone morte du stick Bouton Steam Bouton QAM @@ -1320,6 +1347,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 +2192,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 @@ -2329,7 +2367,8 @@ Téléchargement du client Steam · %1$s Une installation d\'outil de compatibilité est déjà en cours Arrêtez la session en cours avant d\'installer des outils de compatibilité - Aucune version ARM64 trouvée pour %1$s + Aucune version %2$s trouvée pour %1$s + Anti-triche Au moins 4 Go libres, plus la taille du téléchargement, sont nécessaires pour installer %1$s Téléchargement de %1$s %2$s Nouvelle tentative de téléchargement · essai %1$d sur %2$d @@ -2466,6 +2505,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 +3269,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 +4232,9 @@ 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. + Profil %1$s utilisé : %2$s + Profil par défaut utilisé : %1$s diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 174f70bfa1..57ece37715 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 इस सेशन को बंद करने के लिए सेट है इंस्टॉल है डाउनलोड के लिए उपलब्ध @@ -1176,6 +1168,11 @@ एजेंट टूल इंस्टॉल नहीं हुए: %1$s न भेजें संलग्न करें + फ़ाइलें + फ़ोटो की अनुमति दें + और फ़ोटो चुनें + अभी कोई फ़ोटो नहीं + कीबोर्ड हटाएँ डिफ़ॉल्ट सोचने का स्तर @@ -1249,6 +1246,11 @@ तैयार करें वायरलेस डिबगिंग से कनेक्ट नहीं हो पा रहा; पेयर करने से यह चालू हो जाता है पेयर करें + Quest में पेयरिंग स्क्रीन नहीं है। किसी कंप्यूटर से एक बार चलाएँ: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS और adb tcpip 5555। फिर अनुमति दें पर टैप करें और हेडसेट में संकेत स्वीकार करें + अनुमति दें + हेडसेट में “डीबगिंग की अनुमति दें?” स्वीकार करें, हमेशा अनुमति दें चुना हुआ रखें + कनेक्ट नहीं हो सका। हेडसेट में डीबगिंग संकेत स्वीकार करें, या अगर वह नहीं दिखा, तो कंप्यूटर से adb tcpip 5555 चलाएँ और दोबारा कोशिश करें + वायरलेस डीबगिंग तक नहीं पहुँचा जा सकता। इसे फिर से सेट करने के लिए अनुमति दें पर टैप करें इंस्टॉल करें साइन इन करें PR #%1$d @@ -1307,6 +1309,31 @@ बटन का आकार एडैप्टिव स्टिक गेम वाइब्रेशन + Redmagic Air Triggers + खोलें + Air Triggers इस्तेमाल करें + RedMagic के ट्रिगर पैनल या मार्कर के बिना शोल्डर ट्रिगर चालू करता है। इसके बजाय वे टच लेआउट के बटन दबाते हैं। + लेफ़्ट Air Trigger + राइट Air Trigger + इस लेआउट के लिए सहेजा गया + वाइब्रेशन + Air Trigger छूने पर वाइब्रेट करता है + स्क्रीन लाइट इफ़ेक्ट + Air Trigger छूने पर उसके नीचे स्क्रीन का किनारा रोशन करता है + टच एटमॉस्फ़ियर LED इफ़ेक्ट + बंद + स्थिर + पल्स + लेफ़्ट Air Trigger का ऐक्शन + राइट Air Trigger का ऐक्शन + सिंगल टैप + लॉन्ग प्रेस + रैपिड फ़ायर + रैपिड फ़ायर सेटिंग + क्लिक फ़्रीक्वेंसी + कम + सामान्य + ज़्यादा स्टिक का डेड ज़ोन Steam बटन QAM बटन @@ -1314,6 +1341,16 @@ Joy-Con को VR कंट्रोलर की तरह SteamVR चलते समय हर Joy-Con एक हाथ बन जाता है। उसे सामने की ओर करें और फिर से केंद्रित करने के लिए Home या Capture दबाए रखें। एनिमेशन + फ़्रॉस्टेड + लॉन्चर के पीछे आपका वॉलपेपर धुंधला दिखाता है। ज़्यादा बैटरी खर्च होती है। + फ़्रॉस्टेड वॉलपेपर + फ़्रॉस्टेड कार्ड + कार्ड और समूह वॉलपेपर का थोड़ा हिस्सा दिखाते हैं। मेन्यू और डायलॉग ठोस रहते हैं। + फ़्रॉस्टेड वॉलपेपर ज़रूरी है। + वॉलपेपर की पारदर्शिता + वॉलपेपर कितना दिखता है। + कार्ड की पारदर्शिता + कार्ड के पार वॉलपेपर कितना दिखता है। स्टोरेज कम होने पर चेतावनी दें खाली जगह 10 GB से कम होने पर Steam शुरू करने से पहले पूछें। लेआउट @@ -2131,6 +2168,7 @@ बाएँ बीच में दाएँ + विभाजित Steam का क्विक एक्सेस मेनू अभी उपलब्ध नहीं है। इन-गेम आंकड़े निचली स्क्रीन HUD @@ -2304,7 +2342,8 @@ Steam क्लाइंट डाउनलोड हो रहा है · %1$s एक कम्पैटिबिलिटी टूल इंस्टॉल पहले से चल रहा है कम्पैटिबिलिटी टूल इंस्टॉल करने से पहले चल रहा सेशन बंद करें - %1$s के लिए कोई ARM64 रिलीज़ नहीं मिली + %1$s के लिए कोई %2$s रिलीज़ नहीं मिली + एंटी-चीट %1$s इंस्टॉल करने के लिए कम से कम 4 GB खाली जगह और डाउनलोड आकार चाहिए %1$s %2$s डाउनलोड हो रहा है डाउनलोड फिर से कोशिश हो रहा है · %2$d में से %1$d प्रयास @@ -2441,6 +2480,8 @@ %1$s अगर यह संभव नहीं है, तो इस डिवाइस को ADB वाले कंप्यूटर से कनेक्ट करें और नीचे दिया कमांड चलाएं। यहां वापस आएं और फिर से जांचें। Steam सेशन शुरू हो सकते हैं। यह Android वर्शन इस सीमा का उपयोग नहीं करता। + चाइल्ड-प्रोसेस सीमा DroidDeck संभालता है + DroidDeck सत्र के ज़्यादातर प्रोग्राम उन प्रोसेस में चलाता है जिन्हें Android नहीं गिनता, जिससे सत्र सीमा से काफ़ी नीचे रहता है, इसलिए डेवलपर विकल्प बंद रह सकते हैं। Steam और उसके कुछ सहायक प्रोसेस अब भी गिने जाते हैं। डेवलपर विकल्प में “चाइल्ड प्रोसेस से जुड़ी पाबंदियां हटाएं” चालू करें, और बाद में डेवलपर विकल्प चालू रहने दें। इस Android वर्शन में इसके लिए कोई स्विच नहीं है। इसे इस डिवाइस से बदलने के लिए वायरलेस डीबगिंग इस्तेमाल करें। इस बिल्ड में DroidDeck की इस कॉपी के लिए कोई डाउनलोड नहीं है। @@ -3199,9 +3240,11 @@ %1$s घं %1$d मि चित्र की स्थिति + चित्र की स्थिति (लैंडस्केप) + चित्र की स्थिति (पोर्ट्रेट) ऊपर नीचे - बीच में (डिफ़ॉल्ट) + बीच में बाएँ दाएँ स्टोरेज @@ -4150,4 +4193,9 @@ यह गेम अपना Linux संस्करण इंस्टॉल करता है। इसे Steam से इंस्टॉल करें। गेम ज़ूम गेम का ज़ूम 100% से 300% तक समायोजित करें + गेम में शॉर्टकट + Smart Glasses शॉर्टकट दिखाएँ + गेम के ऊपर तैरता हुआ Smart Glasses बटन दिखाएँ। + %1$s प्रोफ़ाइल का उपयोग: %2$s + डिफ़ॉल्ट प्रोफ़ाइल का उपयोग: %1$s diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 5fdb4a5a66..93e0bd906a 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ő @@ -1176,6 +1168,11 @@ Az ügynök eszközei nincsenek telepítve: %1$s Ne küldd el Csatolás + Fájlok + Fotókhoz való hozzáférés engedélyezése + További fotók kiválasztása + Még nincsenek fotók + Billentyűzet Eltávolítás Alapértelmezett Gondolkodási erőfeszítés @@ -1249,6 +1246,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 @@ -1307,6 +1309,31 @@ Gombméret Adaptív karok Játékvibráció + Redmagic Air Triggers + Megnyitás + Air Triggers használata + Bekapcsolja a vállravaszokat a RedMagic ravaszpanelje és jelölői nélkül. Helyettük az érintéses elrendezés gombjait nyomják meg. + Bal Air Trigger + Jobb Air Trigger + Ehhez az elrendezéshez mentve + Rezgés + Rezeg, amikor megérint egy Air Triggert + Fényeffektus a képernyőn + Érintéskor megvilágítja a képernyő szélét az Air Trigger alatt + Érintési hangulat-LED-effektusok + Ki + Folyamatos + Pulzálás + Bal Air Trigger művelete + Jobb Air Trigger művelete + Egy koppintás + Hosszú nyomás + Gyorstüzelés + Gyorstüzelés beállításai + Kattintási gyakoriság + Alacsony + Normál + Magas Kar holtzónája Steam gomb QAM gomb @@ -1314,6 +1341,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 +2168,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 @@ -2304,7 +2342,8 @@ A Steam-kliens letöltése · %1$s Már fut egy kompatibilitási eszköz telepítése Állítsa le az aktív munkamenetet a kompatibilitási eszközök telepítése előtt - Nem található ARM64-es kiadás a %1$s-hez + Nem található %2$s-es kiadás a %1$s-hez + Csalás elleni védelem Legalább 4 GB szabad hely, plusz a letöltés mérete szükséges a %1$s telepítéséhez %1$s %2$s letöltése A letöltés újrapróbálása · %1$d. próbálkozás a %2$d-ből @@ -2441,6 +2480,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 +3240,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 +4193,9 @@ 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. + Használt profil: %1$s – %2$s + Alapértelmezett profil használata: %1$s diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 09891934b8..51741a52d4 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 @@ -1173,6 +1165,11 @@ Alat agen tidak terpasang: %1$s Jangan kirim Lampirkan + File + Izinkan akses foto + Pilih foto lainnya + Belum ada foto + Keyboard Hapus Default Upaya penalaran @@ -1246,6 +1243,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 @@ -1301,6 +1303,31 @@ Ukuran tombol Stik adaptif Getaran gim + Redmagic Air Triggers + Buka + Gunakan Air Triggers + Menyalakan trigger bahu tanpa panel atau penanda trigger RedMagic. Sebagai gantinya, trigger menekan tombol tata letak sentuh. + Air Trigger kiri + Air Trigger kanan + Disimpan untuk tata letak ini + Getaran + Bergetar saat Air Trigger disentuh + Efek cahaya layar + Menerangi tepi layar di bawah Air Trigger saat disentuh + Efek LED suasana saat disentuh + Mati + Tetap + Denyut + Aksi Air Trigger kiri + Aksi Air Trigger kanan + Ketuk sekali + Tekan lama + Tembak cepat + Setelan tembak cepat + Frekuensi klik + Rendah + Normal + Tinggi Zona mati stik Tombol Steam Tombol QAM @@ -1308,6 +1335,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 +2144,7 @@ Kiri Tengah Kanan + Terbagi Menu Akses Cepat Steam belum tersedia. Statistik dalam gim HUD layar bawah @@ -2279,7 +2317,8 @@ Mengunduh klien Steam · %1$s Instalasi alat kompatibilitas sedang berjalan Hentikan sesi aktif sebelum menginstal alat kompatibilitas - Tidak dapat menemukan rilis ARM64 untuk %1$s + Tidak dapat menemukan rilis %2$s untuk %1$s + Anti-cheat Setidaknya 4 GB ruang kosong ditambah ukuran unduhan diperlukan untuk menginstal %1$s Mengunduh %1$s %2$s Mencoba lagi unduhan · percobaan %1$d dari %2$d @@ -2416,6 +2455,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 +3211,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 +4163,9 @@ 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. + Menggunakan profil %1$s: %2$s + Menggunakan profil default: %1$s diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 4aaee8b446..f8972c12bf 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 @@ -1171,6 +1163,11 @@ Strumenti dell’agente non installati: %1$s Non inviare Allega + File + Consenti accesso alle foto + Scegli altre foto + Ancora nessuna foto + Tastiera Rimuovi Predefinito Livello di ragionamento @@ -1244,6 +1241,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 @@ -1305,6 +1307,31 @@ Dimensione dei tasti Levette adattive Vibrazione di gioco + Redmagic Air Triggers + Apri + Usa gli Air Triggers + Attiva i grilletti dorsali senza il pannello né gli indicatori di RedMagic. Premono invece i pulsanti del layout touch. + Air Trigger sinistro + Air Trigger destro + Salvato per questo layout + Vibrazione + Vibra quando tocchi un Air Trigger + Effetto luce sullo schermo + Illumina il bordo dello schermo sotto un Air Trigger quando lo tocchi + Effetti LED d\'atmosfera al tocco + Spento + Fisso + Pulsante + Azione dell\'Air Trigger sinistro + Azione dell\'Air Trigger destro + Tocco singolo + Pressione prolungata + Fuoco rapido + Impostazioni fuoco rapido + Frequenza dei clic + Bassa + Normale + Alta Zona morta dello stick Tasto Steam Tasto QAM @@ -1312,6 +1339,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 +2184,7 @@ Sinistra Centro Destra + Diviso Il menu di accesso rapido di Steam non è ancora disponibile. Statistiche di gioco HUD dello schermo inferiore @@ -2321,7 +2359,8 @@ Download del client Steam · %1$s È già in corso l\'installazione di uno strumento di compatibilità Interrompi la sessione attiva prima di installare strumenti di compatibilità - Impossibile trovare una release ARM64 per %1$s + Impossibile trovare una release %2$s per %1$s + Anti-cheat Per installare %1$s servono almeno 4 GB liberi più la dimensione del download Download di %1$s %2$s Nuovo tentativo di download · tentativo %1$d di %2$d @@ -2458,6 +2497,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 +3269,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 +4232,9 @@ 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. + Profilo %1$s in uso: %2$s + Profilo predefinito in uso: %1$s diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 157a2b6627..6ed0728576 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がこのセッションを終了するように設定されています インストール済み ダウンロード可能 @@ -1173,6 +1165,11 @@ エージェントのツールが未インストール: %1$s 送信しない 添付 + ファイル + 写真へのアクセスを許可 + 写真をさらに選択 + まだ写真がありません + キーボード 削除 デフォルト 推論レベル @@ -1246,6 +1243,11 @@ 準備 ワイヤレスデバッグに接続できません。ペアリングで有効になります ペアリング + Quest にはペア設定画面がありません。パソコンから一度だけ adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS と adb tcpip 5555 を実行し、[許可] をタップしてヘッドセットの確認を承認してください + 許可 + ヘッドセットで「デバッグを許可しますか?」を、[常に許可] にチェックを入れて承認してください + 接続できませんでした。ヘッドセットでデバッグの確認を承認してください。表示されなかった場合は、パソコンから adb tcpip 5555 を実行してもう一度お試しください + ワイヤレス デバッグに接続できません。[許可] をタップして設定し直してください インストール サインイン PR #%1$d @@ -1301,6 +1303,31 @@ ボタンのサイズ アダプティブスティック ゲームの振動 + Redmagic エアトリガー + 開く + エアトリガーを使う + RedMagic のトリガーパネルやマーカーを出さずにショルダートリガーをオンにし、タッチレイアウトのボタンを押します。 + 左エアトリガー + 右エアトリガー + このレイアウトに保存されます + バイブレーション + エアトリガーに触れると振動します + 画面のライト効果 + エアトリガーに触れると、その下の画面の端が光ります + タッチ時のアンビエントLED効果 + オフ + 常時点灯 + パルス + 左エアトリガーの動作 + 右エアトリガーの動作 + シングルタップ + 長押し + 連射 + 連射の設定 + クリック頻度 + 低 + 標準 + 高 スティックのデッドゾーン Steamボタン QAMボタン @@ -1308,6 +1335,16 @@ Joy-ConをVRコントローラーとして使う SteamVRの実行中は各Joy-Conが手になります。前に向けてHOMEボタンかキャプチャーボタンを長押しすると、向きを合わせ直します。 アニメーション + すりガラス + ランチャーの背後に壁紙をぼかして表示します。バッテリーの消費が増えます。 + すりガラスの壁紙 + すりガラスのカード + カードやグループから壁紙が少し透けて見えます。メニューとダイアログは不透明のままです。 + すりガラスの壁紙が必要です。 + 壁紙の透明度 + 壁紙がどれだけ透けて見えるか。 + カードの透明度 + カード越しに壁紙がどれだけ透けて見えるか。 ストレージ残量が少ないときに警告する 空き容量が 10 GB 未満のとき、Steam を起動する前に確認します。 レイアウト @@ -2107,6 +2144,7 @@ 左 中央 右 + 分割 Steam のクイックアクセスメニューはまだ使えません。 ゲーム内統計 下部画面の HUD @@ -2279,7 +2317,8 @@ Steamクライアントをダウンロード中 · %1$s 互換性ツールのインストールはすでに実行中です 互換性ツールをインストールする前に、実行中のセッションを停止してください - %1$sのARM64リリースが見つかりませんでした + %1$sの%2$sリリースが見つかりませんでした + アンチチート %1$sのインストールには、ダウンロードサイズに加えて4GB以上の空き容量が必要です %1$s %2$sをダウンロード中 ダウンロードを再試行中 · %1$d / %2$d回目 @@ -2416,6 +2455,8 @@ %1$s それができない場合は、このデバイスをADBが使えるPCに接続し、以下のコマンドを実行してください。その後ここに戻って再確認してください。 Steamセッションを開始できます。 このAndroidバージョンではこの制限は使用されません。 + 子プロセスの制限は DroidDeck が対処します + DroidDeck はセッションのほとんどのプログラムを Android が数えないプロセスで実行するため、セッションは上限を大きく下回り、開発者向けオプションはオフのままでかまいません。Steam とその補助プロセスの一部は引き続き数えられます。 開発者向けオプションで「子プロセスの制限を無効化」をオンにし、その後も開発者向けオプションをオンのままにしてください。 このAndroidバージョンにはこのスイッチがありません。ワイヤレスデバッグを使って、このデバイスから変更してください。 このビルドには、このDroidDeckコピー用のダウンロードがありません。 @@ -3170,9 +3211,11 @@ ダウンロードは「コンポーネント」ページと共有されます。上でダウンロード済みのバージョンを選ぶと、次回のゲーム起動時に使用されます。 ダウンロードするバージョンを選択 画面の位置 + 画面の位置(横向き) + 画面の位置(縦向き) 上 下 - 中央(既定) + 中央 左 右 ストレージ @@ -4120,4 +4163,9 @@ このゲームは Linux 版をインストールします。Steam からインストールしてください。 ゲームズーム ゲームの拡大率を100%から300%の間で調整します + ゲーム内ショートカット + Smart Glasses のショートカットを表示 + ゲーム画面上に Smart Glasses のフローティングボタンを表示します。 + %1$s プロファイルを使用中: %2$s + デフォルトプロファイルを使用中: %1$s diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index cd41e8aa47..73d71c6e11 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가 이 세션을 종료하도록 설정했습니다 설치됨 다운로드 가능 @@ -1173,6 +1165,11 @@ 에이전트 도구가 설치되지 않음: %1$s 보내지 않기 첨부 + 파일 + 사진 접근 허용 + 사진 더 선택 + 아직 사진이 없습니다 + 키보드 제거 기본 추론 수준 @@ -1246,6 +1243,11 @@ 준비 무선 디버깅에 연결할 수 없습니다. 페어링하면 켜집니다 페어링 + Quest에는 페어링 화면이 없습니다. 컴퓨터에서 한 번 실행하세요: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 및 adb tcpip 5555. 그런 다음 허용을 탭하고 헤드셋에서 요청을 수락하세요 + 허용 + 헤드셋에서 \'디버깅을 허용하시겠습니까?\'를 항상 허용을 선택한 채로 수락하세요 + 연결하지 못했습니다. 헤드셋에서 디버깅 요청을 수락하거나, 요청이 나타나지 않았다면 컴퓨터에서 adb tcpip 5555를 실행한 뒤 다시 시도하세요 + 무선 디버깅에 연결할 수 없습니다. 허용을 탭해 다시 설정하세요 설치 로그인 PR #%1$d @@ -1301,6 +1303,31 @@ 버튼 크기 적응형 스틱 게임 진동 + Redmagic 에어 트리거 + 열기 + 에어 트리거 사용 + RedMagic 트리거 패널이나 표시 없이 숄더 트리거를 켜고, 대신 터치 레이아웃의 버튼을 누릅니다. + 왼쪽 에어 트리거 + 오른쪽 에어 트리거 + 이 레이아웃에 저장됨 + 진동 + 에어 트리거를 터치하면 진동합니다 + 화면 조명 효과 + 에어 트리거를 터치하면 그 아래 화면 가장자리가 밝아집니다 + 터치 분위기 LED 효과 + 끄기 + 상시 점등 + 펄스 + 왼쪽 에어 트리거 동작 + 오른쪽 에어 트리거 동작 + 한 번 탭 + 길게 누르기 + 연사 + 연사 설정 + 클릭 빈도 + 낮음 + 보통 + 높음 스틱 데드존 Steam 버튼 QAM 버튼 @@ -1308,6 +1335,16 @@ Joy-Con을 VR 컨트롤러로 사용 SteamVR이 실행되는 동안 각 Joy-Con이 손이 됩니다. 앞을 향하게 한 채 HOME 또는 캡처 버튼을 길게 누르면 다시 가운데로 맞춥니다. 애니메이션 + 반투명 + 런처 뒤에 배경화면을 흐리게 표시합니다. 배터리를 더 많이 사용합니다. + 반투명 배경화면 + 반투명 카드 + 카드와 그룹에 배경화면이 살짝 비쳐 보입니다. 메뉴와 대화상자는 불투명하게 유지됩니다. + 반투명 배경화면이 필요합니다. + 배경화면 투명도 + 배경화면이 얼마나 비쳐 보이는지 정합니다. + 카드 투명도 + 카드 너머로 배경화면이 얼마나 비쳐 보이는지 정합니다. 저장 공간이 부족할 때 경고 여유 공간이 10GB 미만이면 Steam을 시작하기 전에 확인합니다. 레이아웃 @@ -2107,6 +2144,7 @@ 왼쪽 가운데 오른쪽 + 분할 Steam 빠른 메뉴를 아직 사용할 수 없습니다. 게임 내 통계 하단 화면 HUD @@ -2279,7 +2317,8 @@ Steam 클라이언트 다운로드 중 · %1$s 호환성 도구를 이미 설치하고 있습니다 호환성 도구를 설치하기 전에 실행 중인 세션을 중지하세요 - %1$s의 ARM64 릴리스를 찾을 수 없습니다 + %1$s의 %2$s 릴리스를 찾을 수 없습니다 + 안티 치트 %1$s을(를) 설치하려면 다운로드 크기에 더해 최소 4GB의 여유 공간이 필요합니다 %1$s %2$s 다운로드 중 다운로드 재시도 중 · %2$d회 중 %1$d번째 @@ -2416,6 +2455,8 @@ %1$s 이 방법을 사용할 수 없으면 이 기기를 ADB가 설치된 PC에 연결하고 아래 명령을 실행하세요. 그런 다음 여기로 돌아와 다시 확인하세요. Steam 세션을 시작할 수 있습니다. 이 Android 버전에서는 이 제한을 사용하지 않습니다. + 하위 프로세스 제한은 DroidDeck이 처리합니다 + DroidDeck은 세션 프로그램 대부분을 Android가 세지 않는 프로세스에서 실행하므로 세션이 한도보다 훨씬 낮게 유지되어 개발자 옵션을 꺼 둔 채로 두어도 됩니다. Steam과 일부 보조 프로세스는 여전히 집계됩니다. 개발자 옵션에서 “하위 프로세스 제한 사용 중지”를 켜고, 이후에도 개발자 옵션을 켜 둔 상태로 유지하세요. 이 Android 버전에는 해당 스위치가 없습니다. 무선 디버깅을 사용하여 이 기기에서 변경하세요. 이 빌드에는 이 DroidDeck 복사본용 다운로드가 없습니다. @@ -3170,9 +3211,11 @@ 다운로드는 구성 요소 페이지와 공유됩니다. 위에서 다운로드한 버전을 선택하면 다음 게임 실행 시 사용됩니다. 다운로드할 버전 선택 화면 위치 + 화면 위치 (가로 모드) + 화면 위치 (세로) 위 아래 - 가운데(기본) + 가운데 왼쪽 오른쪽 저장 공간 @@ -4120,4 +4163,9 @@ 이 게임은 Linux 버전을 설치합니다. Steam에서 설치하세요. 게임 확대 게임 확대율을 100%에서 300%까지 조정합니다 + 게임 내 바로가기 + Smart Glasses 바로가기 표시 + 게임 위에 떠 있는 Smart Glasses 버튼을 표시합니다. + %1$s 프로필 사용 중: %2$s + 기본 프로필 사용 중: %1$s diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 92d613f184..1272676fb4 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 @@ -1173,6 +1165,11 @@ Alat ejen tidak dipasang: %1$s Jangan hantar Lampirkan + Fail + Benarkan akses foto + Pilih lebih banyak foto + Belum ada foto + Papan kekunci Alih keluar Lalai Usaha penaakulan @@ -1246,6 +1243,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 @@ -1301,6 +1303,31 @@ Saiz butang Stik adaptif Getaran permainan + Redmagic Air Triggers + Buka + Guna Air Triggers + Menghidupkan pencetus bahu tanpa panel atau penanda pencetus RedMagic. Sebaliknya, ia menekan butang susun atur sentuh. + Air Trigger kiri + Air Trigger kanan + Disimpan untuk susun atur ini + Getaran + Bergetar apabila Air Trigger disentuh + Kesan cahaya skrin + Menyalakan tepi skrin di bawah Air Trigger apabila ia disentuh + Kesan LED suasana sentuhan + Mati + Tetap + Denyut + Tindakan Air Trigger kiri + Tindakan Air Trigger kanan + Ketik sekali + Tekan lama + Tembakan pantas + Tetapan tembakan pantas + Kekerapan klik + Rendah + Biasa + Tinggi Zon mati kayu bedik Butang Steam Butang QAM @@ -1308,6 +1335,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 +2144,7 @@ Kiri Tengah Kanan + Terbahagi Menu Akses Pantas Steam belum tersedia. Statistik dalam permainan HUD skrin bawah @@ -2279,7 +2317,8 @@ Memuat turun klien Steam · %1$s Pemasangan alat keserasian sudah berjalan Hentikan sesi aktif sebelum memasang alat keserasian - Tidak dapat mencari keluaran ARM64 untuk %1$s + Tidak dapat mencari keluaran %2$s untuk %1$s + Anti-cheat Sekurang-kurangnya 4 GB bebas tambah saiz muat turun diperlukan untuk memasang %1$s Memuat turun %1$s %2$s Mencuba semula muat turun · percubaan %1$d daripada %2$d @@ -2416,6 +2455,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 +3211,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 +4163,9 @@ 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. + Menggunakan profil %1$s: %2$s + Menggunakan profil lalai: %1$s diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index edc7b5fa51..b0ed7518e9 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 @@ -1176,6 +1168,11 @@ Agentverktøy er ikke installert: %1$s Ikke send Legg ved + Filer + Tillat tilgang til bilder + Velg flere bilder + Ingen bilder ennå + Tastatur Fjern Standard Resonneringsinnsats @@ -1249,6 +1246,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 @@ -1307,6 +1309,31 @@ Knappestørrelse Adaptive stikker Spillvibrasjon + Redmagic Air Triggers + Åpne + Bruk Air Triggers + Slår på skuldertriggerne uten RedMagics triggerpanel eller markører. De trykker i stedet på knapper i berøringsoppsettet. + Venstre Air Trigger + Høyre Air Trigger + Lagret for dette oppsettet + Vibrering + Vibrerer når en Air Trigger berøres + Lyseffekt på skjermen + Lyser opp skjermkanten under en Air Trigger når den berøres + LED-stemningseffekter ved berøring + Av + Konstant + Puls + Handling for venstre Air Trigger + Handling for høyre Air Trigger + Enkelt trykk + Langt trykk + Hurtigskyting + Innstillinger for hurtigskyting + Klikkfrekvens + Lav + Normal + Høy Dødsone for styrespak Steam-knapp QAM-knapp @@ -1314,6 +1341,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 +2168,7 @@ Venstre Midten Høyre + Delt Steams hurtigtilgangsmeny er ikke tilgjengelig ennå. Statistikk i spillet HUD på bunnskjermen @@ -2304,7 +2342,8 @@ Laster ned Steam-klienten · %1$s En installasjon av et kompatibilitetsverktøy kjører allerede Avslutt den aktive sesjonen før du installerer kompatibilitetsverktøy - Fant ingen ARM64-utgivelse for %1$s + Fant ingen %2$s-utgivelse for %1$s + Anti-juks Minst 4 GB ledig pluss nedlastingens størrelse er nødvendig for å installere %1$s Laster ned %1$s %2$s Prøver nedlastingen igjen · forsøk %1$d av %2$d @@ -2441,6 +2480,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 +3240,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 +4193,9 @@ 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. + Bruker profilen %1$s: %2$s + Bruker standardprofilen: %1$s diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 77808b5f3c..51faec8331 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 @@ -1176,6 +1168,11 @@ Agenttools niet geïnstalleerd: %1$s Niet verzenden Bijvoegen + Bestanden + Toegang tot foto\'s toestaan + Meer foto\'s kiezen + Nog geen foto\'s + Toetsenbord Verwijderen Standaard Redeneerinspanning @@ -1249,6 +1246,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 @@ -1307,6 +1309,31 @@ Knopgrootte Adaptieve sticks Trillen in games + Redmagic Air Triggers + Openen + Air Triggers gebruiken + Zet de schoudertriggers aan zonder het triggerpaneel of de markeringen van RedMagic. Ze drukken in plaats daarvan knoppen van de aanraakindeling in. + Linker Air Trigger + Rechter Air Trigger + Opgeslagen voor deze indeling + Trillen + Trilt wanneer je een Air Trigger aanraakt + Lichteffect op het scherm + Laat de schermrand onder een Air Trigger oplichten wanneer je die aanraakt + Sfeer-ledeffecten bij aanraken + Uit + Constant + Pulseren + Actie van linker Air Trigger + Actie van rechter Air Trigger + Eén keer tikken + Lang indrukken + Snelvuur + Instellingen voor snelvuur + Klikfrequentie + Laag + Normaal + Hoog Dode zone van stick Steam-knop QAM-knop @@ -1314,6 +1341,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 +2168,7 @@ Links Midden Rechts + Gesplitst Het menu Snelle toegang van Steam is nog niet beschikbaar. In-game statistieken HUD op het onderste scherm @@ -2304,7 +2342,8 @@ Steam-client downloaden · %1$s Er wordt al een compatibiliteitstool geïnstalleerd Stop de actieve sessie voordat je compatibiliteitstools installeert - Kan geen ARM64-release vinden voor %1$s + Kan geen %2$s-release vinden voor %1$s + Anti-cheat Om %1$s te installeren is minstens 4 GB vrije ruimte nodig, plus de downloadgrootte %1$s %2$s downloaden Download opnieuw proberen · poging %1$d van %2$d @@ -2441,6 +2480,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 +3240,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 +4193,9 @@ 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. + Profiel %1$s in gebruik: %2$s + Standaardprofiel in gebruik: %1$s diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 687742d283..c58ee37170 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 @@ -1182,6 +1174,11 @@ Narzędzia agenta nie są zainstalowane: %1$s Nie wysyłaj Załącz + Pliki + Zezwól na dostęp do zdjęć + Wybierz więcej zdjęć + Brak zdjęć + Klawiatura Usuń Domyślny Poziom rozumowania @@ -1257,6 +1254,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 @@ -1321,6 +1323,31 @@ Rozmiar przycisków Adaptacyjne gałki Wibracje gry + Redmagic Air Triggers + Otwórz + Używaj Air Triggers + Włącza spusty naramienne bez panelu i znaczników RedMagic. Zamiast tego naciskają przyciski układu dotykowego. + Lewy Air Trigger + Prawy Air Trigger + Zapisane dla tego układu + Wibracje + Wibruje po dotknięciu Air Triggera + Efekt świetlny na ekranie + Podświetla krawędź ekranu pod Air Triggerem po jego dotknięciu + Efekty LED nastroju przy dotyku + Wyłączone + Stałe + Pulsowanie + Działanie lewego Air Triggera + Działanie prawego Air Triggera + Pojedyncze dotknięcie + Długie naciśnięcie + Szybki ogień + Ustawienia szybkiego ognia + Częstotliwość kliknięć + Niska + Normalna + Wysoka Martwa strefa drążka Przycisk Steam Przycisk QAM @@ -1328,6 +1355,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 +2218,7 @@ Do lewej Na środku Do prawej + Podzielony Menu szybkiego dostępu Steam nie jest jeszcze dostępne. Statystyki w grze HUD dolnego ekranu @@ -2356,7 +2394,8 @@ Pobieranie klienta Steam · %1$s Instalacja narzędzia zgodności już trwa Zatrzymaj aktywną sesję przed instalacją narzędzi zgodności - Nie znaleziono wydania ARM64 dla %1$s + Nie znaleziono wydania %2$s dla %1$s + Antycheat Do instalacji %1$s potrzeba co najmniej 4 GB wolnego miejsca plus rozmiar pobierania Pobieranie %1$s %2$s Ponawianie pobierania · próba %1$d z %2$d @@ -2493,6 +2532,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 +3300,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 +4273,9 @@ 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ą. + Używany profil %1$s: %2$s + Używany profil domyślny: %1$s diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index c5970fe00b..28e0cbd71f 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 @@ -1171,6 +1163,11 @@ Ferramentas do agente não instaladas: %1$s Não enviar Anexar + Ficheiros + Permitir acesso às fotos + Escolher mais fotos + Ainda não há fotos + Teclado Remover Predefinido Esforço de raciocínio @@ -1244,6 +1241,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 @@ -1305,6 +1307,31 @@ Tamanho dos botões Analógicos adaptáveis Vibração do jogo + Redmagic Air Triggers + Abrir + Utilizar os Air Triggers + Liga os gatilhos de ombro sem o painel nem os marcadores da RedMagic. Em vez disso, premem botões do esquema tátil. + Air Trigger esquerdo + Air Trigger direito + Guardado para este esquema + Vibração + Vibra quando toca num Air Trigger + Efeito de luz no ecrã + Ilumina a margem do ecrã por baixo de um Air Trigger quando é tocado + Efeitos LED de ambiente ao toque + Desligado + Fixo + Pulsar + Ação do Air Trigger esquerdo + Ação do Air Trigger direito + Toque único + Premir prolongadamente + Disparo rápido + Definições de disparo rápido + Frequência de cliques + Baixa + Normal + Alta Zona morta do manípulo Botão Steam Botão QAM @@ -1312,6 +1339,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 +2199,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 @@ -2336,7 +2374,8 @@ A transferir o cliente Steam · %1$s Já está em curso a instalação de uma ferramenta de compatibilidade Pare a sessão ativa antes de instalar ferramentas de compatibilidade - Não foi possível encontrar uma versão ARM64 de %1$s + Não foi possível encontrar uma versão %2$s de %1$s + Anti-cheat São necessários pelo menos 4 GB livres, mais o tamanho da transferência, para instalar %1$s A transferir %1$s %2$s A repetir a transferência · tentativa %1$d de %2$d @@ -2473,6 +2512,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 +3284,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 +4232,9 @@ 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. + Perfil %1$s em utilização: %2$s + Perfil predefinido em utilização: %1$s diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index df77690a5a..0008c90bba 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 @@ -1178,6 +1170,11 @@ Ferramentas do agente não instaladas: %1$s Não enviar Anexar + Arquivos + Permitir acesso às fotos + Escolher mais fotos + Ainda não há fotos + Teclado Remover Padrão Esforço de raciocínio @@ -1252,6 +1249,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 @@ -1313,6 +1315,31 @@ Tamanho dos botões Analógicos adaptáveis Vibração do jogo + Redmagic Air Triggers + Abrir + Usar os Air Triggers + Liga os gatilhos de ombro sem o painel nem os marcadores da RedMagic. Em vez disso, eles apertam botões do layout de toque. + Air Trigger esquerdo + Air Trigger direito + Salvo para este layout + Vibração + Vibra quando um Air Trigger é tocado + Efeito de luz na tela + Ilumina a borda da tela embaixo de um Air Trigger quando ele é tocado + Efeitos de LED de ambiente ao toque + Desligado + Fixo + Pulsar + Ação do Air Trigger esquerdo + Ação do Air Trigger direito + Toque único + Toque longo + Disparo rápido + Configurações de disparo rápido + Frequência de cliques + Baixa + Normal + Alta Zona morta do analógico Botão Steam Botão QAM @@ -1320,6 +1347,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 +2207,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 @@ -2344,7 +2382,8 @@ Baixando o cliente Steam · %1$s Já há uma instalação de ferramenta de compatibilidade em andamento Pare a sessão ativa antes de instalar ferramentas de compatibilidade - Não foi possível encontrar uma versão ARM64 de %1$s + Não foi possível encontrar uma versão %2$s de %1$s + Anti-cheat É preciso ter pelo menos 4 GB livres, além do tamanho do download, para instalar %1$s Baixando %1$s %2$s Tentando baixar de novo · tentativa %1$d de %2$d @@ -2481,6 +2520,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 +3294,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 +4240,9 @@ 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. + Perfil %1$s em uso: %2$s + Perfil predefinido em uso: %1$s diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 8d6da38074..fd3323ac71 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 @@ -1179,6 +1171,11 @@ Instrumentele agentului nu sunt instalate: %1$s Nu trimite Atașează + Fișiere + Permite accesul la fotografii + Alege mai multe fotografii + Încă nu există fotografii + Tastatură Elimină Implicit Efort de raționament @@ -1253,6 +1250,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 @@ -1314,6 +1316,31 @@ Dimensiunea butoanelor Manșe adaptive Vibrații de joc + Redmagic Air Triggers + Deschide + Folosește Air Triggers + Pornește triggerele de umăr fără panoul sau marcajele RedMagic. În schimb, ele apasă butoane din aranjamentul tactil. + Air Trigger stâng + Air Trigger drept + Salvat pentru acest aranjament + Vibrație + Vibrează când atingi un Air Trigger + Efect de lumină pe ecran + Luminează marginea ecranului de sub un Air Trigger când îl atingi + Efecte LED de atmosferă la atingere + Oprit + Constant + Puls + Acțiunea Air Trigger-ului stâng + Acțiunea Air Trigger-ului drept + Atingere simplă + Apăsare lungă + Foc rapid + Setări foc rapid + Frecvența clicurilor + Scăzută + Normală + Ridicată Zonă moartă a manetei Butonul Steam Butonul QAM @@ -1321,6 +1348,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 +2193,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 @@ -2330,7 +2368,8 @@ Se descarcă clientul Steam · %1$s O instalare a unui instrument de compatibilitate este deja în curs Oprește sesiunea activă înainte de a instala instrumente de compatibilitate - Nu s-a găsit o versiune ARM64 pentru %1$s + Nu s-a găsit o versiune %2$s pentru %1$s + Anti-cheat Este necesar cel puțin 4 GB liber, plus dimensiunea descărcării, pentru a instala %1$s Se descarcă %1$s %2$s Se reîncearcă descărcarea · tentativa %1$d din %2$d @@ -2467,6 +2506,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 +3270,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 +4233,9 @@ 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. + Se folosește profilul %1$s: %2$s + Se folosește profilul implicit: %1$s diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index a37ec1a0aa..a831dcfd41 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 настроен на завершение этой сессии Установлен Доступен для скачивания @@ -1182,6 +1174,11 @@ Инструменты агента не установлены: %1$s Не отправлять Прикрепить + Файлы + Разрешить доступ к фото + Выбрать ещё фото + Пока нет фото + Клавиатура Удалить По умолчанию Уровень рассуждений @@ -1257,6 +1254,11 @@ Подготовить Беспроводная отладка недоступна; «Сопряжение» включит её Сопряжение + В Quest нет экрана сопряжения. Один раз выполните на компьютере: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS и adb tcpip 5555. Затем нажмите «Разрешить» и подтвердите запрос в шлеме + Разрешить + Подтвердите «Разрешить отладку?» в шлеме, отметив «Всегда разрешать» + Не удалось подключиться. Подтвердите запрос на отладку в шлеме, а если он не появился, выполните adb tcpip 5555 на компьютере и повторите попытку + Беспроводная отладка недоступна. Нажмите «Разрешить», чтобы настроить её заново Установить Войти PR #%1$d @@ -1321,6 +1323,31 @@ Размер кнопок Адаптивные стики Вибрация в играх + Redmagic Air Triggers + Открыть + Использовать Air Triggers + Включает плечевые триггеры без панели и меток RedMagic. Вместо этого они нажимают кнопки сенсорной раскладки. + Левый Air Trigger + Правый Air Trigger + Сохраняется для этой раскладки + Вибрация + Вибрирует при касании Air Trigger + Световой эффект на экране + Подсвечивает край экрана под Air Trigger при касании + LED-эффекты атмосферы при касании + Выкл. + Постоянный + Пульсация + Действие левого Air Trigger + Действие правого Air Trigger + Одно нажатие + Долгое нажатие + Быстрая стрельба + Настройки быстрой стрельбы + Частота нажатий + Низкая + Обычная + Высокая Мёртвая зона стика Кнопка Steam Кнопка QAM @@ -1328,6 +1355,16 @@ Joy-Con как VR-контроллеры Пока работает SteamVR, каждый Joy-Con становится рукой. Направьте его вперёд и удерживайте Home или Capture, чтобы снова его отцентрировать. Анимации + Матовое стекло + Показывает размытые обои за лаунчером. Расходует больше заряда. + Матовые обои + Матовые карточки + Сквозь карточки и группы немного просвечивают обои. Меню и диалоги остаются непрозрачными. + Нужны матовые обои. + Прозрачность обоев + Насколько просвечивают обои. + Прозрачность карточек + Насколько обои просвечивают сквозь карточки. Предупреждать о нехватке места Спрашивать перед запуском Steam, если свободно меньше 10 ГБ. Раскладка @@ -2182,6 +2219,7 @@ Слева По центру Справа + Разделённый Меню быстрого доступа Steam пока недоступно. Игровая статистика HUD нижнего экрана @@ -2357,7 +2395,8 @@ Загрузка клиента Steam · %1$s Инструмент совместимости уже устанавливается Остановите текущую сессию перед установкой инструментов совместимости - Не найден выпуск %1$s для ARM64 + Не найден выпуск %1$s для %2$s + Античит Для установки %1$s нужно не менее 4 ГБ свободного места плюс размер загрузки Загрузка %1$s %2$s Повторная загрузка · попытка %1$d из %2$d @@ -2494,6 +2533,8 @@ %1$s Если это невозможно, подключите устройство к компьютеру с ADB и выполните команду ниже. Затем вернитесь сюда и проверьте снова. Сессии Steam могут запускаться. Эта версия Android не использует это ограничение. + Ограничение дочерних процессов обходит DroidDeck + DroidDeck запускает большинство программ сеанса в процессах, которые Android не учитывает, поэтому сеанс остаётся намного ниже лимита и параметры разработчика можно не включать. Steam и некоторые его вспомогательные процессы по-прежнему учитываются. Включите «Отключить ограничения для дочерних процессов» в разделе «Для разработчиков» и оставьте этот раздел включенным. В этой версии Android нет такого переключателя. Измените настройку с этого устройства через отладку по Wi-Fi. В этой сборке нет загрузки для этой копии DroidDeck. @@ -3260,9 +3301,11 @@ Недостаточно места (свободно %1$s, нужно %2$s) Свободное место неизвестно Положение изображения + Положение изображения (Альбомная) + Положение изображения (Портретная) Сверху Снизу - По центру (по умолчанию) + По центру Слева Справа Хранилище @@ -4231,4 +4274,9 @@ Эта игра устанавливает свою версию для Linux. Установите её из Steam. Масштаб игры Настройте увеличение игры от 100% до 300% + Ярлык в игре + Показывать ярлык Smart Glasses + Показывать плавающую кнопку Smart Glasses поверх игры. + Используется профиль %1$s: %2$s + Используется профиль по умолчанию: %1$s diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 506e6226ab..4bbd572c0a 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 @@ -1176,6 +1168,11 @@ Agentens verktyg är inte installerade: %1$s Skicka inte Bifoga + Filer + Tillåt åtkomst till bilder + Välj fler bilder + Inga bilder än + Tangentbord Ta bort Standard Resonemangsnivå @@ -1249,6 +1246,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 @@ -1307,6 +1309,31 @@ Knappstorlek Adaptiva spakar Spelvibration + Redmagic Air Triggers + Öppna + Använd Air Triggers + Slår på axelavtryckarna utan RedMagics avtryckarpanel eller markeringar. De trycker i stället på knappar i pekskärmslayouten. + Vänster Air Trigger + Höger Air Trigger + Sparas för den här layouten + Vibration + Vibrerar när en Air Trigger vidrörs + Ljuseffekt på skärmen + Lyser upp skärmkanten under en Air Trigger när den vidrörs + LED-stämningseffekter vid beröring + Av + Fast + Puls + Åtgärd för vänster Air Trigger + Åtgärd för höger Air Trigger + Enkeltryck + Långt tryck + Snabbeld + Inställningar för snabbeld + Klickfrekvens + Låg + Normal + Hög Styrspakens dödzon Steam-knappen QAM-knappen @@ -1314,6 +1341,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 +2168,7 @@ Vänster Mitten Höger + Delad Steams snabbåtkomstmeny är inte tillgänglig än. Statistik i spelet HUD på nedre skärmen @@ -2304,7 +2342,8 @@ Laddar ned Steam-klienten · %1$s En installation av ett kompatibilitetsverktyg pågår redan Stoppa den aktiva sessionen innan du installerar kompatibilitetsverktyg - Kunde inte hitta en ARM64-utgåva av %1$s + Kunde inte hitta en %2$s-utgåva av %1$s + Anti-cheat Minst 4 GB ledigt utrymme plus nedladdningens storlek krävs för att installera %1$s Laddar ned %1$s %2$s Försöker ladda ned igen · försök %1$d av %2$d @@ -2441,6 +2480,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 +3240,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 +4193,9 @@ 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. + Använder profilen %1$s: %2$s + Använder standardprofilen: %1$s diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index adca121cf7..9a8d17b824 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 ถูกตั้งให้ปิดเซสชันนี้ ติดตั้งแล้ว พร้อมดาวน์โหลด @@ -1173,6 +1165,11 @@ ยังไม่ได้ติดตั้งเครื่องมือของเอเจนต์: %1$s ไม่ต้องส่ง แนบ + ไฟล์ + อนุญาตให้เข้าถึงรูปภาพ + เลือกรูปภาพเพิ่ม + ยังไม่มีรูปภาพ + แป้นพิมพ์ นำออก ค่าเริ่มต้น ระดับการใช้เหตุผล @@ -1246,6 +1243,11 @@ เตรียม เชื่อมต่อการดีบักแบบไร้สายไม่ได้; จับคู่จะเปิดใช้งาน จับคู่ + Quest ไม่มีหน้าจอจับคู่ จากคอมพิวเตอร์ ให้รันหนึ่งครั้ง: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS และ adb tcpip 5555 จากนั้นแตะอนุญาตและยอมรับข้อความในเฮดเซ็ต + อนุญาต + ยอมรับ “อนุญาตการแก้ไขข้อบกพร่องไหม” ในเฮดเซ็ต โดยเลือกอนุญาตเสมอ + เชื่อมต่อไม่ได้ ยอมรับข้อความแก้ไขข้อบกพร่องในเฮดเซ็ต หรือหากไม่มีข้อความขึ้น ให้รัน adb tcpip 5555 จากคอมพิวเตอร์แล้วลองอีกครั้ง + เข้าถึงการแก้ไขข้อบกพร่องแบบไร้สายไม่ได้ แตะอนุญาตเพื่อตั้งค่าใหม่ ติดตั้ง ลงชื่อเข้าใช้ PR #%1$d @@ -1301,6 +1303,31 @@ ขนาดปุ่ม สติ๊กแบบปรับอัตโนมัติ การสั่นของเกม + Redmagic Air Triggers + เปิด + ใช้ Air Triggers + เปิดทริกเกอร์ไหล่โดยไม่แสดงแผงทริกเกอร์หรือเครื่องหมายของ RedMagic และให้กดปุ่มในการจัดวางแบบสัมผัสแทน + Air Trigger ซ้าย + Air Trigger ขวา + บันทึกไว้สำหรับการจัดวางนี้ + การสั่น + สั่นเมื่อแตะ Air Trigger + เอฟเฟกต์แสงบนหน้าจอ + ทำให้ขอบหน้าจอใต้ Air Trigger สว่างขึ้นเมื่อแตะ + เอฟเฟกต์ไฟ LED บรรยากาศเมื่อแตะ + ปิด + ติดค้าง + กะพริบเป็นจังหวะ + การทำงานของ Air Trigger ซ้าย + การทำงานของ Air Trigger ขวา + แตะครั้งเดียว + กดค้าง + ยิงรัว + การตั้งค่ายิงรัว + ความถี่ในการคลิก + ต่ำ + ปกติ + สูง เดดโซนของแอนะล็อกสติ๊ก ปุ่ม Steam ปุ่ม QAM @@ -1308,6 +1335,16 @@ ใช้ Joy-Con เป็นคอนโทรลเลอร์ VR ขณะที่ SteamVR ทำงาน Joy-Con แต่ละตัวจะกลายเป็นมือ ชี้ไปข้างหน้าแล้วกด Home หรือ Capture ค้างไว้เพื่อจัดให้อยู่ตรงกลางอีกครั้ง ภาพเคลื่อนไหว + แบบฝ้า + แสดงวอลเปเปอร์แบบเบลอไว้ด้านหลังตัวเปิดแอป ใช้แบตเตอรี่มากขึ้น + วอลเปเปอร์แบบฝ้า + การ์ดแบบฝ้า + การ์ดและกลุ่มจะเห็นวอลเปเปอร์เล็กน้อย เมนูและกล่องโต้ตอบยังคงทึบ + ต้องเปิดวอลเปเปอร์แบบฝ้า + ความโปร่งใสของวอลเปเปอร์ + ปริมาณวอลเปเปอร์ที่มองทะลุได้ + ความโปร่งใสของการ์ด + ปริมาณวอลเปเปอร์ที่มองทะลุการ์ดได้ เตือนเมื่อพื้นที่เก็บข้อมูลเหลือน้อย ถามก่อนเริ่ม Steam เมื่อพื้นที่ว่างน้อยกว่า 10 GB การจัดวาง @@ -2107,6 +2144,7 @@ ซ้าย กึ่งกลาง ขวา + แบ่งหน้าจอ เมนูเข้าถึงด่วนของ Steam ยังไม่พร้อมใช้งาน สถิติในเกม HUD หน้าจอล่าง @@ -2279,7 +2317,8 @@ กำลังดาวน์โหลดไคลเอนต์ Steam · %1$s มีการติดตั้งเครื่องมือความเข้ากันได้อื่นกำลังทำงานอยู่แล้ว หยุดเซสชันที่กำลังทำงานก่อนติดตั้งเครื่องมือความเข้ากันได้ - ไม่พบรุ่นที่เผยแพร่แบบ ARM64 สำหรับ %1$s + ไม่พบรุ่นที่เผยแพร่แบบ %2$s สำหรับ %1$s + ระบบป้องกันการโกง ต้องมีพื้นที่ว่างอย่างน้อย 4 GB รวมกับขนาดดาวน์โหลดเพื่อติดตั้ง %1$s กำลังดาวน์โหลด %1$s %2$s กำลังลองดาวน์โหลดใหม่ · ครั้งที่ %1$d จาก %2$d @@ -2416,6 +2455,8 @@ %1$s หากทำไม่ได้ ให้เชื่อมต่ออุปกรณ์นี้กับคอมพิวเตอร์ที่มี ADB แล้วรันคำสั่งด้านล่าง กลับมาที่นี่แล้วตรวจสอบอีกครั้ง เซสชัน Steam สามารถเริ่มได้ Android รุ่นนี้ไม่ใช้ขีดจำกัดนี้ + DroidDeck จัดการขีดจำกัดโปรเซสลูกให้ + DroidDeck เรียกใช้โปรแกรมส่วนใหญ่ของเซสชันในโปรเซสที่ Android ไม่นับ เซสชันจึงต่ำกว่าขีดจำกัดมาก และปิดตัวเลือกสำหรับนักพัฒนาซอฟต์แวร์ไว้ได้ Steam และโปรเซสตัวช่วยบางตัวของ Steam ยังคงถูกนับ เปิด “ปิดการจำกัดการประมวลผลข้อมูลย่อย” ในตัวเลือกสำหรับนักพัฒนา และเปิดตัวเลือกสำหรับนักพัฒนาไว้ต่อไปหลังจากนั้น Android รุ่นนี้ไม่มีสวิตช์สำหรับสิ่งนี้ ใช้ Wireless debugging เพื่อเปลี่ยนค่าจากอุปกรณ์นี้ บิลด์นี้ไม่มีให้ดาวน์โหลดสำหรับสำเนานี้ของ DroidDeck @@ -3170,9 +3211,11 @@ %1$s ชม. %1$d นาที ตำแหน่งภาพ + ตำแหน่งภาพ (แนวนอน) + ตำแหน่งภาพ (แนวตั้ง) บน ล่าง - กลาง (ค่าเริ่มต้น) + กลาง ซ้าย ขวา พื้นที่จัดเก็บ @@ -4120,4 +4163,9 @@ เกมนี้ติดตั้งเวอร์ชัน Linux ของตัวเอง ให้ติดตั้งจาก Steam ซูมเกม ปรับการขยายเกมตั้งแต่ 100% ถึง 300% + ทางลัดในเกม + แสดงทางลัด Smart Glasses + แสดงปุ่ม Smart Glasses แบบลอยทับบนเกม + ใช้โปรไฟล์ %1$s: %2$s + ใช้โปรไฟล์เริ่มต้น: %1$s diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 3960ffac55..4b42db49c9 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 @@ -1168,6 +1160,11 @@ Ajan araçları yüklenmedi: %1$s Gönderme Ekle + Dosyalar + Fotoğraflara erişime izin ver + Daha fazla fotoğraf seç + Henüz fotoğraf yok + Klavye Kaldır Varsayılan Akıl yürütme çabası @@ -1241,6 +1238,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 @@ -1299,6 +1301,31 @@ Düğme boyutu Uyarlanabilir çubuklar Oyun titreşimi + Redmagic Air Triggers + Aç + Air Triggers kullan + Omuz tetiklerini RedMagic tetik paneli veya işaretleri olmadan açar. Bunun yerine dokunmatik düzenin düğmelerine basarlar. + Sol Air Trigger + Sağ Air Trigger + Bu düzen için kaydedilir + Titreşim + Bir Air Trigger\'a dokunulduğunda titrer + Ekran ışık efekti + Bir Air Trigger\'a dokunulduğunda altındaki ekran kenarını aydınlatır + Dokunma atmosfer LED efektleri + Kapalı + Sabit + Nabız + Sol Air Trigger işlemi + Sağ Air Trigger işlemi + Tek dokunma + Uzun basma + Hızlı ateş + Hızlı ateş ayarları + Tıklama sıklığı + Düşük + Normal + Yüksek Çubuk ölü bölgesi Steam düğmesi QAM düğmesi @@ -1306,6 +1333,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 +2160,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 @@ -2296,7 +2334,8 @@ Steam istemcisi indiriliyor · %1$s Zaten çalışan bir uyumluluk aracı yüklemesi var Uyumluluk araçlarını yüklemeden önce etkin oturumu durdurun - %1$s için bir ARM64 yayını bulunamadı + %1$s için bir %2$s yayını bulunamadı + Anti-cheat %1$s\'i yüklemek için indirme boyutuna ek olarak en az 4 GB boş alan gerekir %1$s %2$s indiriliyor İndirme yeniden deneniyor · %2$d denemenin %1$d\'i @@ -2433,6 +2472,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 +3240,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 +4193,9 @@ 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. + %1$s profili kullanılıyor: %2$s + Varsayılan profil kullanılıyor: %1$s diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 727d6660f4..90903be02d 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 налаштовано завершувати цей сеанс Встановлено Доступно для завантаження @@ -1182,6 +1174,11 @@ Інструменти агента не встановлено: %1$s Не надсилати Прикріпити + Файли + Дозволити доступ до фото + Вибрати ще фото + Поки немає фото + Клавіатура Видалити За замовчуванням Рівень міркувань @@ -1257,6 +1254,11 @@ Підготувати Бездротове налагодження недоступне; «Сполучити» увімкне його Сполучити + У Quest немає екрана підключення. Один раз виконайте на комп’ютері: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS і adb tcpip 5555. Потім торкніться «Дозволити» й підтвердьте запит у шоломі + Дозволити + Підтвердьте «Дозволити налагодження?» у шоломі, позначивши «Завжди дозволяти» + Не вдалося підключитися. Підтвердьте запит на налагодження в шоломі, а якщо його не було, виконайте adb tcpip 5555 на комп’ютері й спробуйте ще раз + Бездротове налагодження недоступне. Торкніться «Дозволити», щоб налаштувати його знову Установити Увійти PR #%1$d @@ -1321,6 +1323,31 @@ Розмір кнопок Адаптивні стики Вібрація гри + Redmagic Air Triggers + Відкрити + Використовувати Air Triggers + Вмикає плечові тригери без панелі та міток RedMagic. Натомість вони натискають кнопки сенсорної розкладки. + Лівий Air Trigger + Правий Air Trigger + Зберігається для цієї розкладки + Вібрація + Вібрує під час дотику до Air Trigger + Світловий ефект на екрані + Підсвічує край екрана під Air Trigger під час дотику + LED-ефекти атмосфери під час дотику + Вимк. + Постійно + Пульсація + Дія лівого Air Trigger + Дія правого Air Trigger + Одне торкання + Довге натискання + Швидка стрільба + Налаштування швидкої стрільби + Частота натискань + Низька + Звичайна + Висока Мертва зона стіка Кнопка Steam Кнопка QAM @@ -1328,6 +1355,16 @@ Joy-Con як VR-контролери Поки працює SteamVR, кожен Joy-Con стає рукою. Спрямуйте його вперед і утримуйте Home або Capture, щоб знову його відцентрувати. Анімації + Матове скло + Показує розмиті шпалери за лаунчером. Витрачає більше заряду. + Матові шпалери + Матові картки + Крізь картки та групи трохи просвічують шпалери. Меню й діалоги лишаються непрозорими. + Потрібні матові шпалери. + Прозорість шпалер + Наскільки просвічують шпалери. + Прозорість карток + Наскільки шпалери просвічують крізь картки. Попереджати про брак місця Питати перед запуском Steam, якщо вільно менше 10 ГБ. Розкладка @@ -2181,6 +2218,7 @@ Ліворуч По центру Праворуч + Розділений Меню швидкого доступу Steam ще недоступне. Ігрова статистика HUD на нижньому екрані @@ -2356,7 +2394,8 @@ Завантаження клієнта Steam · %1$s Встановлення інструмента сумісності вже триває Зупиніть активний сеанс, перш ніж встановлювати інструменти сумісності - Не вдалося знайти випуск ARM64 для %1$s + Не вдалося знайти випуск %2$s для %1$s + Античит Щоб встановити %1$s, потрібно щонайменше 4 GB вільного місця плюс розмір завантаження Завантаження %1$s %2$s Повтор завантаження · спроба %1$d з %2$d @@ -2493,6 +2532,8 @@ %1$s Якщо це неможливо, підключіть цей пристрій до комп’ютера з ADB і виконайте команду нижче. Потім поверніться сюди і перевірте ще раз. Сеанси Steam можуть запускатися. Ця версія Android не використовує це обмеження. + Обмеження дочірніх процесів обходить DroidDeck + DroidDeck запускає більшість програм сеансу в процесах, які Android не враховує, тож сеанс залишається значно нижче ліміту і параметри розробника можна не вмикати. Steam і деякі його допоміжні процеси все ще враховуються. Увімкніть «Вимкнути обмеження для дочірніх процесів» у розділі «Параметри розробника» і залишіть «Параметри розробника» увімкненими після цього. У цій версії Android немає перемикача для цього. Змініть це з цього пристрою за допомогою бездротового налагодження. У цій збірці немає завантаження для цієї копії DroidDeck. @@ -3259,9 +3300,11 @@ %1$s год %1$d хв Позиція зображення + Позиція зображення (Альбомна) + Позиція зображення (Книжкова) Угорі Унизу - По центру (типово) + По центру Ліворуч Праворуч Сховище @@ -4230,4 +4273,9 @@ Ця гра встановлює свою версію для Linux. Установіть її зі Steam. Масштаб гри Налаштуйте збільшення гри від 100% до 300% + Ярлик у грі + Показувати ярлик Smart Glasses + Показувати плаваючу кнопку Smart Glasses поверх гри. + Використовується профіль %1$s: %2$s + Використовується профіль за замовчуванням: %1$s diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 6803dd16a0..47a25c8975 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 @@ -1173,6 +1165,11 @@ Chưa cài công cụ của tác tử: %1$s Không gửi Đính kèm + Tệp + Cho phép truy cập ảnh + Chọn thêm ảnh + Chưa có ảnh + Bàn phím Xóa Mặc định Mức độ lập luận @@ -1246,6 +1243,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 @@ -1301,6 +1303,31 @@ Kích thước nút Cần thích ứng Rung khi chơi game + Redmagic Air Triggers + Mở + Dùng Air Triggers + Bật trigger vai mà không hiện bảng trigger hay điểm đánh dấu của RedMagic. Thay vào đó, chúng nhấn các nút của bố cục cảm ứng. + Air Trigger trái + Air Trigger phải + Được lưu cho bố cục này + Rung + Rung khi chạm vào Air Trigger + Hiệu ứng ánh sáng trên màn hình + Làm sáng cạnh màn hình bên dưới Air Trigger khi chạm vào + Hiệu ứng đèn LED không khí khi chạm + Tắt + Sáng liên tục + Nhấp nháy theo nhịp + Thao tác của Air Trigger trái + Thao tác của Air Trigger phải + Chạm một lần + Nhấn giữ + Bắn nhanh + Cài đặt bắn nhanh + Tần suất nhấp + Thấp + Bình thường + Cao Vùng chết của cần điều khiển Nút Steam Nút QAM @@ -1308,6 +1335,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 +2144,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 @@ -2279,7 +2317,8 @@ Đang tải client Steam · %1$s Một lượt cài công cụ tương thích đang chạy Dừng phiên đang hoạt động trước khi cài công cụ tương thích - Không tìm thấy bản phát hành ARM64 cho %1$s + Không tìm thấy bản phát hành %2$s cho %1$s + Anti-cheat Cần ít nhất 4 GB trống cộng với kích thước tải xuống để cài %1$s Đang tải %1$s %2$s Đang thử lại tải · lần %1$d trong %2$d @@ -2416,6 +2455,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 +3211,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 +4163,9 @@ 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. + Đang dùng hồ sơ %1$s: %2$s + Đang dùng hồ sơ mặc định: %1$s diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index e9623375c4..531a9c00ec 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 将会终止此会话 已安装 可下载 @@ -1256,6 +1248,11 @@ 智能体工具未安装:%1$s 不发送 添加附件 + 文件 + 允许访问照片 + 选择更多照片 + 还没有照片 + 键盘 移除 默认 推理强度 @@ -1329,6 +1326,11 @@ 准备 无线调试无法连接;配对即可开启 配对 + Quest 没有配对界面。请在电脑上运行一次:adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 和 adb tcpip 5555。然后点按“允许”,并在头显中接受提示 + 允许 + 在头显中接受“允许调试吗?”,并勾选“始终允许” + 无法连接。请在头显中接受调试提示;如果没有出现提示,请在电脑上运行 adb tcpip 5555 后重试 + 无法连接无线调试。点按“允许”重新设置 安装 登录 PR #%1$d @@ -1384,6 +1386,31 @@ 按钮大小 自适应摇杆 游戏震动 + 红魔肩键 + 打开 + 使用肩键 + 开启肩键,但不显示红魔的肩键面板和屏幕标记。肩键改为按下触控布局中的按钮。 + 左肩键 + 右肩键 + 按此布局保存 + 振动 + 触摸肩键时振动 + 屏幕灯效 + 触摸肩键时点亮其下方的屏幕边缘 + 触控氛围灯效 + 关闭 + 常亮 + 脉冲 + 左肩键动作 + 右肩键动作 + 单击 + 长按 + 连发 + 连发设置 + 点击频率 + 低 + 正常 + 高 摇杆死区 Steam 按钮 QAM 按钮 @@ -1391,6 +1418,16 @@ 将 Joy-Con 用作 VR 手柄 SteamVR 运行时,每个 Joy-Con 都会成为一只手。将其指向前方并按住 HOME 键或截图键即可重新居中。 动画 + 毛玻璃 + 在启动器后方显示模糊的壁纸。耗电更多。 + 毛玻璃壁纸 + 毛玻璃卡片 + 卡片和分组会透出少许壁纸。菜单和对话框保持不透明。 + 需要开启毛玻璃壁纸。 + 壁纸透明度 + 壁纸透出的程度。 + 卡片透明度 + 卡片透出壁纸的程度。 存储空间不足时提醒 可用空间不足 10 GB 时,启动 Steam 前先询问。 布局 @@ -2184,6 +2221,7 @@ 左侧 居中 右侧 + 分屏 Steam 快速访问菜单暂不可用。 游戏内数据 下屏 HUD @@ -2356,7 +2394,8 @@ 正在下载 Steam 客户端 · %1$s 已有兼容性工具正在安装 安装兼容性工具前请先停止当前会话 - 找不到 %1$s 的 ARM64 发布版本 + 找不到 %1$s 的 %2$s 发布版本 + 反作弊 安装 %1$s 需要至少 4 GB 可用空间外加下载大小 正在下载 %1$s %2$s 正在重试下载 · 第 %1$d 次,共 %2$d 次 @@ -2493,6 +2532,8 @@ %1$s 如果无法做到,请将此设备连接到装有 ADB 的电脑并运行下方命令,然后返回此处重新检查。 可以启动 Steam 会话了。 此 Android 版本不使用该限制。 + 子进程限制由 DroidDeck 处理 + DroidDeck 在 Android 不计数的进程中运行大部分会话程序,使会话远低于上限,因此开发者选项可以保持关闭。Steam 及其部分辅助进程仍会被计数。 在开发者选项中打开“停止限制子进程”,之后请保持开发者选项开启。 此 Android 版本没有该开关。请使用无线调试在此设备上更改。 此构建没有适用于此 DroidDeck 副本的下载。 @@ -3170,9 +3211,11 @@ 下载内容与“组件”页面共享。在上方选择已下载的版本,即可在下次启动游戏时使用。 选择要下载的版本 画面位置 + 画面位置(横屏) + 画面位置(竖屏) 置顶 置底 - 居中(默认) + 居中 左侧 右侧 存储 @@ -4118,4 +4161,9 @@ 请先关闭 Steam 请先暂停 Steam 下载 此游戏会安装其 Linux 版本。请通过 Steam 安装。 + 游戏内快捷方式 + 显示 Smart Glasses 快捷方式 + 在游戏画面上显示悬浮的 Smart Glasses 按钮。 + 正在使用 %1$s 配置:%2$s + 正在使用默认配置:%1$s diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index ab70512c13..f497ca0fc6 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 已設定為終止此會話 已安裝 可供下載 @@ -1172,6 +1164,11 @@ 智能體工具未安裝:%1$s 不要傳送 附加 + 檔案 + 允許存取相片 + 選擇更多相片 + 尚未有相片 + 鍵盤 移除 預設 推理強度 @@ -1245,6 +1242,11 @@ 準備 無線偵錯無法連線;按「配對」即可開啟 配對 + Quest 沒有配對畫面。請在電腦上執行一次:adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 及 adb tcpip 5555。然後輕按「允許」,並在頭戴裝置中接受提示 + 允許 + 在頭戴裝置中接受「要允許偵錯嗎?」,並剔選「一律允許」 + 無法連接。請在頭戴裝置中接受偵錯提示;如果沒有出現提示,請在電腦上執行 adb tcpip 5555 後再試一次 + 無法連接無線偵錯。輕按「允許」重新設定 安裝 登入 PR #%1$d @@ -1300,6 +1302,31 @@ 按鍵大小 自動調整搖桿 遊戲震動 + 紅魔肩鍵 + 開啟 + 使用肩鍵 + 開啟肩鍵,但不顯示紅魔的肩鍵面板和螢幕標記。肩鍵改為按下觸控佈局中的按鈕。 + 左肩鍵 + 右肩鍵 + 按此佈局儲存 + 震動 + 觸摸肩鍵時震動 + 螢幕燈效 + 觸摸肩鍵時點亮其下方的螢幕邊緣 + 觸控氛圍燈效 + 關閉 + 常亮 + 脈衝 + 左肩鍵動作 + 右肩鍵動作 + 單擊 + 長按 + 連發 + 連發設定 + 點擊頻率 + 低 + 正常 + 高 搖桿死區 Steam 按鈕 QAM 按鈕 @@ -1307,6 +1334,16 @@ 將 Joy-Con 用作 VR 控制器 SteamVR 執行時,每個 Joy-Con 都會變成一隻手。將它指向前方並按住 HOME 鍵或擷取鍵,即可重新置中。 動畫 + 毛玻璃 + 在啟動器後方顯示模糊的桌布。耗電較多。 + 毛玻璃桌布 + 毛玻璃卡片 + 卡片和群組會透出少許桌布。選單和對話框保持不透明。 + 需要開啟毛玻璃桌布。 + 桌布透明度 + 桌布透出的程度。 + 卡片透明度 + 卡片透出桌布的程度。 儲存空間不足時提醒 可用空間少於 10 GB 時,啟動 Steam 前先詢問。 佈局 @@ -2106,6 +2143,7 @@ 左側 置中 右側 + 分割 Steam 快速存取選單暫時無法使用。 遊戲內數據 下方螢幕 HUD @@ -2278,7 +2316,8 @@ 正在下載 Steam 用戶端 · %1$s 已有兼容性工具正在安裝 請先停止目前的會話,再安裝兼容性工具 - 找不到 %1$s 的 ARM64 發佈版本 + 找不到 %1$s 的 %2$s 發佈版本 + 防作弊 安裝 %1$s 需要至少 4 GB 可用空間,另加下載大小 正在下載 %1$s %2$s 正在重試下載 · 第 %1$d 次,共 %2$d 次 @@ -2413,6 +2452,8 @@ %1$s 如無法這樣做,請將此裝置連接到已安裝 ADB 的電腦,並執行以下指令,然後返回這裡再檢查一次。 可以啟動 Steam 會話。 此 Android 版本不使用此限制。 + 子程序限制由 DroidDeck 處理 + DroidDeck 在 Android 不計算的程序中執行工作階段的大部分程式,讓工作階段遠低於上限,因此開發人員選項可以保持關閉。Steam 及其部分輔助程序仍會被計算。 在開發人員選項中開啟「停用對子處理過程的限制」,之後請保持開發人員選項開啟。 此 Android 版本沒有此開關。請使用無線偵錯,直接在此裝置上更改。 此版本沒有適用於此 DroidDeck 版本的下載。 @@ -3167,9 +3208,11 @@ 下載內容與「元件」頁面共用。在上方選擇已下載的版本,即可在下次啟動遊戲時使用。 選擇要下載的版本 畫面位置 + 畫面位置(橫向) + 畫面位置(直向) 置頂 置底 - 置中(預設) + 置中 左側 右側 儲存空間 @@ -4118,4 +4161,9 @@ 請先關閉 Steam 請先暫停 Steam 下載 此遊戲會安裝其 Linux 版本。請透過 Steam 安裝。 + 遊戲內捷徑 + 顯示 Smart Glasses 捷徑 + 在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。 + 正在使用 %1$s 設定檔:%2$s + 正在使用預設設定檔:%1$s diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index b2e20baea0..1c0a3db86f 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 已設定為結束此工作階段 已安裝 可下載 @@ -1172,6 +1164,11 @@ 智慧代理工具未安裝:%1$s 不要傳送 附加 + 檔案 + 允許存取相片 + 選擇更多相片 + 還沒有相片 + 鍵盤 移除 預設 推理強度 @@ -1245,6 +1242,11 @@ 準備 無線偵錯無法連線;配對即可開啟 配對 + Quest 沒有配對畫面。請在電腦上執行一次:adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 和 adb tcpip 5555。接著輕觸「允許」,並在頭戴式裝置中接受提示 + 允許 + 在頭戴式裝置中接受「要允許偵錯嗎?」,並勾選「一律允許」 + 無法連線。請在頭戴式裝置中接受偵錯提示;如果沒有出現提示,請在電腦上執行 adb tcpip 5555 後再試一次 + 無法連上無線偵錯。輕觸「允許」重新設定 安裝 登入 PR #%1$d @@ -1300,6 +1302,31 @@ 按鍵大小 自適應搖桿 遊戲震動 + 紅魔肩鍵 + 開啟 + 使用肩鍵 + 開啟肩鍵,但不顯示紅魔的肩鍵面板和螢幕標記。肩鍵改為按下觸控版面配置中的按鈕。 + 左肩鍵 + 右肩鍵 + 依此版面配置儲存 + 震動 + 觸碰肩鍵時震動 + 螢幕燈效 + 觸碰肩鍵時點亮其下方的螢幕邊緣 + 觸控氛圍燈效 + 關閉 + 恆亮 + 脈衝 + 左肩鍵動作 + 右肩鍵動作 + 單擊 + 長按 + 連發 + 連發設定 + 點擊頻率 + 低 + 正常 + 高 搖桿死區 Steam 按鈕 QAM 按鈕 @@ -1307,6 +1334,16 @@ 將 Joy-Con 當作 VR 控制器 SteamVR 執行時,每個 Joy-Con 都會變成一隻手。將它指向前方並按住 HOME 鍵或擷取鍵,即可重新置中。 動畫 + 毛玻璃 + 在啟動器後方顯示模糊的桌布。較為耗電。 + 毛玻璃桌布 + 毛玻璃卡片 + 卡片和群組會透出少許桌布。選單和對話方塊保持不透明。 + 需要開啟毛玻璃桌布。 + 桌布透明度 + 桌布透出的程度。 + 卡片透明度 + 卡片透出桌布的程度。 儲存空間不足時提醒 可用空間少於 10 GB 時,啟動 Steam 前先詢問。 版面配置 @@ -2106,6 +2143,7 @@ 左側 置中 右側 + 分割 Steam 快速存取選單暫時無法使用。 遊戲內數據 下螢幕 HUD @@ -2278,7 +2316,8 @@ 正在下載 Steam 用戶端 · %1$s 已有相容性工具正在安裝 安裝相容性工具前,請先停止執行中的工作階段 - 找不到 %1$s 的 ARM64 發行版本 + 找不到 %1$s 的 %2$s 發行版本 + 反作弊 安裝 %1$s 需要至少 4 GB 可用空間,再加上下載大小 正在下載 %1$s %2$s 正在重試下載 · 第 %1$d 次,共 %2$d 次 @@ -2413,6 +2452,8 @@ %1$s 如果無法這麼做,請將此裝置連接到裝有 ADB 的電腦並執行下方指令,然後返回這裡重新檢查。 可以啟動 Steam 工作階段。 此 Android 版本不使用這項限制。 + 子程序限制由 DroidDeck 處理 + DroidDeck 在 Android 不計算的程序中執行工作階段的大部分程式,讓工作階段遠低於上限,因此開發人員選項可以保持關閉。Steam 及其部分輔助程序仍會被計算。 在開發人員選項中開啟「停止限制子程序」,之後請保持開發人員選項開啟。 此 Android 版本沒有這個開關。請使用無線偵錯,直接在此裝置上變更。 此組建版本沒有適用於此 DroidDeck 複本的下載檔案。 @@ -3167,9 +3208,11 @@ 下載內容與「元件」頁面共用。在上方選擇已下載的版本,即可在下次啟動遊戲時使用。 選擇要下載的版本 畫面位置 + 畫面位置(橫向) + 畫面位置(直向) 置頂 置底 - 置中(預設) + 置中 左側 右側 儲存空間 @@ -4118,4 +4161,9 @@ 請先關閉 Steam 請先暫停 Steam 下載 此遊戲會安裝其 Linux 版本。請透過 Steam 安裝。 + 遊戲內捷徑 + 顯示 Smart Glasses 捷徑 + 在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。 + 正在使用 %1$s 設定檔:%2$s + 正在使用預設設定檔:%1$s diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3627ce6603..c9a8dd1d3d 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 @@ -678,6 +667,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 @@ -707,7 +699,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 @@ -1163,6 +1170,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 @@ -1202,6 +1224,10 @@ Not loaded: %1$s Waiting for a restart Kept + + %d kept build + %d kept builds + For another version Rebuild Deletes this build from the device @@ -1304,6 +1330,11 @@ Agent tools not installed: %1$s Don\'t send Attach + Files + Allow photo access + Choose more photos + No photos yet + Keyboard Remove Default Reasoning effort @@ -1392,6 +1423,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 @@ -1463,6 +1499,31 @@ Button size Adaptive sticks Game vibration + Redmagic Air Triggers + Open + Use Air Triggers + Turns on the shoulder triggers without RedMagic\'s trigger panel or markers. They press buttons of the touch layout instead. + Left Air Trigger + Right Air Trigger + Saved for this layout + Vibration + Vibrates when an Air Trigger is touched + Screen light effect + Lights up the screen edge under an Air Trigger when it is touched + Touch atmosphere LED effects + Off + Steady + Pulse + Left Air Trigger action + Right Air Trigger action + Single tap + Long press + Rapid fire + Rapid fire settings + Click frequency + Low + Normal + High Stick dead zone Steam button QAM button @@ -1470,6 +1531,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 @@ -2414,6 +2485,7 @@ Left Center Right + Split Steam\'s Quick Access menu is not available yet. In-game stats Bottom screen HUD @@ -2597,7 +2669,8 @@ A compatibility tool install is already running Stop the active session before installing compatibility tools - Could not find an ARM64 release for %1$s + Could not find an %2$s release for %1$s + Anti-Cheat At least 4 GB free plus the download size is required to install %1$s Downloading %1$s %2$s Retrying download · attempt %1$d of %2$d @@ -2744,6 +2817,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. @@ -2798,6 +2873,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 @@ -2805,6 +2883,8 @@ Shared by Steam and Desktop. Applies live. Shared by Steam and Desktop. FSR, GSR and NIS apply when enlarging the session image. Sharpen only also works without enlargement. + Using %1$s profile: %2$s + Using Default profile: %1$s Filter sharpness %1$s Sets scaling to %2$s. Match screen (%1$d×%2$d) @@ -3383,6 +3463,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 @@ -3534,11 +3617,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. @@ -4347,6 +4432,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 @@ -4475,4 +4561,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/DeviceReportBuildDateTest.kt b/app/src/test/java/com/droiddeck/launcher/core/DeviceReportBuildDateTest.kt new file mode 100644 index 0000000000..21e4ad4206 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/DeviceReportBuildDateTest.kt @@ -0,0 +1,16 @@ +package com.droiddeck.launcher.core + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class DeviceReportBuildDateTest { + @Test fun theFirmwareBuildTimeIsShownInUtc() { + assertEquals("2024-11-08 17:47 UTC", DeviceReport.buildDate(1_731_088_027_000L)) + } + + @Test fun anUnsetBuildTimeIsUnknown() { + assertNull(DeviceReport.buildDate(0L)) + assertNull(DeviceReport.buildDate(-1L)) + } +} 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/RedMagicAirTriggersTest.kt b/app/src/test/java/com/droiddeck/launcher/input/RedMagicAirTriggersTest.kt new file mode 100644 index 0000000000..83c75a2970 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/RedMagicAirTriggersTest.kt @@ -0,0 +1,358 @@ +package com.droiddeck.launcher.input + +import android.hardware.input.InputManager +import android.os.Looper +import android.provider.Settings +import android.view.InputDevice +import android.view.KeyCharacterMap +import android.view.KeyEvent +import java.io.File +import java.time.Duration +import java.util.concurrent.Executor +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.InputDeviceBuilder + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class]) +class RedMagicAirTriggersTest { + private val events = mutableListOf() + private val router = InputRouter(object : InputOutput { + override fun key(code: Int, down: Boolean) { events += "key:$code:$down" } + override fun button(code: Int, down: Boolean) { events += "button:$code:$down" } + override fun pointer(dx: Float, dy: Float) {} + override fun scroll(steps: Int) {} + override fun command(command: InputCommand) { events += command.name } + override fun command(command: InputCommand, role: InputRole) { events += "${command.name}:$role" } + override fun requestMotion() {} + }) + private val context = RuntimeEnvironment.getApplication() + private val bridge = PadBridge(File(context.cacheDir, "air-trigger-input")) + private val input = AirTriggerInput(bridge) + private val lt = InputSurfaceElement(InputControl.LT, .1f, .1f, .1f, .1f) + private val rt = InputSurfaceElement(InputControl.RT, .8f, .1f, .1f, .1f) + private val jump = InputSurfaceElement(InputControl.A, .8f, .8f, .1f, .1f, id = "custom:jump", name = "Jump") + private val stick = InputSurfaceElement(InputControl.LS, .1f, .7f, .2f, .2f) + private val layout = SavedInputLayout("pad", "Pad", listOf(lt, rt, jump, stick)) + + @Before fun setup() { bridge.setInputRouter(router); DeckControls.setRouter(router) } + @After fun close() { input.close(); bridge.stop(); DeckControls.setRouter(null); DeckControls.releaseAll() } + + private fun bind(vararg actions: Pair) { + bridge.setInputProfile(InputProfile("test", elements = mapOf(InputRole.PRIMARY to mapOf(*actions)))) + } + private fun setups(vararg chosen: Pair) = chosen.associate { (trigger, element) -> trigger to AirTriggerSetup(element) } + private fun down(trigger: AirTrigger, enabled: Boolean = true, repeat: Int = 0) = input.onKey(trigger, KeyEvent.ACTION_DOWN, repeat, enabled) + private fun up(trigger: AirTrigger) = input.onKey(trigger, KeyEvent.ACTION_UP, 0, true) + private fun idle(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms)) + + private fun keyboard(id: Int, name: String, vararg keys: Int, external: Boolean = false): InputDevice { + val device = InputDeviceBuilder.newBuilder().setId(id).setName(name).setDescriptor("keyboard-$id") + .setExternal(external).setSources(InputDevice.SOURCE_KEYBOARD) + .setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build() + val manager = shadowOf(context.getSystemService(InputManager::class.java)) + manager.addInputDevice(device) + manager.addInputDeviceKeys(id, keys) + return device + } + + @Test fun onlyTheTriggerDeviceKeysAreAirTriggers() { + val triggers = keyboard(10, "nubia_tgk_aw_sar0_ch0") + val externalKeyboard = keyboard(11, "Keychron K2", KeyEvent.KEYCODE_F7, KeyEvent.KEYCODE_F8, external = true) + assertEquals(AirTrigger.LEFT, AirTrigger.of(KeyEvent.KEYCODE_F7, triggers)) + assertEquals(AirTrigger.RIGHT, AirTrigger.of(KeyEvent.KEYCODE_F8, triggers)) + assertNull(AirTrigger.of(KeyEvent.KEYCODE_F7, externalKeyboard)) + assertNull(AirTrigger.of(KeyEvent.KEYCODE_F8, null)) + assertNull(AirTrigger.of(KeyEvent.KEYCODE_VOLUME_DOWN, triggers)) + } + + @Test fun theUnnamedInternalKeyboardCanContainBothTriggers() { + val left = KeyEvent.KEYCODE_F7 + val right = KeyEvent.KEYCODE_F8 + val merged = keyboard(10, "", left, right, KeyEvent.KEYCODE_POWER) + assertEquals(AirTrigger.LEFT, AirTrigger.of(left, merged)) + assertEquals(AirTrigger.RIGHT, AirTrigger.of(right, merged)) + assertNull(AirTrigger.of(left, keyboard(11, "", left, right, external = true))) + assertNull(AirTrigger.of(left, keyboard(12, "", left))) + assertNull(AirTrigger.of(left, keyboard(-1, "", left, right))) + } + + @Test fun theTriggerLightUsesTheCodeRedMagicsSettingsGiveTheChosenEffect() { + val settings = """{"version":1,"shoulder_effects":{"close":"02000000","steady":"02101009","pulse":"021"},"selection":"02101000"}""" + assertEquals("02101009", RedMagicAirTriggers.shoulderEffect(settings, AirTriggerLed.STEADY)) + assertEquals("02000000", RedMagicAirTriggers.shoulderEffect(settings, AirTriggerLed.OFF)) + assertEquals("02102000", RedMagicAirTriggers.shoulderEffect(settings, AirTriggerLed.PULSE)) + assertEquals("02101000", RedMagicAirTriggers.shoulderEffect(null, AirTriggerLed.STEADY)) + assertEquals("02102000", RedMagicAirTriggers.shoulderEffect("not json", AirTriggerLed.PULSE)) + } + + @Test fun openingShowsTheIdleLightAndAppliesAgainAfterGameSpacesOwnSetup() { + val calls = mutableListOf() + val worker = RedMagicAirTriggers.worker + val lights = RedMagicAirTriggers.lights + RedMagicAirTriggers.worker = Executor { it.run() } + RedMagicAirTriggers.lights = object : TriggerLights { + override fun request(action: Int) { calls += "$action" } + override fun setEffect(effect: String) { calls += effect } + } + Settings.Global.putString(context.contentResolver, "lighting_shoulder_config_json", """{"shoulder_effects":{"pulse":"02102000"}}""") + AirTriggerPrefs.setLed(context, AirTriggerLed.PULSE) + try { + val opened = listOf("110", "02102000", "107", "109") + RedMagicAirTriggers.open(context) + assertEquals(opened, calls) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(opened + opened, calls) + RedMagicAirTriggers.restore(context) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(10)) + assertEquals(opened + opened + "111", calls) + } finally { + RedMagicAirTriggers.worker = worker + RedMagicAirTriggers.lights = lights + } + } + + @Test fun triggersDefaultToTheLayoutTriggersAndFollowAChoiceThatStillExists() { + assertEquals(lt, AirTriggerButtons.resolve(layout, AirTrigger.LEFT, null)) + assertEquals(rt, AirTriggerButtons.resolve(layout, AirTrigger.RIGHT, null)) + assertEquals(jump, AirTriggerButtons.resolve(layout, AirTrigger.LEFT, "custom:jump")) + assertEquals(lt, AirTriggerButtons.resolve(layout, AirTrigger.LEFT, "custom:removed")) + assertEquals(listOf(lt, rt, jump), AirTriggerButtons.options(layout)) + } + + @Test fun aLayoutWithoutTriggersStillOffersTheControllerTriggers() { + val buttons = SavedInputLayout("buttons", "Buttons", listOf(jump)) + assertEquals(listOf("custom:jump", "legacy:lt", "legacy:rt"), AirTriggerButtons.options(buttons).map { it.id }) + assertEquals("legacy:rt", AirTriggerButtons.resolve(buttons, AirTrigger.RIGHT, null).id) + assertEquals("legacy:lt", AirTriggerButtons.resolve(null, AirTrigger.LEFT, null).id) + } + + @Test fun touchFeedbackStartsOffWithASteadyLight() { + assertFalse(AirTriggerPrefs.vibration(context)) + assertFalse(AirTriggerPrefs.screenLight(context)) + assertEquals(AirTriggerLed.STEADY, AirTriggerPrefs.led(context)) + AirTriggerPrefs.setVibration(context, true) + AirTriggerPrefs.setScreenLight(context, true) + AirTriggerPrefs.setLed(context, AirTriggerLed.OFF) + assertTrue(AirTriggerPrefs.vibration(context)) + assertTrue(AirTriggerPrefs.screenLight(context)) + assertEquals(AirTriggerLed.OFF, AirTriggerPrefs.led(context)) + } + + @Test fun actionsAndRatesAreSavedPerLayoutBesideTheButton() { + assertEquals(AirTriggerAction.TAP, AirTriggerPrefs.action(context, "pad", AirTrigger.LEFT)) + assertEquals(RapidFireRate.NORMAL, AirTriggerPrefs.rate(context, "pad", AirTrigger.LEFT)) + AirTriggerPrefs.setButton(context, "pad", AirTrigger.LEFT, "custom:jump") + AirTriggerPrefs.setAction(context, "pad", AirTrigger.LEFT, AirTriggerAction.RAPID) + AirTriggerPrefs.setRate(context, "pad", AirTrigger.LEFT, RapidFireRate.HIGH) + assertEquals("custom:jump", AirTriggerPrefs.button(context, "pad", AirTrigger.LEFT)) + assertEquals(AirTriggerAction.RAPID, AirTriggerPrefs.action(context, "pad", AirTrigger.LEFT)) + assertEquals(RapidFireRate.HIGH, AirTriggerPrefs.rate(context, "pad", AirTrigger.LEFT)) + assertEquals(AirTriggerAction.TAP, AirTriggerPrefs.action(context, "pad", AirTrigger.RIGHT)) + assertEquals(AirTriggerAction.TAP, AirTriggerPrefs.action(context, "other", AirTrigger.LEFT)) + } + + @Test fun aLongPressLatchesTheButtonUntilTheNextTouch() { + val touches = mutableListOf() + val latch = AirTriggerInput(bridge, touched = { trigger, down -> touches += "$trigger:$down" }) + bind("legacy:lt" to InputAction.Keys(listOf(42))) + latch.configure(mapOf(AirTrigger.LEFT to AirTriggerSetup(lt, AirTriggerAction.LATCH))) + latch.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + assertTrue(latch.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true)) + idle(1_000) + assertEquals(listOf("key:42:true"), events) + latch.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + assertEquals(listOf("key:42:true", "key:42:false"), events) + latch.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + latch.close() + assertEquals(listOf("key:42:true", "key:42:false"), events) + assertEquals(listOf("LEFT:true", "LEFT:false", "LEFT:true", "LEFT:false"), touches) + } + + @Test fun aLongPressOnAToggleButtonLetsGoOnTheNextTouch() { + val screen = mutableListOf() + val latch = AirTriggerInput(bridge, { id, _, held, _ -> screen += "$id:$held"; true }) + bind("custom:jump" to InputAction.Keys(listOf(57))) + latch.configure(mapOf(AirTrigger.LEFT to AirTriggerSetup(jump.copy(toggle = true), AirTriggerAction.LATCH))) + latch.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true); latch.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + latch.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true); latch.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + latch.close() + assertEquals(listOf("key:57:true", "key:57:false"), events) + assertEquals(emptyList(), screen) + } + + @Test fun aSingleTapHoldsTheButtonWhileTheTriggerIsTouched() { + bind("legacy:lt" to InputAction.Keys(listOf(42))) + input.configure(mapOf(AirTrigger.LEFT to AirTriggerSetup(lt, AirTriggerAction.TAP))) + down(AirTrigger.LEFT) + idle(1_000) + assertEquals(listOf("key:42:true"), events) + up(AirTrigger.LEFT) + assertEquals(listOf("key:42:true", "key:42:false"), events) + } + + @Test fun rapidFireClicksAtTheChosenRateWhileHeld() { + val rapid = AirTriggerInput(bridge) + bind("legacy:lt" to InputAction.Keys(listOf(42))) + rapid.configure(mapOf(AirTrigger.LEFT to AirTriggerSetup(lt, AirTriggerAction.RAPID, RapidFireRate.NORMAL))) + rapid.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + idle(950) + assertEquals(10, events.size) + assertEquals("key:42:true", events.first()) + assertEquals(5, events.count { it == "key:42:true" }) + rapid.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + idle(1_000) + rapid.close() + assertEquals(10, events.size) + assertEquals("key:42:false", events.last()) + } + + @Test fun liftingTheTriggerMidClickEndsRapidFireReleased() { + val rapid = AirTriggerInput(bridge) + bind("legacy:lt" to InputAction.Keys(listOf(42))) + rapid.configure(mapOf(AirTrigger.LEFT to AirTriggerSetup(lt, AirTriggerAction.RAPID, RapidFireRate.HIGH))) + rapid.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + idle(120) + rapid.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + idle(500) + rapid.close() + assertEquals(listOf("key:42:true", "key:42:false", "key:42:true", "key:42:false"), events) + } + + @Test fun rapidFireClicksAToggleButtonAsAPlainOneThatEndsReleased() { + val screen = mutableListOf() + val rapid = AirTriggerInput(bridge, { id, _, held, _ -> screen += "$id:$held"; true }) + bind("custom:jump" to InputAction.Keys(listOf(57))) + rapid.configure(mapOf(AirTrigger.LEFT to AirTriggerSetup(jump.copy(toggle = true), AirTriggerAction.RAPID))) + rapid.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + idle(250) + rapid.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + rapid.close() + assertEquals(listOf("key:57:true", "key:57:false", "key:57:true", "key:57:false"), events) + assertEquals(emptyList(), screen) + } + + @Test fun changingTheActionMidPressLetsGoOfTheButtonUntilTheNextTouch() { + bind("legacy:lt" to InputAction.Keys(listOf(42))) + input.configure(setups(AirTrigger.LEFT to lt)) + down(AirTrigger.LEFT) + input.configure(mapOf(AirTrigger.LEFT to AirTriggerSetup(lt, AirTriggerAction.RAPID))) + idle(500) + assertTrue(up(AirTrigger.LEFT)) + assertEquals(listOf("key:42:true", "key:42:false"), events) + down(AirTrigger.LEFT) + idle(250) + up(AirTrigger.LEFT) + assertEquals(listOf("key:42:true", "key:42:false", "key:42:true", "key:42:false", "key:42:true", "key:42:false"), events) + } + + @Test fun choicesAreSavedPerLayoutAndTheToggleStartsOff() { + assertFalse(AirTriggerPrefs.enabled(context)) + AirTriggerPrefs.setEnabled(context, true) + AirTriggerPrefs.setButton(context, "pad", AirTrigger.LEFT, "custom:jump") + assertTrue(AirTriggerPrefs.enabled(context)) + assertEquals("custom:jump", AirTriggerPrefs.button(context, "pad", AirTrigger.LEFT)) + assertNull(AirTriggerPrefs.button(context, "pad", AirTrigger.RIGHT)) + assertNull(AirTriggerPrefs.button(context, "other", AirTrigger.LEFT)) + } + + @Test fun aTriggerPressesTheChosenLayoutButton() { + bind("legacy:lt" to InputAction.Keys(listOf(42)), "custom:jump" to InputAction.Keys(listOf(57))) + input.configure(setups(AirTrigger.LEFT to lt, AirTrigger.RIGHT to jump)) + assertTrue(down(AirTrigger.LEFT)); assertTrue(down(AirTrigger.RIGHT)) + assertTrue(up(AirTrigger.RIGHT)); assertTrue(up(AirTrigger.LEFT)) + assertEquals(listOf("key:42:true", "key:57:true", "key:57:false", "key:42:false"), events) + } + + @Test fun keyRepeatsAndPressesWhileInputIsBlockedAreSwallowed() { + bind("legacy:lt" to InputAction.Keys(listOf(42))) + input.configure(setups(AirTrigger.LEFT to lt)) + assertTrue(down(AirTrigger.LEFT, enabled = false)) + assertTrue(up(AirTrigger.LEFT)) + assertTrue(down(AirTrigger.LEFT)); assertTrue(down(AirTrigger.LEFT, repeat = 1)) + assertTrue(up(AirTrigger.LEFT)) + assertEquals(listOf("key:42:true", "key:42:false"), events) + } + + @Test fun switchingOffReleasesAHeldButtonAndLetsTheKeysThrough() { + bind("legacy:lt" to InputAction.Keys(listOf(42))) + input.configure(setups(AirTrigger.LEFT to lt)) + assertFalse(down(AirTrigger.RIGHT)) + down(AirTrigger.LEFT) + input.configure(emptyMap()) + assertEquals(listOf("key:42:true", "key:42:false"), events) + assertTrue(up(AirTrigger.LEFT)) + assertFalse(down(AirTrigger.LEFT)) + assertEquals(2, events.size) + } + + @Test fun aButtonShownOnScreenTakesThePressAndTheTriggersLight() { + val screen = mutableListOf() + val lights = mutableListOf() + val onScreen = AirTriggerInput(bridge, { id, trigger, held, cancelled -> screen += "$id:$trigger:$held:$cancelled"; id == "custom:jump" }, + { trigger, down -> lights += if (down) trigger.pressLight else trigger.releaseLight }) + bind("legacy:lt" to InputAction.Keys(listOf(42)), "custom:jump" to InputAction.Keys(listOf(57))) + onScreen.configure(setups(AirTrigger.LEFT to lt, AirTrigger.RIGHT to jump)) + onScreen.onKey(AirTrigger.RIGHT, KeyEvent.ACTION_DOWN, 0, true); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + onScreen.onKey(AirTrigger.RIGHT, KeyEvent.ACTION_UP, 0, true); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, false); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + onScreen.close() + assertEquals(listOf("custom:jump:RIGHT:true:false", "legacy:lt:LEFT:true:false", "custom:jump:RIGHT:false:false"), screen) + assertEquals(listOf("key:42:true", "key:42:false"), events) + assertEquals(listOf(108, 106, 109, 107), lights) + } + + @Test fun switchingOffLetsGoOfTheOnScreenButton() { + val screen = mutableListOf() + val onScreen = AirTriggerInput(bridge, { id, trigger, held, cancelled -> screen += "$id:$trigger:$held:$cancelled"; true }) + onScreen.configure(setups(AirTrigger.LEFT to jump)) + onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + onScreen.configure(emptyMap()) + assertTrue(onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true)) + assertEquals(listOf("custom:jump:LEFT:true:false", "custom:jump:LEFT:false:true"), screen) + } + + @Test fun aForcedReleaseDoesNotRunACommandButtonButAKeyUpDoes() { + bind("custom:jump" to InputAction.Command(InputCommand.KEYBOARD)) + input.configure(setups(AirTrigger.LEFT to jump)) + down(AirTrigger.LEFT) + input.release() + up(AirTrigger.LEFT) + assertEquals(emptyList(), events) + down(AirTrigger.LEFT); up(AirTrigger.LEFT) + assertEquals(listOf("KEYBOARD:PRIMARY"), events) + } + + @Test fun aToggleLatchedWhileItsButtonWasHiddenIsHandedToTheShownButton() { + var shown = false + val screen = mutableListOf() + val onScreen = AirTriggerInput(bridge, { id, _, held, _ -> screen += "$id:$held"; shown }) + bind("custom:jump" to InputAction.Keys(listOf(57))) + onScreen.configure(setups(AirTrigger.LEFT to jump.copy(toggle = true))) + onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + assertEquals(listOf("key:57:true"), events) + shown = true + onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + assertEquals(listOf("key:57:true", "key:57:false"), events) + onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + onScreen.close() + assertEquals(listOf("custom:jump:true", "custom:jump:true", "custom:jump:false"), screen) + } + + @Test fun choosingAnotherButtonMovesTheTriggerWithoutLeavingTheOldOneHeld() { + bind("legacy:lt" to InputAction.Keys(listOf(42)), "custom:jump" to InputAction.Keys(listOf(57))) + input.configure(setups(AirTrigger.LEFT to lt)) + down(AirTrigger.LEFT) + input.configure(setups(AirTrigger.LEFT to jump)) + up(AirTrigger.LEFT) + down(AirTrigger.LEFT); up(AirTrigger.LEFT) + assertEquals(listOf("key:42:true", "key:42:false", "key:57:true", "key:57:false"), events) + } +} 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/DesktopLanguageIndexSourceTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt index 3b4b008c50..03bd7746da 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt @@ -41,7 +41,18 @@ class DesktopLanguageIndexSourceTest { context = ApplicationProvider.getApplicationContext() DownloadSource.init(context) DownloadSource.setMode(context, DownloadSource.MODE_MIRROR) + } + + // Downloads other tests leave running also go through this proxy while it is set, so it is set only around [block]. + private fun tunnelsDuring(block: () -> Unit): List { DownloadSource.setProxy(context, "127.0.0.1:${proxy.localPort}") + tunnels.clear() + try { + block() + } finally { + DownloadSource.setProxy(context, "") + } + return tunnels.toList() } @After fun tearDown() { @@ -51,12 +62,12 @@ class DesktopLanguageIndexSourceTest { } @Test fun mirrorModeWouldOtherwiseSendTheIndexThroughAMirror() { - Downloader.downloadString(base + "desktop-kde.i18n.txt") - assertTrue(tunnels.toString(), tunnels.any { host -> DownloadSource.MIRRORS.any { it.host == host } }) + val seen = tunnelsDuring { Downloader.downloadString(base + "desktop-kde.i18n.txt") } + assertTrue(seen.toString(), seen.any { host -> DownloadSource.MIRRORS.any { it.host == host } }) } @Test fun indexIsFetchedOnlyFromGithubInMirrorMode() { - assertNull(DesktopLanguage.fetchIndex(base)) - assertEquals(listOf("github.com"), tunnels.toList()) + val seen = tunnelsDuring { assertNull(DesktopLanguage.fetchIndex(base)) } + assertEquals(listOf("github.com"), seen) } } 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/EnhancedSessionLogShareTest.kt b/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt index e02523e97f..e6dd6163d6 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt @@ -14,6 +14,7 @@ import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config +import java.io.File import java.io.IOException import java.io.RandomAccessFile import java.nio.ByteBuffer @@ -436,6 +437,53 @@ class EnhancedSessionLogShareTest { SessionLogShare.clear(app) } + @Test fun theRunningSessionsGameLogIsSharedBeforeSteamsWholeClientLogs() { + val previousLogsEnabled = SessionPrefs.logsEnabled(app) + val steamLog = File(SessionPrefs.activeSteamRoot(app), "logs/console_log.txt") + var started: File? = null + try { + SessionPrefs.setLogsEnabled(app, true) + val session = SessionPaths.beginOrCurrent(app, "live-steam").also { started = it } + session.resolve("session.log").writeText("session\n") + session.resolve("steam-239250.log").writeText("wine: game log\n") + steamLog.apply { parentFile!!.mkdirs(); writeText("steam client history\n".repeat(400)) } + val limits = EnhancedShareLimits(maxFilesPerArchive = 16, maxBytesPerFile = 8192, maxBytesTotal = 4096) + + val zip = EnhancedSessionLogShare.createLegacy(app, session, limits = limits)!! + + ZipFile(zip).use { archive -> + assertEquals( + "wine: game log\n", + archive.getInputStream(archive.getEntry("${session.name}/steam-239250.log")).bufferedReader().readText(), + ) + val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")) + .bufferedReader().readText()) + val entries = manifest.getJSONArray("entries") + val records = (0 until entries.length()).map { entries.getJSONObject(it) } + assertEquals("captured", records.single { it.optString("entry") == "${session.name}/steam-239250.log" }.getString("status")) + val steam = records.single { it.optString("entry") == "${session.name}/steam/console_log.txt" } + assertEquals("live-steam", steam.getString("origin")) + assertEquals("truncated", steam.getString("status")) + assertTrue(archive.getEntry("${session.name}/steam/console_log.txt") != null) + } + + val roomy = EnhancedSessionLogShare.createLegacy(app, session)!! + + ZipFile(roomy).use { archive -> + assertEquals( + "steam client history\n".repeat(400), + archive.getInputStream(archive.getEntry("${session.name}/steam/console_log.txt")).bufferedReader().readText(), + ) + } + } finally { + SessionPaths.take()?.let { SessionPaths.release(app, it) } + started?.deleteRecursively() + steamLog.delete() + SessionPrefs.setLogsEnabled(app, previousLogsEnabled) + SessionLogShare.clear(app) + } + } + @Test fun unreadableDiscoverySubtreeKeepsOtherLogsAndMarksTheManifestPartial() { assumeFilePermissionsEnforced() assumeFalse(System.getProperty("os.name").startsWith("Windows")) 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..aed120c6f6 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,36 @@ 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)) + } + + @Test fun afterPictureInPictureTheLayerStopsVotingThirtyWhileItsOwnOverrideIsStillReported() { + val staleOverride = SessionPrefs.hostFrameCap(30f, 120f) + assertEquals(SessionPrefs.PIP_FPS, staleOverride) + val own = SessionPrefs.compositorFpsLimit(0, 0, pip = false) + assertEquals(120f, SessionPrefs.layerFrameRate(own, 120f, false), 0f) + assertEquals(staleOverride, SessionPrefs.compositorFpsLimit(0, 0, pip = false, hostCap = staleOverride)) + assertEquals(SessionPrefs.FPS_UNPACED, SessionPrefs.compositorFpsLimit(0, 0, pip = false, hostCap = SessionPrefs.hostFrameCap(120f, 120f))) + } + + @Test fun theLayerVotesOnlyTheSessionsOwnLimits() { + assertEquals(SessionPrefs.PIP_FPS.toFloat(), SessionPrefs.layerFrameRate(SessionPrefs.compositorFpsLimit(0, pip = true), 120f, false), 0f) + assertEquals(45f, SessionPrefs.layerFrameRate(SessionPrefs.compositorFpsLimit(0, 45), 120f, false), 0f) + assertEquals(60f, SessionPrefs.layerFrameRate(SessionPrefs.compositorFpsLimit(60), 120f, false), 0f) + assertEquals(120f, SessionPrefs.layerFrameRate(SessionPrefs.FPS_UNPACED, 120f, false), 0f) + } + + @Test fun blackFrameInsertionKeepsThePanelRate() { + assertEquals(120f, SessionPrefs.layerFrameRate(45, 120f, true), 0f) + } } 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/ProtonExtrasTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt index d975b6b756..33542f0f0e 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt @@ -78,7 +78,7 @@ class ProtonExtrasTest { @Test fun theSourcesInOrder() { - assertEquals(listOf("ge", "cachyos", "droiddeck", "bionic"), ProtonExtras.tools.map { it.id }) + assertEquals(listOf("ge", "cachyos", "droiddeck", "anticheat", "bionic"), ProtonExtras.tools.map { it.id }) val droiddeck = tool("droiddeck") assertEquals("DroidDeck-Proton", droiddeck.name) assertEquals("DroidDeck-Proton", droiddeck.prefix) @@ -88,6 +88,13 @@ class ProtonExtrasTest { assertFalse(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-7.5-aarch64.sha512sum")) assertFalse(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-7.5-aarch64.build-info.json")) assertFalse(tool("cachyos").assetPattern.containsMatchIn("proton-cachyos-11.0-20261005-slr-x86_64.tar.xz")) + val antiCheat = tool("anticheat") + assertEquals("Droid-Deck/DroidDeck-Proton", antiCheat.repo) + assertEquals("DroidDeck-Proton", antiCheat.prefix) + assertTrue(antiCheat.assetPattern.containsMatchIn("DroidDeck-Proton-11-14.3-x86_64.tar.gz")) + assertFalse(antiCheat.assetPattern.containsMatchIn("DroidDeck-Proton-11-14.3-x86_64.sha512sum")) + assertFalse(antiCheat.assetPattern.containsMatchIn("DroidDeck-Proton-11-14.3-aarch64.tar.gz")) + assertFalse(droiddeck.assetPattern.containsMatchIn("DroidDeck-Proton-11-14.3-x86_64.tar.gz")) } @Test @@ -181,6 +188,55 @@ class ProtonExtrasTest { assertEquals(emptyList(), ProtonExtras.installedIn(File(tools, "missing"), tool("ge"))) } + @Test + fun x86_64BuildsAreNotTakenForTheArm64Tool() { + val tools = temp.newFolder("compatibilitytools.d") + for (name in listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-14.2-x86_64")) installTool(tools, name) + File(tools, "DroidDeck-Proton-11-14.2-x86_64/files/lib/wine/x86_64-unix").mkdirs() + File(tools, "DroidDeck-Proton 11-7.5/files/lib/wine/x86_64-unix").mkdirs() + File(tools, "DroidDeck-Proton 11-7.5/files/bin-arm64").mkdirs() + assertEquals(listOf("DroidDeck-Proton 11-7.5"), ProtonExtras.installedIn(tools, tool("droiddeck"))) + assertTrue(ProtonExtras.x86_64Build(File(tools, "DroidDeck-Proton-11-14.2-x86_64"))) + assertEquals(listOf("DroidDeck-Proton-11-14.2-x86_64"), ProtonExtras.installedIn(tools, tool("anticheat"))) + } + + @Test + fun theX86_64BuildIsFetchedOnlyForAnInstalledAntiCheatRuntimeUnlessTheUserRemovedIt() { + val context = RuntimeEnvironment.getApplication() + val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d") + tools.deleteRecursively() + File(context.filesDir, "proton-latest.json").writeText( + """{"anticheat":{"tag":"DroidDeck-Proton-11-14.3","at":1}}""") + val antiCheat = tool("anticheat") + ProtonExtras.setDeclined(context, false, "anticheat") + assertNull(ProtonExtras.missing(context, antiCheat) { false }) + assertEquals("DroidDeck-Proton-11-14.3", ProtonExtras.missing(context, antiCheat) { true }) + ProtonExtras.setDeclined(context, true, "anticheat") + assertNull(ProtonExtras.missing(context, antiCheat) { true }) + assertFalse(ProtonExtras.declined(context)) + ProtonExtras.setDeclined(context, false, "anticheat") + installTool(tools, "DroidDeck-Proton 11-14.2") + File(tools, "DroidDeck-Proton 11-14.2/files/bin-arm64").mkdirs() + assertEquals("DroidDeck-Proton-11-14.3", ProtonExtras.missing(context, antiCheat) { true }) + installTool(tools, "DroidDeck-Proton-11-14.2-x86_64") + File(tools, "DroidDeck-Proton-11-14.2-x86_64/files/lib/wine/x86_64-unix").mkdirs() + assertNull(ProtonExtras.missing(context, antiCheat) { true }) + } + + @Test + fun anAntiCheatRuntimeInAnyLibraryCounts() { + val first = temp.newFolder("library-a") + val second = temp.newFolder("library-b") + File(second, "steamapps").mkdirs() + assertFalse(ProtonExtras.antiCheatRuntimeIn(listOf(first, second))) + File(second, "steamapps/appmanifest_1161040.acf").writeText("") + assertTrue(ProtonExtras.antiCheatRuntimeIn(listOf(first, second))) + assertFalse(ProtonExtras.antiCheatRuntimeIn(listOf(first))) + File(first, "steamapps").mkdirs() + File(first, "steamapps/appmanifest_1826330.acf").writeText("") + assertTrue(ProtonExtras.antiCheatRuntimeIn(listOf(first))) + } + @Test fun interruptedBuildsAreNotReportedAsInstalled() { val tools = temp.newFolder("compatibilitytools.d") @@ -218,6 +274,7 @@ class ProtonExtrasTest { .put("ge", JSONObject().put("tag", "GE-Proton11-7").put("at", now - 60_000)) .put("cachyos", JSONObject().put("tag", "cachyos-11.0-20261005-slr").put("at", now - 60_000)) .put("droiddeck", JSONObject().put("tag", "DroidDeck-Proton-11-7.6").put("at", now - ProtonExtras.CHECK_EVERY_MS + 60_000)) + .put("anticheat", JSONObject().put("tag", "DroidDeck-Proton-11-7.6").put("at", now - 60_000)) File(context.filesDir, "proton-latest.json").writeText(latest.toString()) assertFalse(ProtonExtras.checkLatest(context, now = now)) assertEquals("DroidDeck-Proton-11-7.6", ProtonExtras.update(context, tool("droiddeck"))) 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/SessionLogShareZipTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt index 087c1a9980..94537df59b 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt @@ -10,6 +10,7 @@ import java.util.concurrent.TimeUnit import java.util.zip.ZipFile import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.After import org.junit.Before @@ -116,6 +117,33 @@ class SessionLogShareZipTest { } } + @Test fun theSessionsGameLogsAreSharedBeforeBulkySteamClientLogsUseTheBudget() { + val session = File(LinuxRuntime.logDir(app), "2026-12-05-08-steam").apply { mkdirs() } + val out = File(app.getExternalFilesDir(null), "agent-logs/budget") + try { + File(session, "session.log").writeText("booted\n") + val steam = File(session, "steam").apply { mkdirs() } + listOf("console_log.txt", "webhelper_js.txt", "cef_log.txt").forEach { + File(steam, it).writeText("client line\n".repeat(600)) + } + File(session, "steam-1568590.log").writeText("Proton: x86-64\nerr:module:load\n") + File(session, "games").apply { mkdirs() }.resolve("dxvk.log").writeText("info: DXVK\n") + val limits = EnhancedShareLimits(maxFilesPerArchive = 512, maxBytesPerFile = 8192, maxBytesTotal = 6000) + + val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out, limits = limits)!! + ZipFile(zip).use { archive -> + assertNotNull(archive.getEntry("${session.name}/session.log")) + val proton = archive.getEntry("${session.name}/steam-1568590.log")!! + assertTrue(archive.getInputStream(proton).bufferedReader().readText().contains("err:module:load")) + assertTrue(archive.entries().toList().any { it.name.startsWith("${session.name}/games/") }) + assertTrue(archive.entries().toList().count { it.name.startsWith("${session.name}/steam/") } < 3) + } + } finally { + out.deleteRecursively() + session.deleteRecursively() + } + } + @Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() { val logs = LinuxRuntime.logDir(app) val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsUpscalerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsUpscalerTest.kt new file mode 100644 index 0000000000..36708bc145 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsUpscalerTest.kt @@ -0,0 +1,79 @@ +package com.droiddeck.launcher.session + +import android.content.Context +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 + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class SessionPrefsUpscalerTest { + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + @Test fun gameOverridesAreIsolatedAndFallBackToTheGlobalFilter() { + SessionPrefs.setUpscaler(context, 4) + SessionPrefs.setGameUpscaler(context, "12345", 7) + + assertEquals(4, SessionPrefs.upscaler(context)) + assertEquals(7, SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + assertEquals(4, SessionPrefs.screenEffectsUpscaler(context, "game:54321")) + assertTrue(SessionPrefs.hasGameUpscalerOverride(context, "12345")) + assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "54321")) + assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345")) + } + + @Test fun resettingGameOverrideRestoresTheGlobalFilter() { + SessionPrefs.setUpscaler(context, 3) + SessionPrefs.setGameUpscaler(context, "12345", 6) + + SessionPrefs.clearGameUpscaler(context, "12345") + + assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345")) + assertEquals(3, SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + } + + @Test fun screenEffectsUpscalerApiKeepsGameFiltersSeparateFromScreenEffects() { + SessionPrefs.setUpscaler(context, 4) + SessionPrefs.setScreenEffectsUpscaler(context, "game:12345", 8) + + assertEquals(8, SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345")) + } + + @Test fun legacyGameFilterOverridesRemainReadableAndCanBeReset() { + val profile = JSONObject().put("upscaler", 6) + val profiles = JSONObject().put("game:12345", profile) + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit() + .putString("screenEffects.profiles", profiles.toString()).commit() + + assertTrue(SessionPrefs.hasGameUpscalerOverride(context, "12345")) + assertEquals(6, SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + + SessionPrefs.clearGameUpscaler(context, "12345") + + assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345")) + assertEquals(2, SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345")) + } + + @Test fun deletingGameScreenEffectsProfileClearsUpscalerOverrideEvenWithoutEffectsProfile() { + SessionPrefs.setGameUpscaler(context, "12345", 6) + + SessionPrefs.deleteScreenEffectsProfile(context, "game:12345") + + assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345")) + assertEquals(SessionPrefs.upscaler(context), SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + } +} 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/SessionVisibilityPolicyTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt index 708241662e..5bbf3bcc19 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt @@ -5,6 +5,21 @@ import org.junit.Assert.assertTrue import org.junit.Test class SessionVisibilityPolicyTest { + @Test fun attachmentPickerKeepsTheDockedDrawerAliveDuringActivityStop() { + assertFalse(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop( + screenOff = false, dockedDrawerOpen = true, attachmentPickerOpen = true, + )) + assertTrue(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop( + screenOff = false, dockedDrawerOpen = true, attachmentPickerOpen = false, + )) + assertTrue(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop( + screenOff = false, dockedDrawerOpen = false, attachmentPickerOpen = true, + )) + assertFalse(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop( + screenOff = true, dockedDrawerOpen = false, attachmentPickerOpen = false, + )) + } + @Test fun handsetScreenStateControlsActivityOnDefaultDisplay() { assertFalse(SessionVisibilityPolicy.isHidden(true, true, true, false)) assertTrue(SessionVisibilityPolicy.isHidden(true, false, true, true)) 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/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/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/ComponentDownloadsDrawerTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/ComponentDownloadsDrawerTest.kt index 4d3f1852a5..f52ae99690 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/ComponentDownloadsDrawerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/ComponentDownloadsDrawerTest.kt @@ -3,24 +3,31 @@ package com.droiddeck.launcher.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Text +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Modifier 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.assertIsFocused import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performSemanticsAction import androidx.compose.ui.test.pressKey import androidx.compose.ui.test.requestFocus import com.droiddeck.launcher.R import com.droiddeck.launcher.session.ComponentsManager import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -67,6 +74,29 @@ class ComponentDownloadsDrawerTest { assertEquals(listOf(nightly), requested) } + @Config(qualifiers = "w800dp-h800dp") + @Test fun nightlySelectionSurvivesCrossingTheColumnThreshold() { + val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test") + val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test") + val twoColumns = mutableStateOf(false) + lateinit var menu: MenuHost + show(catalog = listOf(stable, nightly), twoColumns = twoColumns, captureHost = { menu = it }) + val chooser = compose.onNodeWithTag("cmp-download-dxvk") + val nightlyRow = compose.onNodeWithText(nightly.file.removeSuffix(".wcp")) + val narrowLeft = chooser.getUnclippedBoundsInRoot().left + chooser.performSemanticsAction(SemanticsActions.OnClick) + compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.comp_channel_nightly)).performClick() + nightlyRow.assertExists() + compose.runOnIdle { menu.open = null; twoColumns.value = true } + assertTrue(chooser.getUnclippedBoundsInRoot().left > narrowLeft) + chooser.performSemanticsAction(SemanticsActions.OnClick) + nightlyRow.assertExists() + compose.runOnIdle { menu.open = null; twoColumns.value = false } + assertEquals(narrowLeft, chooser.getUnclippedBoundsInRoot().left) + chooser.performSemanticsAction(SemanticsActions.OnClick) + nightlyRow.assertExists() + } + @Test fun controllerPicksNightlyOnItsTabThenDownloadsItFromTheRow() { val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test") val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test") @@ -107,18 +137,28 @@ class ComponentDownloadsDrawerTest { checking: Boolean = false, onRefresh: () -> Unit = {}, onDownload: (ComponentsManager.CatalogItem) -> Unit = {}, + twoColumns: State? = null, + captureHost: (MenuHost) -> Unit = {}, ) { compose.setContent { inputMode = LocalInputModeManager.current DroidDeckTheme { Column(Modifier.verticalScroll(rememberScrollState())) { - ComponentDownloadsDrawerGroup( - host = rememberMenuHost(), catalog = catalog, catalogAt = 0, - checking = checking, - packages = listOf(ComponentsManager.Package(stored.file, "dxvk", "2.3", "", 100)), - downloads = downloads, onRefresh = onRefresh, onDownload = onDownload, - track = { Modifier.testTag(it) }, - ) + val host = rememberMenuHost() + captureHost(host) + val content: @androidx.compose.runtime.Composable () -> Unit = { + ComponentDownloadsDrawerGroup( + host = host, catalog = catalog, catalogAt = 0, + checking = checking, + packages = listOf(ComponentsManager.Package(stored.file, "dxvk", "2.3", "", 100)), + downloads = downloads, onRefresh = onRefresh, onDownload = onDownload, + track = { Modifier.testTag(it) }, + ) + } + if (twoColumns == null) content() else DrawerColumns(twoColumns.value) { + SettingsGroup("Profile") { Text("Profile settings") } + content() + } } } } 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/DrawerColumnsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/DrawerColumnsTest.kt new file mode 100644 index 0000000000..a5201db5b4 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/DrawerColumnsTest.kt @@ -0,0 +1,48 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.height +import androidx.compose.material3.Text +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.unit.dp +import org.junit.Assert.assertTrue +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 = [28], qualifiers = "w800dp-h600dp") +class DrawerColumnsTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Test fun theComponentNoteStaysInItsGroupAndSixGroupsSplitEvenly() { + val note = "Component note" + val componentRow = "Component row" + compose.setContent { + DroidDeckTheme { + DrawerColumns(two = true) { + repeat(3) { index -> Box(Modifier.height(32.dp).testTag("left-$index")) } + DrawerComponentSettingsGroup(note) { Text(componentRow) } + repeat(2) { index -> Box(Modifier.height(32.dp).testTag("right-$index")) } + } + } + } + val left = (0..2).map { compose.onNodeWithTag("left-$it").getUnclippedBoundsInRoot() } + val right = (0..1).map { compose.onNodeWithTag("right-$it").getUnclippedBoundsInRoot() } + val group = compose.onNodeWithText(componentRow).getUnclippedBoundsInRoot() + val footer = compose.onNodeWithText(note).getUnclippedBoundsInRoot() + assertTrue(left.all { it.left == left.first().left }) + assertTrue(right.all { it.left == right.first().left && it.left > left.first().left }) + assertTrue(group.left >= right.first().left) + assertTrue(footer.left >= right.first().left) + assertTrue(footer.top >= group.bottom) + assertTrue(right.first().top >= footer.bottom) + assertTrue(left.zipWithNext().all { (first, next) -> first.bottom <= next.top }) + } +} 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..786ee5203a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt @@ -77,6 +77,59 @@ class InputSurfaceTouchTest { assertFalse(state().isDown(PadState.A)) } + @Test fun anOutsideHoldPressesAndLightsTheButtonAlongsideAFinger() { + val surface = view.inputSurface + val button = (surface.javaClass.getDeclaredField("customCanvas").also { it.isAccessible = true }.get(surface) as ViewGroup).getChildAt(0) + fun lit() = button.javaClass.getDeclaredMethod("getHighlighted").also { it.isAccessible = true }.invoke(button) as Boolean + + assertTrue(surface.hold(a.id, 0, true)) + assertTrue(state().isDown(PadState.A)) + assertTrue(lit()) + touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f)) + touch(MotionEvent.ACTION_UP, 1 to (800f to 240f)) + assertTrue(state().isDown(PadState.A)) + assertTrue(surface.hold(a.id, 0, false)) + assertFalse(state().isDown(PadState.A)) + assertFalse(lit()) + assertFalse(surface.hold("custom:missing", 0, true)) + } + + @Test fun aCancelledTouchLeavesAnOutsideHoldOnTheButton() { + val surface = view.inputSurface + assertTrue(surface.hold(a.id, 0, true)) + touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f)) + touch(MotionEvent.ACTION_CANCEL, 1 to (800f to 240f)) + assertTrue(state().isDown(PadState.A)) + assertTrue(surface.hold(a.id, 0, false)) + assertFalse(state().isDown(PadState.A)) + } + + @Test fun releasingAllInputLetsGoOfAnOutsideHold() { + val surface = view.inputSurface + val button = (surface.javaClass.getDeclaredField("customCanvas").also { it.isAccessible = true }.get(surface) as ViewGroup).getChildAt(0) + fun lit() = button.javaClass.getDeclaredMethod("getHighlighted").also { it.isAccessible = true }.invoke(button) as Boolean + + assertTrue(surface.hold(a.id, 0, true)) + view.releaseAll() + assertFalse(state().isDown(PadState.A)) + assertFalse(lit()) + touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f)) + assertTrue(state().isDown(PadState.A)) + touch(MotionEvent.ACTION_UP, 1 to (800f to 240f)) + assertTrue(surface.hold(a.id, 0, false)) + assertFalse(state().isDown(PadState.A)) + } + + @Test fun aCancelledOutsideHoldDoesNotRunTheButtonsCommand() { + val surface = view.inputSurface + assertTrue(surface.hold(keyboard.id, 0, true)) + assertTrue(surface.hold(keyboard.id, 0, false, cancelled = true)) + assertEquals(emptyList(), events) + assertTrue(surface.hold(keyboard.id, 0, true)) + assertTrue(surface.hold(keyboard.id, 0, false)) + assertEquals(listOf("KEYBOARD:PRIMARY"), events) + } + @Test fun steamDeckStylingKeepsTheHeldButtonAndItsHitArea() { val button = a.copy(buttonShape = InputButtonShape.CIRCLE) show(button) @@ -227,6 +280,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/anti-cheat.md b/docs/development/anti-cheat.md new file mode 100644 index 0000000000..d287aea85e --- /dev/null +++ b/docs/development/anti-cheat.md @@ -0,0 +1,54 @@ +# Easy Anti-Cheat and BattlEye + +On a Steam Deck, Proton loads Valve's anti-cheat runtimes (Proton EasyAntiCheat Runtime, app 1826330, and +Proton BattlEye Runtime, app 1161040). Their bridge libraries are x86 only, so the ARM64 DroidDeck-Proton +cannot load them. Games that need them run an x86-64 DroidDeck-Proton under FEX instead. + +## Routing + +The Proton launchers (`steam-compatibility`: the built-in DroidDeck-Proton launcher and the wrapper put around +every tool in `compatibilitytools.d`) check each `run` and `waitforexitandrun` before any ARM64 setup: + +- **Condition.** The game folder (`STEAM_COMPAT_INSTALL_PATH`, three levels deep) holds one of + `EasyAntiCheat/Settings.json`, `easyanticheat_x64.so`, `BEClient_x64.so` or `BEService_x64.exe`. No + title, app ID or device list is involved. +- **Chosen tool.** Only launches through DroidDeck's own Proton (the built-in launcher or a `DroidDeck-Proton*` + folder) are moved. A game set to any other tool, such as GE-Proton, Bionic or Valve's Proton, in DroidDeck or + in Steam's Properties, runs on that tool and the launcher logs that it was chosen. +- **Tool.** The newest `compatibilitytools.d/DroidDeck-Proton*` whose layout is x86-64 + (`files/lib/wine/x86_64-unix`, no `files/bin-arm64`). +- **Runtime.** `PROTON_EAC_RUNTIME` or `PROTON_BATTLEYE_RUNTIME` when it already points at a folder with the + bridge libraries, otherwise the runtime's folder in any Steam library. +- **Launch.** `droiddeck-fex proton /proton `: FEX with the Steam Linux Runtime rootfs, + keeping the game's own `STEAM_COMPAT_DATA_PATH` prefix. + +Without the x86-64 tool or the runtime files the launch stays on ARM64 and the launcher logs why. +`DROIDDECK_ANTICHEAT=off` in the game's launch options keeps it on ARM64. Picking the x86-64 tool for a +game in Steam always runs it under FEX. + +## Why the x86-64 build needs its own Wine patches + +Android kernels use 39-bit user address spaces. Easy Anti-Cheat's launcher maps fixed memory at +`0x7001_0000_0000`, which FEX serves from emulated guest pages (`tools/fex/patches/0027`). Exclusive load and store pairs on that +memory are emulated as a compare-and-swap, so hosts without LSE atomics work too. `tools/fex/probes/guest-high-memory.c` +checks loads, stores, atomics, iovec system calls, `madvise` and code written through a high alias. The x86-64 Wine +in DroidDeck-Proton carries `ntdll-fixed-allocations-above-host-address-limit.patch` (fixed mappings above +the host limit go to the emulator) and `ntdll-keep-libc-in-native-syscall-dispatch-range.patch` (the +re-armed syscall user dispatch range keeps libc native). Stock x86-64 Proton stops after "Hack native +syscalls" on the same game. + +Easy Anti-Cheat's launcher attaches to the game with ptrace, stops it on a `rt_sigprocmask` call, runs its +own loader and restores the registers it saved at the stop. The call then returns `ENOSYS` without writing +the old mask, as it does on a desktop kernel. `ntdll-retry-blocking-signals-dropped-by-a-tracer.patch` +retries the block once when it fails, so Wine never restores an uninitialised mask that blocks `SIGSYS`. + +## The container's procfs + +Android mounts `/proc` with `hidepid=invisible,gid=3009`, and Easy Anti-Cheat refuses that mount with +launch error 261. Without root, user namespaces or PID namespaces, no procfs instance without those options +can be mounted. Every program in the container runs as the app's user and already sees all of the +container's processes, as it would in a PID-namespaced sandbox on a desktop, so FEX's emulated +`/proc//mounts` and `/proc//mountinfo` show the proc mount without `hidepid=`, `gid=` and +`subset=` (`tools/fex/patches/0029`). Only x86 programs under FEX see this view; every other line of the +table is the host's. Processes of other Android users stay hidden, as host processes do from a desktop +sandbox. 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/game-environment.md b/docs/development/game-environment.md index 6036cc3a7a..8fe41b0a61 100644 --- a/docs/development/game-environment.md +++ b/docs/development/game-environment.md @@ -117,7 +117,7 @@ the UI shows a restart reminder instead of enabling logs that would be discarded | `PROTON_LOG` | `1` | | `PROTON_LOG_DIR`, `PROTON_CRASH_REPORT_DIR`, `DXVK_LOG_PATH` | The actual session log directory | | `DXVK_LOG_LEVEL` | `debug` | -| `VKD3D_DEBUG` | `info` | +| `VKD3D_DEBUG`, `VKD3D_SHADER_DEBUG` | `warn` | | `WINEDEBUG` | Valid custom channels plus Proton's standard diagnostic channels | Diagnostics take precedence over conflicting inherited, shared, or per-game log @@ -193,6 +193,14 @@ A Unity game under FEX (`UnityPlayer.dll` for Windows builds under Proton, turns it off: without TSO such games can deadlock or crash (seen with Megabonk and Crab Game). A FEX preset chosen for the game itself still applies. +A game that ships the PlayStation PC SDK runtime installer +(`install_pspc_sdk_runtime.bat`, `PsPcSdkRuntimeInstaller.msi` or +`PsPcSdkRuntimeManager.msi`, next to the executable, one folder below, or in an +Unreal launcher's `/Binaries/Win64`) gets FEX's full x87 precision. +The SDK's obfuscated x87 code depends on full precision; with reduced precision +the game crashes or hangs at startup (FEX-Emu/FEX#4556, FEX-Emu/FEX#5988). A +FEX preset or value chosen for the game itself still applies. + An Inno Setup installer added as a game runs with the Stability preset's FEX settings (full TSO, full x87 precision, no multiblock). Under the default Performance + TSO preset the 32-bit setup stub corrupts its own paths and stops 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..d4d67c7687 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -216,9 +216,10 @@ alone would then read as an installed client. NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the overlapping part of any alias that is already executable, so the first write faults and invalidates. `FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch. - - `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to - `install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure. - The guest libraries are external projects in the default build, which `install` already follows. + - `0007-cmake-install-code-without-depends` (`Fixed-upstream: FEX-2612`): CMake 4.5 rejects the + `DEPENDS` argument FEX passes to `install(CODE ...)` for the guest thunk libraries, so builds with + host thunks stopped at configure. The guest libraries are external projects in the default build, + which `install` already follows. - `0008-signal-return-restores-syscall-state`: a guest `rt_sigreturn` is a system call, so FEX's syscall stub marks every static register as spilled (`InSyscallInfo = 0xFFFF`). When the handler left RIP alone, the return resumed the interrupted JIT code without passing the stub's reset, and @@ -303,6 +304,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..3b2ccd2c84 100644 --- a/tools/agent/AGENTS.md +++ b/tools/agent/AGENTS.md @@ -44,8 +44,10 @@ from what tripped agents up on real devices. running makes Steam show "Game already running" and `launch` time out. - Session scripts are APK assets, copied into the rootfs at every session start over any local edit. A Lab build (`dd-lab-build`, see `docs/lab-builds.md`) carries app code and resources only: - session scripts, native code and assets need a new APK, such as the pull request's CI test build - (DroidDeck > Updates > Test builds). + session scripts, native code, assets and `AndroidManifest.xml` need a new APK, such as the pull + request's CI test build (DroidDeck > Updates > Test builds). `dd-lab-build` refuses changes to the + manifest, native code, Gradle files and a few startup classes, but builds session script and asset + changes without them. To try the rest of a branch, build a copy without those changes. ## Changing DroidDeck @@ -56,10 +58,17 @@ The source is checked out at `/root/DroidDeck` once the Agent tab's build tools - `dd-lab-build` builds the checkout as a Lab build and restarts DroidDeck on it. DroidDeck runs the build in a process of its own and shows its progress; `dd-lab-build` follows its log. Run it in the background and keep checking, so the user can talk to you meanwhile. The restart ends your - process, and the conversation continues on the new build. + process; DroidDeck starts you again on the new build, in the same conversation, so tell the user + what you will check then instead of asking them to message you. +- To try a change, commit it and go straight to `dd-lab-build`: it compiles the app, so a Gradle + compile first only adds time. It refuses changes since the installed build (`apkCommit` in + `droiddeckctl state`) that need a new APK. For a branch from a newer `origin/main`, cherry-pick + its commits onto a branch from `apkCommit` and build that. - 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 8e52a857da..be9cc347b7 100644 --- a/tools/bionic-runtime/tool/launch.sh +++ b/tools/bionic-runtime/tool/launch.sh @@ -52,6 +52,13 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;; DROIDDECK_GUEST_ROOT) ;; 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 @@ -86,7 +93,8 @@ RTD=$APP/.wayland-rt export VK_ICD_FILENAMES=$PACK/adapter/icd.json ADRENOTOOLS_DRIVER_PATH=$DRVDIR/ ADRENOTOOLS_HOOKS_PATH=$PACK/lib export ADRENOTOOLS_DRIVER_NAME=$(drvlib "$DRVDIR") export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/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), @@ -258,7 +266,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 } @@ -273,7 +281,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 } @@ -282,7 +290,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 @@ -426,7 +434,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 5cccf80ffa..9f78ac708b 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", "app/src/main/cpp/waylandcomp/generated", "app/src/main/cpp/waylandcomp/src/headpose_shm.h", @@ -24,6 +25,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" ], "ndk": true, @@ -32,7 +37,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 9de7efba18..70628c5638 100644 --- a/tools/components/recipes/runtime.sh +++ b/tools/components/recipes/runtime.sh @@ -12,6 +12,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/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..fd9931a9cd 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -108,7 +108,8 @@ def receiver_call(adb: str, serial: str, method: str, arg: str | None, request: raise ControlError(f"{PACKAGE} is not running and this shell has no `content` command to start it; open DroidDeck once", "APP_NOT_RUNNING") call_id = uuid.uuid4().hex[:16] remote = f"/sdcard/Android/data/{PACKAGE}/files/agent-calls/{call_id}.json" - command = ["shell", "am", "broadcast", "-a", f"{PACKAGE}.AGENT_CALL", "-p", PACKAGE, + # By component: release variants rename the package but not the receiver's intent action. + command = ["shell", "am", "broadcast", "-n", f"{PACKAGE}/com.droiddeck.launcher.agent.AgentCallReceiver", "--es", "method", method, "--es", "id", call_id] if arg is not None: command += ["--es", "arg", shlex.quote(arg)] @@ -750,13 +751,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 +796,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 +937,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/build-in-arch.sh b/tools/fex/build-in-arch.sh index dccb24f882..9adc7e93e5 100755 --- a/tools/fex/build-in-arch.sh +++ b/tools/fex/build-in-arch.sh @@ -63,6 +63,11 @@ cmake -S fex-src -B fex-build -G Ninja \ ${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"} ninja -C fex-build DESTDIR="$WORK/out" ninja -C fex-build install +mkdir -p out/usr/local/share/fex-emu +for p in tools/fex/patches/*.patch; do + p=$(basename "$p" .patch) + echo "${p#*-}" +done > out/usr/local/share/fex-emu/.droiddeck-patches install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs install -Dm644 "$(readlink -f /usr/lib/libxxhash.so.0)" out/usr/local/lib/libxxhash.so.0 bundled=$(cd out/usr/local/lib && ls -- *.so* | sort -u) diff --git a/tools/fex/patches/0007-cmake-install-code-without-depends.patch b/tools/fex/patches/0007-cmake-install-code-without-depends.patch index 6752b40280..83c0e1fb82 100644 --- a/tools/fex/patches/0007-cmake-install-code-without-depends.patch +++ b/tools/fex/patches/0007-cmake-install-code-without-depends.patch @@ -1,3 +1,4 @@ +Fixed-upstream: FEX-2612 diff --git a/CMakeLists.txt b/CMakeLists.txt index 8976588..3ae54f4 100644 --- a/CMakeLists.txt diff --git a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch index 6592a94550..327fe76a85 100644 --- a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch +++ b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch @@ -1,8 +1,8 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -index b4c7b24..643185d 100644 +index 345f4d834..085ff00a2 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr +@@ -283,12 +283,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr auto Frame = Thread->CurrentFrame; if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { diff --git a/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch index fbeec5ec96..6af2b7eb33 100644 --- a/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch +++ b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch @@ -1,5 +1,5 @@ diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h -index 02bb6bf..2e72492 100644 +index 02bb6bfef..2e724929f 100644 --- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h @@ -49,6 +49,11 @@ struct X86ContextBackup { @@ -27,10 +27,10 @@ index 02bb6bf..2e72492 100644 // Arm64 doesn't have a red zone diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -index 643185d..53179c4 100644 +index 085ff00a2..5c79d1092 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* +@@ -155,6 +155,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* #endif } @@ -62,7 +62,7 @@ index 643185d..53179c4 100644 ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) { // We can end up getting a signal at any point in our host state // Jump to a handler that saves all state so we can safely return -@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr +@@ -268,6 +293,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr } OldSP = *reinterpret_cast(GuestSP); @@ -82,7 +82,7 @@ index 643185d..53179c4 100644 } uintptr_t NewSP = OldSP; -@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS +@@ -306,6 +344,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS auto ContextBackup = StoreThreadState(Thread, Signal, ucontext); auto Frame = Thread->CurrentFrame; @@ -90,7 +90,7 @@ index 643185d..53179c4 100644 // Ref count our faults // We use this to track if it is safe to clear cache -@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS +@@ -355,6 +394,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP]; uint64_t NewGuestSP = OldGuestSP; @@ -99,7 +99,7 @@ index 643185d..53179c4 100644 // altstack is only used if the signal handler was setup with SA_ONSTACK if (GuestAction->sa_flags & SA_ONSTACK) { -@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS +@@ -364,6 +405,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS // Then that means we are hitting recursive signals and we need to walk back the stack correctly uint64_t AltStackBase = reinterpret_cast(GuestStack->ss_sp); uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size; @@ -108,7 +108,7 @@ index 643185d..53179c4 100644 if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) { // We are already in the alt stack, the rest of the code will handle adjusting this } else { -@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS +@@ -372,6 +415,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS } } @@ -149,7 +149,7 @@ index 643185d..53179c4 100644 // siginfo_t siginfo_t* HostSigInfo = reinterpret_cast(info); -@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre +@@ -510,6 +587,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre // Our ref counting doesn't matter anymore Thread->CurrentFrame->SignalHandlerRefCounter = 0; @@ -159,7 +159,7 @@ index 643185d..53179c4 100644 // Set the new PC if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) { diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h -index dfcd4b0..e4a86a9 100644 +index 0f45cf68d..408cddf71 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h @@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { diff --git a/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch index 626c726b59..cebe184aa2 100644 --- a/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch +++ b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch @@ -1,7 +1,8 @@ diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp +index 1946dc946..9f04358c5 100644 --- a/FEXCore/Source/Interface/Core/Core.cpp +++ b/FEXCore/Source/Interface/Core/Core.cpp -@@ -383,7 +383,11 @@ +@@ -383,7 +383,11 @@ bool ContextImpl::InitCore() { } void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) { @@ -15,9 +16,10 @@ diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/C void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) { diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +index ae3ed51e4..c5e656d2c 100644 --- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp -@@ -305,6 +305,9 @@ +@@ -306,6 +306,9 @@ DEF_OP(Thunk) { PushDynamicRegs(TMP1); @@ -27,7 +29,7 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr)); InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash); -@@ -320,6 +323,8 @@ +@@ -321,6 +324,8 @@ DEF_OP(Thunk) { FillStaticRegs({ .NZCV = false, }); @@ -37,9 +39,10 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In DEF_OP(ValidateCode) { diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index 5c79d1092..e8e04b056 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -@@ -107,6 +107,10 @@ +@@ -126,6 +126,10 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* #ifdef ARCHITECTURE_arm64 Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext)); @@ -50,7 +53,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou for (size_t i = 0; i < Config.SRAGPRCount; i++) { const uint8_t SRAIdxMap = Config.SRAGPRMapping[i]; if (IgnoreMask & (1U << SRAIdxMap)) { -@@ -301,12 +305,10 @@ +@@ -320,12 +324,10 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr if (Context->UContextLocation) { auto Frame = Thread->CurrentFrame; @@ -67,7 +70,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou if (Is64BitMode) { RestoreFrame_x64(Thread, Context, Frame, ucontext); -@@ -361,6 +363,9 @@ +@@ -380,6 +382,9 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo; Thread->CurrentFrame->InSyscallInfo = 0; } else { @@ -78,9 +81,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou // This is likely to cause issues but in some cases it isn't fatal // This can also happen if we have put a signal on hold, then we just reenabled the signal diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +index fa6260954..e5d92e7c5 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp -@@ -131,7 +131,7 @@ +@@ -131,7 +131,7 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) { // Restore previous `InSyscallInfo` structure. @@ -89,7 +93,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram // Hack! Go back to the top of the dispatcher top // This is only safe inside the JIT rather than anything outside of it -@@ -211,7 +211,7 @@ +@@ -211,7 +211,7 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre // If the guest modified the RIP then we need to take special precautions here if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) { // Restore previous `InSyscallInfo` structure. @@ -98,7 +102,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram // Hack! Go back to the top of the dispatcher top // This is only safe inside the JIT rather than anything outside of it -@@ -290,7 +290,7 @@ +@@ -290,7 +290,7 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) { // Restore previous `InSyscallInfo` structure. diff --git a/tools/fex/patches/0012-signal-return-applies-guest-registers.patch b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch index d97a75bee3..09c8398310 100644 --- a/tools/fex/patches/0012-signal-return-applies-guest-registers.patch +++ b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch @@ -1,7 +1,8 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +index 9e6820bf6..43898e700 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h -@@ -263,6 +263,8 @@ +@@ -266,6 +266,8 @@ private: FEXCore::Core::CpuStateFrame* Frame, void* ucontext); void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext); @@ -11,9 +12,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Sourc ///< Setup the signal frame for x64. uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup, diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +index e5d92e7c5..38dc524f1 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp -@@ -122,6 +122,32 @@ +@@ -122,6 +122,32 @@ static void SetXStateInfo(T* xstate, bool is_avx_enabled) { } } @@ -46,7 +48,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { auto* guest_uctx = reinterpret_cast(Context->UContextLocation); -@@ -202,6 +228,27 @@ +@@ -202,6 +228,27 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa const auto modulo_i = (i + CurrentOffset) % 8; memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0])); } @@ -74,7 +76,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram } } -@@ -280,6 +327,17 @@ +@@ -280,6 +327,17 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre const auto modulo_i = (i + CurrentOffset) % 8; memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); } @@ -92,7 +94,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram } } -@@ -359,6 +417,17 @@ +@@ -359,6 +417,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th const auto modulo_i = (i + CurrentOffset) % 8; memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); } diff --git a/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch b/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch index 2192b9b0af..9bdad1cebd 100644 --- a/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch +++ b/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch @@ -1,8 +1,8 @@ diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp -index 2881ad9..abc84f3 100644 +index dd2c18303..e7e88f8f2 100644 --- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp -@@ -518,7 +518,7 @@ int main(int argc, char** argv, char** const envp) { +@@ -524,7 +524,7 @@ int main(int argc, char** argv, char** const envp) { FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, Program.ProgramName); } else { // Anonymous program. @@ -12,7 +12,7 @@ index 2881ad9..abc84f3 100644 } } else { diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp -index a7a432b..4a77d87 100644 +index a7a432bbd..4a77d8716 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp @@ -441,7 +441,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname 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/fex/patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch b/tools/fex/patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch new file mode 100644 index 0000000000..b070802512 --- /dev/null +++ b/tools/fex/patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch @@ -0,0 +1,5015 @@ +From: StonkGuy <68372320+StonkGuy@users.noreply.github.com> +Subject: [PATCH] x86-64 ptrace, seccomp and /proc emulation for anti-cheat launchers + +Author: StonkGuy (https://github.com/StonkGuy/FEX) +Source: https://github.com/StonkGuy/FEX branch eac-2611 (tag eac-2611.1) +Copyright (c) StonkGuy and FEX contributors, MIT licence + +diff --git a/FEXCore/Source/CMakeLists.txt b/FEXCore/Source/CMakeLists.txt +index 61385d2c3..b515a4a02 100644 +--- a/FEXCore/Source/CMakeLists.txt ++++ b/FEXCore/Source/CMakeLists.txt +@@ -4,6 +4,7 @@ set(FEXCORE_BASE_SRCS + Interface/Config/Config.cpp + Utils/Allocator.cpp + Utils/FileLoading.cpp ++ Utils/FaultSafeRead.cpp + Utils/FileUtils.cpp + Utils/ForcedAssert.cpp + Utils/LogManager.cpp +diff --git a/FEXCore/Source/Interface/Config/Config.json.in b/FEXCore/Source/Interface/Config/Config.json.in +index 6bd89a1e5..860bd4429 100644 +--- a/FEXCore/Source/Interface/Config/Config.json.in ++++ b/FEXCore/Source/Interface/Config/Config.json.in +@@ -604,6 +604,62 @@ + "\tfull: Validate code before every run (slow)" + ] + }, ++ "ProfileSampleHz": { ++ "Type": "uint32", ++ "Default": "0", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Samples the host PC of the main guest thread this many times per second into /dev/shm/fex--samples (in-process; no ptrace).", ++ "Use with LibraryJITNaming to attribute samples to guest libraries. 0 disables." ++ ] ++ }, ++ "ProfileSampleMinThreads": { ++ "Type": "uint32", ++ "Default": "100", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "ProfileSampleHz starts the sampler in the process that reaches this many guest threads (default 100: the application,", ++ "not the hundreds of helper processes of a Steam/Wine session). 1 samples every process from its first thread.", ++ "0: no sampler thread; each SIGPROF sent from outside stores a snapshot record of the receiving thread (ring in fex--snap)." ++ ] ++ }, ++ "ProfileSampleAllThreads": { ++ "Type": "bool", ++ "Default": "false", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "ProfileSampleHz samples every guest thread instead of only the main one." ++ ] ++ }, ++ "SignalTrace": { ++ "Type": "bool", ++ "Default": "false", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Records guest signal handling events (host signal arrival, masking decisions, delivery, rt_sigreturn, sigprocmask, kill/tgkill)", ++ "into a ring buffer in /dev/shm/fex--sigtrace. For diagnosing lost signals; decode with tools/harness/sigtrace.py." ++ ] ++ }, ++ "SignalMaskFix": { ++ "Type": "bool", ++ "Default": "true", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Run guest signal handlers with the signal mask Linux gives them (the interrupted mask plus sa_mask and the signal)", ++ "and restore the interrupted mask at rt_sigreturn. With false FEX blocks only sa_mask and the signal during the handler and keeps", ++ "a stale view of the mask afterwards, so a signal handler that restores its saved mask can unblock the signal it is running for." ++ ] ++ }, ++ "SMCHotPageFaults": { ++ "Type": "uint32", ++ "Default": "32", ++ "AffectsCodeGen": "true", ++ "Desc": [ ++ "Number of self-modifying-code write faults a guest page may take before FEX stops write-protecting it.", ++ "Instead the JIT verifies the code of every instruction it translates from such a page (like SMCChecks=full, but only for that page).", ++ "Only used with SMCChecks=mtrack. 0 disables the demotion (pages stay write-protected and keep faulting)." ++ ] ++ }, + "TSOEnabled": { + "Type": "bool", + "Default": "true", +@@ -691,6 +747,16 @@ + "Should only be used for applications that have issues with this set." + ] + }, ++ "EnableCPUIDFaulting": { ++ "Type": "bool", ++ "Default": "false", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Honour ARCH_SET_CPUID. When a guest thread calls arch_prctl(ARCH_SET_CPUID, 0), CPUID from that", ++ "thread raises a #GP (SIGSEGV, si_code SI_KERNEL) like Linux with a CPUID-faulting CPU, instead of", ++ "executing transparently. Off by default, so a guest that never asks for it is unaffected." ++ ] ++ }, + "StartupSleep": { + "Type": "uint32", + "Default": "0", +diff --git a/FEXCore/Source/Interface/Context/Context.h b/FEXCore/Source/Interface/Context/Context.h +index cce4d5113..24118405d 100644 +--- a/FEXCore/Source/Interface/Context/Context.h ++++ b/FEXCore/Source/Interface/Context/Context.h +@@ -224,8 +224,12 @@ public: + + void OnCodeBufferAllocated(const std::shared_ptr&) override; + void ClearCodeCache(FEXCore::Core::InternalThreadState* Thread, bool NewCodeBuffer = true) override; +- void InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) override; +- void InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; ++ void InvalidateExecutableRangeCaches() override { ++ ExecutableRangeEpoch.fetch_add(1, std::memory_order_acq_rel); ++ } ++ bool InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) override; ++ std::atomic ExecutableRangeEpoch {}; ++ void InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached) override; + FEXCore::Utils::WritePriorityMutex::Mutex& GetCodeInvalidationMutex() override { + return CodeInvalidationMutex; + } +diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp +index 9f04358c5..02d9a280a 100644 +--- a/FEXCore/Source/Interface/Core/Core.cpp ++++ b/FEXCore/Source/Interface/Core/Core.cpp +@@ -31,6 +31,7 @@ $end_info$ + #include "Utils/Allocator.h" + #include "Utils/Allocator/HostAllocator.h" + #include "Utils/crc32.h" ++#include + #include + #include "Utils/variable_length_integer.h" + +@@ -201,8 +202,11 @@ uint32_t ContextImpl::ReconstructCompactedEFLAGS(FEXCore::Core::InternalThreadSt + case X86State::RFLAG_SF_RAW_LOC: + case X86State::RFLAG_OF_RAW_LOC: + case X86State::RFLAG_DF_RAW_LOC: ++ case X86State::RFLAG_NZCV_LOC: ++ case X86State::RFLAG_NZCV_1_LOC: ++ case X86State::RFLAG_NZCV_2_LOC: ++ case X86State::RFLAG_NZCV_3_LOC: + // Intentionally do nothing. +- // These contain multiple bits which can corrupt other members when compacted. + break; + default: EFLAGS |= uint32_t {Frame->State.flags[i]} << i; break; + } +@@ -645,11 +649,13 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue + Thread->OpDispatcher->_GuestOpcode(InstAddress - GuestRIP); + } + +- if (Config.SMCChecks == FEXCore::Config::CONFIG_SMC_FULL || Block.ForceFullSMCDetection) { ++ if (Config.SMCChecks == FEXCore::Config::CONFIG_SMC_FULL || Block.ForceFullSMCDetection || SyscallHandler->IsSMCHotPage(InstAddress)) { + auto ExistingCodePtr = reinterpret_cast(Block.Entry + BlockInstructionsLength); + auto InstAddressReg = Thread->OpDispatcher->_EntrypointOffset(GPRSize, InstAddress - GuestRIP); + +- auto Value = FEXCore::Utils::crc32(ExistingCodePtr, DecodedInfo->InstSize); ++ uint8_t InstBytes[16]; ++ const bool Readable = FEXCore::Utils::FaultSafeRead::Copy(InstBytes, ExistingCodePtr, DecodedInfo->InstSize); ++ auto Value = Readable ? FEXCore::Utils::crc32(InstBytes, DecodedInfo->InstSize) : ~0U; + auto CRC = WantsDiskCachePatching ? + Thread->OpDispatcher->_PatchableGuestCRC(IR::OpSize::i64Bit, Value, (int64_t)ExistingCodePtr, DecodedInfo->InstSize) : + Thread->OpDispatcher->Constant(Value); +@@ -730,6 +736,8 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue + Thread->OpDispatcher->InvalidOp(DecodedInfo); + } else if (Block.BlockStatus == Frontend::Decoder::DecodedBlockStatus::UNIMPLEMENTED_INST) { + Thread->OpDispatcher->UnimplementedOp(DecodedInfo); ++ } else if (Block.BlockStatus == Frontend::Decoder::DecodedBlockStatus::TOO_LONG_INST) { ++ Thread->OpDispatcher->PermissionRestrictedOp(DecodedInfo); + } else { + Thread->OpDispatcher->NoExecOrPartialOp(DecodedInfo); + } +@@ -897,9 +905,10 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ + auto LoadedCode = Thread->CPUBackend->LoadCachedCode(Hit->HostCode); + if (LoadedCode.BlockBegin) { + for (auto& CodePage : Hit->GuestPages) { +- if (Thread->LookupCache->AddBlockExecutableRange(Thread, Hit->EntryPointRIPs, CodePage, FEXCore::Utils::FEX_PAGE_SIZE)) { ++ if (!Thread->LookupCache->HasBlockExecutableRange(CodePage)) { + SyscallHandler->MarkGuestExecutableRange(Thread, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } ++ Thread->LookupCache->AddBlockExecutableRange(Thread, Hit->EntryPointRIPs, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } + + LOGMAN_THROW_A_FMT(Hit->EntryPointRIPs.size() == Hit->EntryPointHostOffsets.size(), "Mismatched Disk Cache entrypoint pairs!"); +@@ -993,9 +1002,10 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ + CodePages.reserve(BlockInfo->CodePages.size()); + CodePages.insert(CodePages.end(), BlockInfo->CodePages.begin(), BlockInfo->CodePages.end()); + for (auto CodePage : BlockInfo->CodePages) { +- if (Thread->LookupCache->AddBlockExecutableRange(Thread, BlockInfo->EntryPoints, CodePage, FEXCore::Utils::FEX_PAGE_SIZE)) { ++ if (!Thread->LookupCache->HasBlockExecutableRange(CodePage)) { + SyscallHandler->MarkGuestExecutableRange(Thread, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } ++ Thread->LookupCache->AddBlockExecutableRange(Thread, BlockInfo->EntryPoints, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } + } + +@@ -1006,10 +1016,13 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ + if (DebugData && DebugData->Relocations) { + Relocations = *DebugData->Relocations; + } +- std::span GuestCode = {reinterpret_cast(StartAddr), Length}; +- const Frontend::Decoder::DecodedBlockInformation* BlockInfo = +- NeedsAddGuestCodeRanges ? Thread->FrontendDecoder->GetDecodedBlockInfo() : nullptr; +- DiskCache.Store(Thread, Region, GuestRIP, *DiskCacheGuestCodeKey, GuestCode, CompiledCode, Relocations, BlockInfo); ++ fextl::vector GuestCodeCopy(Length); ++ if (FEXCore::Utils::FaultSafeRead::Copy(GuestCodeCopy.data(), reinterpret_cast(StartAddr), Length)) { ++ std::span GuestCode = GuestCodeCopy; ++ const Frontend::Decoder::DecodedBlockInformation* BlockInfo = ++ NeedsAddGuestCodeRanges ? Thread->FrontendDecoder->GetDecodedBlockInfo() : nullptr; ++ DiskCache.Store(Thread, Region, GuestRIP, *DiskCacheGuestCodeKey, GuestCode, CompiledCode, Relocations, BlockInfo); ++ } + } + + if (CodeMapWriter && Region && Region->FileStartVA != 0) { +@@ -1055,31 +1068,38 @@ uintptr_t ContextImpl::CompileSingleStep(FEXCore::Core::CpuStateFrame* Frame, ui + return (uintptr_t)CodePtr; + } + +-void ContextImpl::InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) { ++bool ContextImpl::InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) { + FEXCORE_PROFILE_SCOPED("InvalidateCodeBuffersCodeRange"); + + LOGMAN_THROW_A_FMT(CodeInvalidationMutex.try_lock() == false, "CodeInvalidationMutex needs to be unique_locked here"); + std::scoped_lock lk {CodeBufferListLock}; ++ bool Found = false; + auto it = CodeBufferList.begin(); + while (it != CodeBufferList.end()) { + if (auto Strong = it->lock()) { +- Strong->LookupCache->InvalidateRange(Start, Length); ++ Found |= Strong->LookupCache->InvalidateRange(Start, Length); + it++; + } else { + it = CodeBufferList.erase(it); + } + } ++ return Found; + } + +-void ContextImpl::InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) { ++void ContextImpl::InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached) { + LOGMAN_THROW_A_FMT(CodeInvalidationMutex.try_lock() == false, "CodeInvalidationMutex needs to be unique_locked here"); + + // Ensures now-modified mappings aren't cached as being in their previous non-executable state. + // Accessing FrontendDecoder is safe as the thread's code invalidation mutex must be locked here. + Thread->FrontendDecoder->ResetExecutableRangeCache(); + ++ if (!CodeMayBeCached) { ++ return; ++ } ++ + if (Thread->LookupCache->InvalidateCacheRange(Start, Length)) { + FEXCORE_PROFILE_SCOPED("InvalidateCallRet"); ++ FEXCORE_PROFILE_INSTANT_INCREMENT(Thread, AccumulatedCallRetFlushCount, 1); + + // This may cause access violations in the thread on Windows as zeroing is not atomic, this is handled by the frontend + Allocator::VirtualDontNeed(Thread->CallRetStackBase, FEXCore::Core::InternalThreadState::CALLRET_STACK_SIZE); +diff --git a/FEXCore/Source/Interface/Core/DiskCache.cpp b/FEXCore/Source/Interface/Core/DiskCache.cpp +index 3c78b22da..d903216c1 100644 +--- a/FEXCore/Source/Interface/Core/DiskCache.cpp ++++ b/FEXCore/Source/Interface/Core/DiskCache.cpp +@@ -11,6 +11,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -22,6 +23,23 @@ + #include + #include + ++namespace { ++template ++bool HashGuestMemory(UpdateFn&& Update, uint64_t Address, uint64_t Size) { ++ uint8_t Buffer[256]; ++ while (Size) { ++ const uint64_t Chunk = std::min(Size, sizeof(Buffer)); ++ if (!FEXCore::Utils::FaultSafeRead::Copy(Buffer, reinterpret_cast(Address), Chunk)) { ++ return false; ++ } ++ Update(Buffer, Chunk); ++ Address += Chunk; ++ Size -= Chunk; ++ } ++ return true; ++} ++} ++ + namespace FEXCore { + + namespace DiskCache { +@@ -576,12 +594,18 @@ namespace DiskCache { + } + uint64_t HashStart = SubBlock.Entry; + // skip over masked in-block data and data/etc gaps between blocks ++ auto Update = [&](const uint8_t* Bytes, uint64_t Size) { ++ XXH3_64bits_update(&HashState, Bytes, Size); ++ }; + for (auto& DataMask : SubBlock.DataMasks) { +- XXH3_64bits_update(&HashState, reinterpret_cast(HashStart), DataMask.FieldAddress - HashStart); ++ if (!HashGuestMemory(Update, HashStart, DataMask.FieldAddress - HashStart)) { ++ return std::nullopt; ++ } + HashStart = DataMask.FieldAddress + DataMask.ValueSize; + } +- if (HashStart != SubBlock.Entry + SubBlock.Size) { +- XXH3_64bits_update(&HashState, reinterpret_cast(HashStart), SubBlock.Size - (HashStart - SubBlock.Entry)); ++ if (HashStart != SubBlock.Entry + SubBlock.Size && ++ !HashGuestMemory(Update, HashStart, SubBlock.Size - (HashStart - SubBlock.Entry))) { ++ return std::nullopt; + } + } + GuestCodeKey = XXH3_64bits_digest(&HashState); +@@ -704,8 +728,13 @@ namespace DiskCache { + if (FirstHash || LastFootprintHashed != CurrentFootprint) { + XXH3_state_t HashState; + XXH3_128bits_reset(&HashState); ++ auto Update = [&](const uint8_t* Bytes, uint64_t Size) { ++ XXH3_128bits_update(&HashState, Bytes, Size); ++ }; + for (uint32_t i = 0; i < Entry.GuestExtents.size(); i += 2) { +- XXH3_128bits_update(&HashState, reinterpret_cast(GuestRIP) + Entry.GuestExtents[i], Entry.GuestExtents[i + 1]); ++ if (!HashGuestMemory(Update, GuestRIP + Entry.GuestExtents[i], Entry.GuestExtents[i + 1])) { ++ return std::nullopt; ++ } + } + LiveGuestHash = XXH3_128bits_digest(&HashState); + LastFootprintHashed = CurrentFootprint; +diff --git a/FEXCore/Source/Interface/Core/DiskCache.h b/FEXCore/Source/Interface/Core/DiskCache.h +index 0bd3c21e4..0f1490cba 100644 +--- a/FEXCore/Source/Interface/Core/DiskCache.h ++++ b/FEXCore/Source/Interface/Core/DiskCache.h +@@ -249,7 +249,7 @@ namespace DiskCache { + // The current version of the diskcache. + // This must be changed any time codegen changes occur! + // Be aware of the impact of changing this frequently! +- static constexpr uint16_t FormatVersion = 52; ++ static constexpr uint16_t FormatVersion = 0x8000 | (1 << 8) | 52; + + static constexpr uint32_t LOOKUP_KEY_MAX_BUCKET_DEPTH = 500; + +diff --git a/FEXCore/Source/Interface/Core/Frontend.cpp b/FEXCore/Source/Interface/Core/Frontend.cpp +index 94e4ac522..18cda8889 100644 +--- a/FEXCore/Source/Interface/Core/Frontend.cpp ++++ b/FEXCore/Source/Interface/Core/Frontend.cpp +@@ -19,6 +19,7 @@ $end_info$ + #include + #include + #include ++#include + #include + #include + #include +@@ -108,6 +109,11 @@ int32_t Decoder::CheckRangeExecutable(uint64_t Address, uint64_t Size) { + } + } + ++ if (const auto Epoch = CTX->ExecutableRangeEpoch.load(std::memory_order_acquire); Epoch != ExecutableRangeEpochSeen) { ++ ExecutableRangeEpochSeen = Epoch; ++ ResetExecutableRangeCache(); ++ } ++ + uint64_t RemainingSize = Size; + while (Address < ExecutableRangeBase || Address + RemainingSize > ExecutableRangeEnd) { + auto RangeInfo = CTX->SyscallHandler->QueryGuestExecutableRange(Thread, Address); +@@ -132,8 +138,13 @@ int32_t Decoder::CheckRangeExecutable(uint64_t Address, uint64_t Size) { + } + + uint8_t Decoder::ReadByte() { ++ if (InstructionSize >= MAX_INST_SIZE) { ++ HitInstructionLengthLimit = true; ++ return 0; ++ } ++ + std::optional Byte = PeekByte(0); +- if (!Byte || InstructionSize == MAX_INST_SIZE) { ++ if (!Byte) { + HitNonExecutableRange = true; + // Pretend we read 0, the main decode loop will see HitNonExecutableRange and rollback the instruction. + return 0; +@@ -146,8 +157,10 @@ uint8_t Decoder::ReadByte() { + + std::optional Decoder::PeekByte(uint8_t Offset) { + uint64_t ByteAddress = reinterpret_cast(InstStream.InstStream + InstructionSize + Offset); +- if (CheckRangeExecutable(ByteAddress, 1) == 1) { +- return InstStream.AdjustedInstStream[InstructionSize + Offset]; ++ uint8_t Byte; ++ if (CheckRangeExecutable(ByteAddress, 1) == 1 && ++ FEXCore::Utils::FaultSafeRead::Copy(&Byte, &InstStream.AdjustedInstStream[InstructionSize + Offset], 1)) { ++ return Byte; + } else { + return std::nullopt; + } +@@ -160,13 +173,24 @@ std::pair Decoder::ReadData(uint8_t Size) { + uint64_t Address = reinterpret_cast(InstStream.InstStream + InstructionSize); + LastFieldReadOffset = (uint8_t)InstructionSize; + LastFieldReadSize = Size; +- auto ReadableSize = CheckRangeExecutable(Address, Size); +- if (ReadableSize == Size) { +- std::memcpy(&Res, &InstStream.AdjustedInstStream[InstructionSize], Size); +- } else { +- HitNonExecutableRange = true; +- // See PeekByte, this specific case may cause some executable memory to read as 0 but it doesn't matter as the entire instruction will be rolled back anyway. ++ int32_t ReadableSize {}; ++ if (InstructionSize + Size > MAX_INST_SIZE) [[unlikely]] { ++ const int32_t FetchableSize = InstructionSize < MAX_INST_SIZE ? MAX_INST_SIZE - InstructionSize : 0; ++ ReadableSize = FetchableSize ? CheckRangeExecutable(Address, FetchableSize) : 0; ++ if (ReadableSize != FetchableSize) { ++ HitNonExecutableRange = true; ++ } ++ HitInstructionLengthLimit = true; + Res = 0; ++ } else { ++ ReadableSize = CheckRangeExecutable(Address, Size); ++ if (ReadableSize == Size && !FEXCore::Utils::FaultSafeRead::Copy(&Res, &InstStream.AdjustedInstStream[InstructionSize], Size)) { ++ ReadableSize = 0; ++ } ++ if (ReadableSize != Size) { ++ HitNonExecutableRange = true; ++ Res = 0; ++ } + } + + // Skip the number of decoded bytes regardless to get instruction size. +@@ -881,7 +905,7 @@ Decoder::DecodedBlockStatus Decoder::DecodeInstructionImpl(uint64_t PC) { + + for (;;) { + if (InstructionSize >= MAX_INST_SIZE) { +- return DecodedBlockStatus::INVALID_INST; ++ return DecodedBlockStatus::TOO_LONG_INST; + } + uint8_t Op = ReadByte(); + switch (Op) { +@@ -1108,11 +1132,12 @@ void Decoder::DecodeREXIfValid(int8_t ExpectedOffset) { + Decoder::DecodedBlockStatus Decoder::DecodeInstruction(uint64_t PC) { + // Will be set if DecodeInstructionImpl tries to read non-executable memory + HitNonExecutableRange = false; ++ HitInstructionLengthLimit = false; + HitBadRelocation = false; + HitBreakpoint = ~0U; + auto ErrorDuringDecoding = DecodeInstructionImpl(PC); + +- if (ErrorDuringDecoding != DecodedBlockStatus::SUCCESS || HitNonExecutableRange || HitBadRelocation) [[unlikely]] { ++ if (ErrorDuringDecoding != DecodedBlockStatus::SUCCESS || HitNonExecutableRange || HitInstructionLengthLimit || HitBadRelocation) [[unlikely]] { + // Put an invalid instruction in the stream so the core can raise SIGILL if hit + // Error while decoding instruction. We don't know the table or instruction size + DecodeInst->TableInfo = nullptr; +@@ -1134,6 +1159,10 @@ Decoder::DecodedBlockStatus Decoder::DecodeInstruction(uint64_t PC) { + return DecodedBlockStatus::BAD_RELOCATION; + } + ++ if (HitInstructionLengthLimit) { ++ return DecodedBlockStatus::TOO_LONG_INST; ++ } ++ + return ErrorDuringDecoding; + } else if (!DecodeInst->TableInfo || (DecodeInst->TableInfo->Type == TYPE_INST && !DecodeInst->TableInfo->OpcodeDispatcher.OpDispatch)) { + // If there wasn't an error during decoding but we have no dispatcher for the instruction then claim invalid instruction. +@@ -1693,6 +1722,7 @@ void Decoder::DecodeLoop(const uint8_t* _InstStream, uint64_t GuestSizePause) { + BlockIt->BlockStatus == DecodedBlockStatus::BREAKPOINT_3 ? "Breakpoint" : + BlockIt->BlockStatus == DecodedBlockStatus::INVALID_INST ? "Invalid" : + BlockIt->BlockStatus == DecodedBlockStatus::NOEXEC_INST ? "NoExec" : ++ BlockIt->BlockStatus == DecodedBlockStatus::TOO_LONG_INST ? "TooLong" : + BlockIt->BlockStatus == DecodedBlockStatus::BAD_RELOCATION ? "BadRelocation" : + BlockIt->BlockStatus == DecodedBlockStatus::UNIMPLEMENTED_INST ? "Unimplemented" : + "PartialDecode", +diff --git a/FEXCore/Source/Interface/Core/Frontend.h b/FEXCore/Source/Interface/Core/Frontend.h +index ade14bc44..6d279b22c 100644 +--- a/FEXCore/Source/Interface/Core/Frontend.h ++++ b/FEXCore/Source/Interface/Core/Frontend.h +@@ -28,6 +28,7 @@ public: + INVALID_INST, + NOEXEC_INST, + PARTIAL_DECODE_INST, ++ TOO_LONG_INST, + BAD_RELOCATION, + UNIMPLEMENTED_INST, + BREAKPOINT_0, +@@ -93,6 +94,8 @@ public: + ExecutableRangeBase = ExecutableRangeEnd = 0; + } + ++ uint64_t ExecutableRangeEpochSeen {}; ++ + private: + // To pass any information from instruction prefixes + // down into the actual instruction handling machinery. +@@ -159,6 +162,7 @@ private: + uint64_t ExecutableRangeEnd {}; + bool ExecutableRangeWritable {}; + bool HitNonExecutableRange {}; ++ bool HitInstructionLengthLimit {}; + bool HitBadRelocation {}; + uint32_t HitBreakpoint {~0U}; + +diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +index c5e656d2c..7b9c15b61 100644 +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -195,6 +195,21 @@ DEF_OP(ExitFunction) { + ARMEmitter::ForwardLabel SkipFullLookup; + auto RipReg = GetReg(Op->NewRIP); + ++ if (Op->Hint == IR::BranchHint::CheckTF || CompilingWithTF) { ++ ARMEmitter::ForwardLabel TFUnset; ++ ldrb(TMP1, STATE_PTR(CpuStateFrame, State.flags[X86State::RFLAG_TF_RAW_LOC])); ++ (void)cbz(ARMEmitter::Size::i32Bit, TMP1, &TFUnset); ++ if (Op->Hint == IR::BranchHint::Return) { ++ add(ARMEmitter::Size::i64Bit, REG_CALLRET_SP, REG_CALLRET_SP, 0x10); ++ } else if (Op->Hint == IR::BranchHint::Call) { ++ stp(ARMEmitter::XReg::zr, ARMEmitter::XReg::zr, REG_CALLRET_SP, -0x10); ++ } ++ str(RipReg.X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip)); ++ ldr(TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.DispatcherLoopTop)); ++ br(TMP2); ++ (void)Bind(&TFUnset); ++ } ++ + if (Op->Hint == IR::BranchHint::Return) { + // First try to pop from the call-ret stack, otherwise follow the normal path (but ending in a ret) + ldp(TMP1, TMP2, REG_CALLRET_SP, 0x10); +diff --git a/FEXCore/Source/Interface/Core/JIT/JIT.cpp b/FEXCore/Source/Interface/Core/JIT/JIT.cpp +index fa9c8c880..777b4b51d 100644 +--- a/FEXCore/Source/Interface/Core/JIT/JIT.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/JIT.cpp +@@ -862,6 +862,7 @@ CPUBackend::CompiledCode Arm64JITCore::EmitJITCode(uint64_t Entry, uint64_t Size + this->DebugData = DebugData; + this->IR = IR; + RequiresFarARM64Jumps = false; ++ CompilingWithTF = CheckTF; + SSANodeMultiplier = 24; + + // Prepare restart via long jump in case branch encoding fails. +diff --git a/FEXCore/Source/Interface/Core/JIT/JITClass.h b/FEXCore/Source/Interface/Core/JIT/JITClass.h +index 55286855f..684ac9d9d 100644 +--- a/FEXCore/Source/Interface/Core/JIT/JITClass.h ++++ b/FEXCore/Source/Interface/Core/JIT/JITClass.h +@@ -86,6 +86,7 @@ private: + // In the rare case when those assumptions are broken, FEX needs to safely restart the JIT. + RestartOptions RestartControl {}; + bool RequiresFarARM64Jumps {}; ++ bool CompilingWithTF {}; + // Default to 6 instructions per SSA node. + uint32_t SSANodeMultiplier {24}; + +diff --git a/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp b/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp +index d15ef9aee..bc1fb9c19 100644 +--- a/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp +@@ -86,6 +86,34 @@ DEF_OP(Break) { + br(TMP1); + } + ++DEF_OP(BreakErrorCode) { ++ auto Op = IROp->C(); ++ ++ uxth(ARMEmitter::Size::i64Bit, TMP2, GetReg(Op->ErrorCode)); ++ ResetStack(); ++ ++ Core::CpuStateFrame::SynchronousFaultDataStruct State = { ++ .FaultToTopAndGeneratedException = 1, ++ .Signal = Op->Reason.Signal, ++ .TrapNo = Op->Reason.TrapNumber, ++ .si_code = Op->Reason.si_code, ++ .err_code = 0, ++ .FaultAddress = 0, ++ }; ++ static_assert(offsetof(Core::CpuStateFrame::SynchronousFaultDataStruct, err_code) == 4, "err_code is bits 32-47"); ++ ++ uint64_t Constant {}; ++ memcpy(&Constant, &State, sizeof(uint64_t)); ++ ++ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, static_cast(Constant)); ++ bfi(ARMEmitter::Size::i64Bit, TMP1, TMP2, 32, 16); ++ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, SynchronousFaultData)); ++ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, SynchronousFaultData) + 8); ++ ++ ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.GuestSignal_SynchronousFault)); ++ br(TMP1); ++} ++ + DEF_OP(GetRoundingMode) { + auto Dst = GetReg(Node); + mrs(Dst, ARMEmitter::SystemRegister::FPCR); +diff --git a/FEXCore/Source/Interface/Core/LookupCache.h b/FEXCore/Source/Interface/Core/LookupCache.h +index 391d48560..228d03969 100644 +--- a/FEXCore/Source/Interface/Core/LookupCache.h ++++ b/FEXCore/Source/Interface/Core/LookupCache.h +@@ -125,7 +125,7 @@ struct GuestToHostMap { + return BlockList.erase(Address) != 0; + } + +- void InvalidateRange(uint64_t Start, uint64_t Length) { ++ bool InvalidateRange(uint64_t Start, uint64_t Length) { + auto lk = AcquireWriteLock(); + + auto lower = CodePages.lower_bound(Start >> 12); +@@ -136,7 +136,9 @@ struct GuestToHostMap { + Erase(Entry, lk); + } + } ++ const bool Found = lower != upper; + CodePages.erase(lower, upper); ++ return Found; + } + + void AddBlockLink(uint64_t GuestDestination, FEXCore::Context::ExitFunctionLinkData* HostLink, +@@ -144,6 +146,11 @@ struct GuestToHostMap { + BlockLinks->insert({{GuestDestination, HostLink}, delinker}); + } + ++ bool HasBlockExecutableRange(uint64_t Page, const LookupCacheReadLockToken&) const { ++ auto it = CodePages.find(Page >> 12); ++ return it != CodePages.end() && !it->second.empty(); ++ } ++ + bool AddBlockExecutableRange(const std::ranges::input_range auto& Addresses, uint64_t Start, uint64_t Length, const LookupCacheWriteLockToken&) { + bool rv = false; + +@@ -282,6 +289,11 @@ public: + + GuestToHostMap* Shared = nullptr; + ++ bool HasBlockExecutableRange(uint64_t Page) { ++ auto lk = Shared->AcquireReadLock(); ++ return Shared->HasBlockExecutableRange(Page, lk); ++ } ++ + // Appends a list of Block {Address} to CodePages [Start, Start + Length) + // Returns true if new pages are marked as containing code + bool AddBlockExecutableRange(FEXCore::Core::InternalThreadState* Thread, auto& Addresses, uint64_t Start, uint64_t Length) { +diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp b/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp +index 356fc3bb1..27491cea4 100644 +--- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp ++++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp +@@ -138,6 +138,31 @@ void OpDispatchBuilder::IRETOp(OpcodeArgs) { + + const auto GPRSize = GetGPROpSize(); + ++ { ++ auto FaultBlock = CreateNewCodeBlockAfter(GetCurrentBlock()); ++ auto ContinueBlock = CreateNewCodeBlockAfter(FaultBlock); ++ ++ auto CondJump_ = CondJump(GetRFLAG(FEXCore::X86State::RFLAG_NT_LOC), CondClass::EQ); ++ SetTrueJumpTarget(CondJump_, ContinueBlock); ++ SetFalseJumpTarget(CondJump_, FaultBlock); ++ ++ SetCurrentCodeBlock(FaultBlock); ++ StartNewBlock(); ++ ++ _StoreContextGPR(GPRSize, GetRelocatedPC(Op, -Op->InstSize), offsetof(FEXCore::Core::CPUState, rip)); ++ ++ IR::BreakDefinition Reason {}; ++ Reason.ErrorRegister = 0; ++ Reason.Signal = Core::FAULT_SIGSEGV; ++ Reason.TrapNumber = X86State::X86_TRAPNO_GP; ++ Reason.si_code = 0x80; ++ BlockSetRIP = true; ++ Break(Reason); ++ ++ SetCurrentCodeBlock(ContinueBlock); ++ StartNewBlock(); ++ } ++ + Ref SP = _RMWHandle(LoadGPRRegister(X86State::REG_RSP)); + + // RIP (64/32/16 bits) +@@ -164,7 +189,7 @@ void OpDispatchBuilder::IRETOp(OpcodeArgs) { + StoreGPRRegister(X86State::REG_RSP, SP); + } + +- ExitFunction(NewRIP); ++ ExitFunction(NewRIP, BranchHint::CheckTF); + BlockSetRIP = true; + } + +@@ -1230,6 +1255,36 @@ void OpDispatchBuilder::FLAGControlOp(OpcodeArgs) { + } + + ++void OpDispatchBuilder::MOVSegFSGS64(OpcodeArgs, Ref Selector, uint32_t IndexOffset, uint32_t BaseOffset) { ++ Ref Index = _Bfe(OpSize::i32Bit, 13, 3, Selector); ++ Ref TI = _Bfe(OpSize::i32Bit, 1, 2, Selector); ++ Ref Allowed = _And(OpSize::i32Bit, _Lshr(OpSize::i32Bit, Constant(0x8071), Index), Constant(1)); ++ Allowed = _Select(OpSize::i32Bit, OpSize::i32Bit, CondClass::ULT, Index, Constant(16), Allowed, Constant(0)); ++ Allowed = _Select(OpSize::i32Bit, OpSize::i32Bit, CondClass::EQ, TI, Constant(0), Allowed, Constant(0)); ++ ++ auto FaultBlock = CreateNewCodeBlockAfter(GetCurrentBlock()); ++ auto ContinueBlock = CreateNewCodeBlockAfter(FaultBlock); ++ auto CondJump_ = CondJump(Allowed, CondClass::NEQ); ++ SetTrueJumpTarget(CondJump_, ContinueBlock); ++ SetFalseJumpTarget(CondJump_, FaultBlock); ++ ++ SetCurrentCodeBlock(FaultBlock); ++ StartNewBlock(); ++ Ref FaultSelector = LoadSourceGPR_WithOpSize(Op, Op->Src[0], OpSize::i16Bit, Op->Flags); ++ _StoreContextGPR(GetGPROpSize(), GetRelocatedPC(Op, -Op->InstSize), offsetof(FEXCore::Core::CPUState, rip)); ++ IR::BreakDefinition Reason {}; ++ Reason.Signal = Core::FAULT_SIGSEGV; ++ Reason.TrapNumber = X86State::X86_TRAPNO_GP; ++ Reason.si_code = 0x80; ++ BlockSetRIP = true; ++ BreakErrorCode(_And(OpSize::i32Bit, FaultSelector, Constant(0xfffc)), Reason); ++ ++ SetCurrentCodeBlock(ContinueBlock); ++ StartNewBlock(); ++ _StoreContextGPR(OpSize::i16Bit, LoadSourceGPR_WithOpSize(Op, Op->Src[0], OpSize::i16Bit, Op->Flags), IndexOffset); ++ _StoreContextGPR(OpSize::i64Bit, Constant(0), BaseOffset); ++} ++ + void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + // In x86-64 mode the accesses to the segment registers end up being constant zero moves + // Aside from FS/GS +@@ -1243,7 +1298,6 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + // selected for the registers + // This statement is actually untrue, the instructions will /actually/ load 16bits in to the selector portion of the register! + // Tested on a Zen+ CPU, the selector is the portion that is modified! +- // We don't currently support FS/GS selector modifying, so this needs to be asserted out + // The loads here also load the selector, NOT the base + + if (ToSeg) { +@@ -1283,8 +1337,7 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + _StoreContextGPR(OpSize::i16Bit, Src, offsetof(FEXCore::Core::CPUState, gs_idx)); + UpdatePrefixFromSegment(Src, FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX); + } else { +- LogMan::Msg::EFmt("We don't support modifying GS selector in 64bit mode!"); +- DecodeFailure = true; ++ MOVSegFSGS64(Op, Src, offsetof(FEXCore::Core::CPUState, gs_idx), offsetof(FEXCore::Core::CPUState, gs_cached)); + } + break; + case FEXCore::X86State::REG_RSP: // FS +@@ -1293,8 +1346,7 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + _StoreContextGPR(OpSize::i16Bit, Src, offsetof(FEXCore::Core::CPUState, fs_idx)); + UpdatePrefixFromSegment(Src, FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX); + } else { +- LogMan::Msg::EFmt("We don't support modifying FS selector in 64bit mode!"); +- DecodeFailure = true; ++ MOVSegFSGS64(Op, Src, offsetof(FEXCore::Core::CPUState, fs_idx), offsetof(FEXCore::Core::CPUState, fs_cached)); + } + break; + default: UnimplementedOp(Op); return; +@@ -1321,19 +1373,11 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + break; + case FEXCore::X86State::REG_RBP: // GS + case FEXCore::X86State::REG_R13: // GS +- if (Is64BitMode) { +- Segment = Constant(0); +- } else { +- Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, gs_idx)); +- } ++ Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, gs_idx)); + break; + case FEXCore::X86State::REG_RSP: // FS + case FEXCore::X86State::REG_R12: // FS +- if (Is64BitMode) { +- Segment = Constant(0); +- } else { +- Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, fs_idx)); +- } ++ Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, fs_idx)); + break; + default: UnimplementedOp(Op); return; + } +diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h +index d3e523d9b..601db6009 100644 +--- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h ++++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h +@@ -216,6 +216,10 @@ public: + } + return _Break(Reason, RelocatedPC); + } ++ IRPair BreakErrorCode(Ref ErrorCode, BreakDefinition Reason) { ++ FlushRegisterCache(); ++ return _BreakErrorCode(ErrorCode, Reason); ++ } + IRPair Thunk(Ref ArgPtr, SHA256Sum ThunkNameHash) { + FlushRegisterCache(); + return _Thunk(ArgPtr, ThunkNameHash); +@@ -417,6 +421,7 @@ public: + void XCHGRAXOp(OpcodeArgs); + void SAHFOp(OpcodeArgs); + void LAHFOp(OpcodeArgs); ++ void MOVSegFSGS64(OpcodeArgs, Ref Selector, uint32_t IndexOffset, uint32_t BaseOffset); + void MOVSegOp(OpcodeArgs, bool ToSeg); + void FLAGControlOp(OpcodeArgs); + void MOVOffsetOp(OpcodeArgs); +@@ -1974,8 +1979,8 @@ private: + // An exception should still be raised after an instruction that unsets TF, leave the unblocked bit set but unset + // the TF bit to cause such behaviour. The handling code at the start of the next block will then unset the + // unblocked bit before raising the exception. +- auto NewPackedTF = +- _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, Value, Constant(0), _And(OpSize::i32Bit, PackedTF, Constant(~1)), Constant(1)); ++ auto NewPackedTF = _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, Value, Constant(0), _And(OpSize::i32Bit, PackedTF, Constant(~1)), ++ _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, PackedTF, Constant(3), Constant(3), Constant(1))); + _StoreContextGPR(OpSize::i8Bit, NewPackedTF, ARRAY_OFFSETOF(FEXCore::Core::CPUState, flags, BitOffset)); + } else { + _StoreContextGPR(OpSize::i8Bit, Value, ARRAY_OFFSETOF(FEXCore::Core::CPUState, flags, BitOffset)); +diff --git a/FEXCore/Source/Interface/IR/IR.json b/FEXCore/Source/Interface/IR/IR.json +index 4b79cf35c..0c01f580d 100644 +--- a/FEXCore/Source/Interface/IR/IR.json ++++ b/FEXCore/Source/Interface/IR/IR.json +@@ -324,6 +324,12 @@ + "Break BreakDefinition:$Reason, GPR:$FaultAddress": { + "HasSideEffects": true + }, ++ "BreakErrorCode GPR:$ErrorCode, BreakDefinition:$Reason": { ++ "HasSideEffects": true, ++ "Desc": ["Break whose fault error code is the low 16 bits of $ErrorCode, known only at run time", ++ "(a #GP with a selector as its error code); Reason.ErrorRegister is not used" ++ ] ++ }, + "CallbackReturn": { + "HasSideEffects": true + }, +diff --git a/FEXCore/Source/Interface/IR/IREmitter.cpp b/FEXCore/Source/Interface/IR/IREmitter.cpp +index 6c8ed5d11..d8fd1431e 100644 +--- a/FEXCore/Source/Interface/IR/IREmitter.cpp ++++ b/FEXCore/Source/Interface/IR/IREmitter.cpp +@@ -23,7 +23,8 @@ static bool IsFragmentExit(FEXCore::IR::IROps Op) { + case OP_SYSCALL: + case OP_CPUID: + case OP_EXITFUNCTION: +- case OP_BREAK: return true; ++ case OP_BREAK: ++ case OP_BREAKERRORCODE: return true; + default: return false; + } + } +diff --git a/FEXCore/Source/Utils/FaultSafeRead.cpp b/FEXCore/Source/Utils/FaultSafeRead.cpp +new file mode 100644 +index 000000000..aaa7a80cf +--- /dev/null ++++ b/FEXCore/Source/Utils/FaultSafeRead.cpp +@@ -0,0 +1,46 @@ ++// SPDX-License-Identifier: MIT ++#include ++ ++#include ++ ++namespace FEXCore::Utils::FaultSafeRead { ++#if defined(ARCHITECTURE_arm64) && !defined(_WIN32) ++__attribute__((naked)) static size_t CopyImpl(void* Dest, const void* Src, size_t Size) { ++ __asm volatile(R"( ++ // Early exit if a copy of size zero. ++ cbz x2, 2f; ++ ++ 1: ++ .globl FEXCore_FaultSafeRead_FaultInst ++ FEXCore_FaultSafeRead_FaultInst: ++ ldrb w3, [x1], 1; // <- This line can fault. ++ strb w3, [x0], 1; ++ sub x2, x2, 1; ++ cbnz x2, 1b; ++2: ++ mov x0, 0; ++ ret; ++ )" :: ++ : "memory"); ++} ++ ++extern "C" uint64_t FEXCore_FaultSafeRead_FaultInst; ++ ++bool Copy(void* Dest, const void* Src, size_t Size) { ++ return CopyImpl(Dest, Src, Size) == 0; ++} ++ ++bool IsFaultLocation(uint64_t PC) { ++ return reinterpret_cast(PC) == &FEXCore_FaultSafeRead_FaultInst; ++} ++#else ++bool Copy(void* Dest, const void* Src, size_t Size) { ++ memcpy(Dest, Src, Size); ++ return true; ++} ++ ++bool IsFaultLocation(uint64_t PC) { ++ return false; ++} ++#endif ++} +diff --git a/FEXCore/include/FEXCore/Core/Context.h b/FEXCore/include/FEXCore/Core/Context.h +index 7e1d30770..854c5ce1c 100644 +--- a/FEXCore/include/FEXCore/Core/Context.h ++++ b/FEXCore/include/FEXCore/Core/Context.h +@@ -141,9 +141,11 @@ public: + virtual void FlushAndCloseCodeMap() = 0; + + FEX_DEFAULT_VISIBILITY virtual void ClearCodeCache(FEXCore::Core::InternalThreadState* Thread, bool NewCodeBuffer = true) = 0; +- FEX_DEFAULT_VISIBILITY virtual void InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) = 0; ++ FEX_DEFAULT_VISIBILITY virtual void InvalidateExecutableRangeCaches() = 0; ++ ++ FEX_DEFAULT_VISIBILITY virtual bool InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) = 0; + FEX_DEFAULT_VISIBILITY virtual void +- InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) = 0; ++ InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached = true) = 0; + FEX_DEFAULT_VISIBILITY virtual FEXCore::Utils::WritePriorityMutex::Mutex& GetCodeInvalidationMutex() = 0; + + FEX_DEFAULT_VISIBILITY virtual void +diff --git a/FEXCore/include/FEXCore/Core/CoreState.h b/FEXCore/include/FEXCore/Core/CoreState.h +index 7c02605f5..98ba8e150 100644 +--- a/FEXCore/include/FEXCore/Core/CoreState.h ++++ b/FEXCore/include/FEXCore/Core/CoreState.h +@@ -282,6 +282,11 @@ struct alignas(64) CPUState { + + // TODO: This should be moved to the frontend. + constexpr static uint32_t DEFAULT_USER_CS = 6; ++ constexpr static uint32_t DEFAULT_USER_DS = 5; ++ ++ constexpr static uint32_t DEFAULT_USER_CS_SEL = (DEFAULT_USER_CS << 3) | 3; ++ constexpr static uint32_t DEFAULT_USER_DS_SEL = (DEFAULT_USER_DS << 3) | 3; ++ constexpr static uint32_t DEFAULT_USER32_CS_SEL = 0x23; + + // Follows encoding of the TI bit in segment selector encoding. + constexpr static uint32_t SEGMENT_ARRAY_INDEX_GDT = 0; +diff --git a/FEXCore/include/FEXCore/HLE/SyscallHandler.h b/FEXCore/include/FEXCore/HLE/SyscallHandler.h +index 0ba0218e3..89e36d52e 100644 +--- a/FEXCore/include/FEXCore/HLE/SyscallHandler.h ++++ b/FEXCore/include/FEXCore/HLE/SyscallHandler.h +@@ -33,6 +33,10 @@ public: + virtual void HandleSyscall(FEXCore::Core::CpuStateFrame* Frame) = 0; + + virtual void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {} ++ ++ virtual bool IsSMCHotPage(uint64_t Address) { ++ return false; ++ } + virtual void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {} + virtual void MarkOvercommitRange(uint64_t Start, uint64_t Length) {} + virtual void UnmarkOvercommitRange(uint64_t Start, uint64_t Length) {} +diff --git a/FEXCore/include/FEXCore/Utils/FaultSafeRead.h b/FEXCore/include/FEXCore/Utils/FaultSafeRead.h +new file mode 100644 +index 000000000..1fc7213b5 +--- /dev/null ++++ b/FEXCore/include/FEXCore/Utils/FaultSafeRead.h +@@ -0,0 +1,12 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++#include ++ ++#include ++#include ++ ++namespace FEXCore::Utils::FaultSafeRead { ++FEX_DEFAULT_VISIBILITY bool Copy(void* Dest, const void* Src, size_t Size); ++ ++FEX_DEFAULT_VISIBILITY bool IsFaultLocation(uint64_t PC); ++} +diff --git a/FEXCore/include/FEXCore/Utils/SHMStats.h b/FEXCore/include/FEXCore/Utils/SHMStats.h +index c5844fe10..d646c6a2f 100644 +--- a/FEXCore/include/FEXCore/Utils/SHMStats.h ++++ b/FEXCore/include/FEXCore/Utils/SHMStats.h +@@ -74,7 +74,10 @@ struct ThreadStats { + uint64_t AccumulatedDiskCacheHitCount; + uint64_t AccumulatedDiskCacheMissCount; + uint64_t AccumulatedDiskCacheLookupTime; +- uint64_t Padding; ++ ++ uint64_t AccumulatedInvalidationCount; ++ uint64_t AccumulatedInvalidationTime; ++ uint64_t AccumulatedCallRetFlushCount; + }; + + // Ensure 16-byte alignment to take advantage of ARM single-copy atomicity. +diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +index e7e88f8f2..26b8186c8 100644 +--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp ++++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +@@ -602,8 +602,7 @@ int main(int argc, char** argv, char** const envp) { + // Create a thread without a RIP or stack pointer setup initially. + auto ParentThread = SyscallHandler->TM.CreateThread(); + SyscallHandler->TM.TrackThread(ParentThread); +- SignalDelegation->RegisterTLSState(ParentThread); +- ThunkHandler->RegisterTLSState(ParentThread); ++ SyscallHandler->RegisterTLSState(ParentThread); + + SyscallHandler->DeserializeSeccompFD(ParentThread, FEXSeccompFD); + +diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +index 2e724929f..62135b824 100644 +--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h ++++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +@@ -20,6 +20,7 @@ namespace FEX::ArchHelpers::Context { + + enum ContextFlags : uint32_t { + CONTEXT_FLAG_INJIT = (1U << 0), ++ CONTEXT_FLAG_SYSCALLINFO_CLEARED = (1U << 1), + }; + + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED +@@ -40,7 +41,11 @@ struct X86ContextBackup { + FEXCore::x86_64::_libc_fpstate FPRState; + uint64_t sa_mask; + uint16_t InSyscallInfo; ++ uint16_t ClearedSyscallInfo; + bool FaultToTopAndGeneratedException; ++ uint64_t GuestSignalMask; ++ uint64_t SeccompTrapRIP; ++ uint64_t SavedJITStackSP; + + // Guest state + int Signal; +@@ -72,7 +77,11 @@ struct ArmContextBackup { + __uint128_t FPRs[32]; + uint64_t sa_mask; + uint16_t InSyscallInfo; ++ uint16_t ClearedSyscallInfo; + bool FaultToTopAndGeneratedException; ++ uint64_t GuestSignalMask; ++ uint64_t SeccompTrapRIP; ++ uint64_t SavedJITStackSP; + + // Guest state + int Signal; +@@ -92,6 +101,11 @@ struct ArmContextBackup { + static constexpr int RedZoneSize = 0; + }; + ++template ++static inline uint16_t SavedSyscallInfo(const Backup* Context) { ++ return (Context->Flags & CONTEXT_FLAG_SYSCALLINFO_CLEARED) ? Context->ClearedSyscallInfo : Context->InSyscallInfo; ++} ++ + static inline ucontext_t* GetUContext(void* ucontext) { + ucontext_t* _context = (ucontext_t*)ucontext; + return _context; +diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt +index 715a8f132..3f02104ea 100644 +--- a/Source/Tools/LinuxEmulation/CMakeLists.txt ++++ b/Source/Tools/LinuxEmulation/CMakeLists.txt +@@ -10,6 +10,9 @@ add_library(LinuxEmulation STATIC + LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp + LinuxSyscalls/FaultSafeUserMemAccess.cpp + LinuxSyscalls/FileManagement.cpp ++ LinuxSyscalls/PtraceEmu.cpp ++ LinuxSyscalls/SamplingProfiler.cpp ++ LinuxSyscalls/SignalTrace.cpp + LinuxSyscalls/LinuxAllocator.cpp + LinuxSyscalls/Seccomp/SeccompEmulator.cpp + LinuxSyscalls/Seccomp/BPFEmitter.cpp +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index 2095d4dc5..eb12945e4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -10,6 +10,7 @@ $end_info$ + + #include "Common/CPUInfo.h" + #include "Common/FDUtils.h" ++#include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h" + +@@ -24,6 +25,8 @@ $end_info$ + + #include + ++#include ++#include + #include + #include + #include +@@ -593,6 +596,10 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx) + FDReadCreators[procAuxv] = &EmulatedFDManager::ProcAuxv; + FDReadCreators["/proc/self/auxv"] = &EmulatedFDManager::ProcAuxv; + ++ fextl::string procStatus = fextl::fmt::format("/proc/{}/status", getpid()); ++ FDReadCreators[procStatus] = &EmulatedFDManager::ProcStatus; ++ FDReadCreators["/proc/self/status"] = &EmulatedFDManager::ProcStatus; ++ + if (ThreadsConfig > 1) { + cpus_online = fextl::fmt::format("0-{}", ThreadsConfig - 1); + } else { +@@ -602,6 +609,20 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx) + + EmulatedFDManager::~EmulatedFDManager() {} + ++static bool IsProcMapsPath(const char* Path) { ++ if (strncmp(Path, "/proc/", 6) != 0) { ++ return false; ++ } ++ const char* P = Path + 6; ++ if (!isdigit(*P)) { ++ return strcmp(P, "self/maps") == 0; ++ } ++ while (isdigit(*P)) { ++ ++P; ++ } ++ return strcmp(P, "/maps") == 0; ++} ++ + int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) { + auto Creator = FDReadCreators.end(); + if (pathname) { +@@ -609,12 +630,148 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) + } + + if (Creator == FDReadCreators.end()) { ++ if (pathname && IsProcMapsPath(pathname)) { ++ return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode); ++ } + return -1; + } + + return Creator->second(CTX, AT_FDCWD, pathname, flags, mode); + } + ++int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { ++ int HostFD = ::open(pathname, O_RDONLY | O_CLOEXEC); ++ if (HostFD < 0) { ++ return -1; ++ } ++ fextl::string In; ++ char Buf[65536]; ++ for (;;) { ++ const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf)); ++ if (Len > 0) { ++ In.append(Buf, Len); ++ } else if (Len == 0) { ++ break; ++ } else if (errno != EINTR) { ++ LogMan::Msg::EFmt("ProcMaps: reading {} failed: {}", pathname, errno); ++ ::close(HostFD); ++ return -1; ++ } ++ } ++ ::close(HostFD); ++ ++ constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096; ++ fextl::string Out; ++ Out.reserve(In.size()); ++ size_t Pos = 0; ++ while (Pos < In.size()) { ++ size_t Eol = In.find('\n', Pos); ++ const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1; ++ const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16); ++ if (Start < X86_64TaskSizeMax) { ++ Out.append(In, Pos, End - Pos); ++ } ++ Pos = End; ++ } ++ ++ int NewFD = GenTmpFD(pathname, flags); ++ if (NewFD < 0) { ++ LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); ++ return -1; ++ } ++ for (size_t Done = 0; Done < Out.size();) { ++ const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done); ++ if (Wrote > 0) { ++ Done += Wrote; ++ } else if (Wrote < 0 && errno == EINTR) { ++ continue; ++ } else { ++ LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ } ++ if (::lseek(NewFD, 0, SEEK_SET) != 0) { ++ LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ SealTmpFD(NewFD); ++ return NewFD; ++} ++ ++int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { ++ char Buf[8192]; ++ ssize_t Len = 0; ++ { ++ int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ if (HostFD >= 0) { ++ Len = ::read(HostFD, Buf, sizeof(Buf) - 1); ++ ::close(HostFD); ++ } ++ } ++ if (Len < 0) { ++ Len = 0; ++ } ++ Buf[Len] = '\0'; ++ ++ uint32_t SeccompMode = SECCOMP_MODE_DISABLED; ++ if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) { ++ SeccompMode = Thread->SeccompMode; ++ } ++ ++ fextl::string Out; ++ Out.reserve(Len + 64); ++ const char* Cursor = Buf; ++ while (*Cursor) { ++ const char* Eol = strchr(Cursor, '\n'); ++ const size_t LineLen = Eol ? static_cast(Eol - Cursor) + 1 : strlen(Cursor); ++ if (strncmp(Cursor, "Seccomp:", 8) == 0) { ++ Out += fextl::fmt::format("Seccomp:\t{}\n", SeccompMode); ++ } else if (strncmp(Cursor, "TracerPid:", 10) == 0) { ++ if (FEX::HLE::PtraceEmu::IsAttached()) { ++ Out.append(Cursor, LineLen); ++ } else { ++ Out += "TracerPid:\t0\n"; ++ } ++ } else { ++ Out.append(Cursor, LineLen); ++ if (!Eol) { ++ break; ++ } ++ } ++ if (!Eol) { ++ break; ++ } ++ Cursor = Eol + 1; ++ } ++ ++ int NewFD = GenTmpFD(pathname, flags); ++ if (NewFD < 0) { ++ LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); ++ return -1; ++ } ++ for (size_t Done = 0; Done < Out.size();) { ++ const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done); ++ if (Wrote > 0) { ++ Done += Wrote; ++ } else if (Wrote < 0 && errno == EINTR) { ++ continue; ++ } else { ++ LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ } ++ if (::lseek(NewFD, 0, SEEK_SET) != 0) { ++ LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ SealTmpFD(NewFD); ++ return NewFD; ++} ++ + int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { + const auto [auxvBase, auxvSize] = FEX::HLE::_SyscallHandler->GetCodeLoader()->GetAuxv(); + if (auxvBase == 0) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +index 854232341..b98ef4bda 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +@@ -34,6 +34,8 @@ private: + fextl::unordered_map FDReadCreators; + + static int32_t ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); ++ static int32_t ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); ++ static int32_t ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); + const uint32_t ThreadsConfig; + }; + } // namespace FEX::EmulatedFile +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp +index 6471e6483..7a7e068e2 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp +@@ -1,6 +1,8 @@ + // SPDX-License-Identifier: MIT + #include "LinuxSyscalls/Syscalls.h" + ++#include ++ + namespace FEX::HLE::FaultSafeUserMemAccess { + #ifdef ARCHITECTURE_arm64 + __attribute__((naked)) size_t CopyFromUser(void* Dest, const void* Src, size_t Size) { +@@ -41,6 +43,26 @@ __attribute__((naked)) size_t CopyToUser(void* Dest, const void* Src, size_t Siz + : "memory"); + } + ++__attribute__((naked)) static size_t StringReadableImpl(const char* Src) { ++ __asm volatile(R"( ++ 1: ++ .globl StringReadable_FaultInst ++ StringReadable_FaultInst: ++ ldrb w1, [x0], 1; // <- This line can fault. ++ cbnz w1, 1b; ++ mov x0, 0; ++ ret; ++ )" :: ++ : "memory"); ++} ++ ++bool IsStringReadable(const char* Src) { ++ return Src == nullptr || StringReadableImpl(Src) == 0; ++} ++ ++extern "C" uint64_t StringReadable_FaultInst; ++void* const StringReadable_FaultLocation = &StringReadable_FaultInst; ++ + extern "C" uint64_t CopyFromUser_FaultInst; + void* const CopyFromUser_FaultLocation = &CopyFromUser_FaultInst; + +@@ -157,6 +179,8 @@ bool IsFaultLocation(uint64_t PC) { + bool IsMemcpyFault = false; + IsMemcpyFault |= reinterpret_cast(PC) == CopyToUser_FaultLocation; + IsMemcpyFault |= reinterpret_cast(PC) == CopyFromUser_FaultLocation; ++ IsMemcpyFault |= reinterpret_cast(PC) == StringReadable_FaultLocation; ++ IsMemcpyFault |= FEXCore::Utils::FaultSafeRead::IsFaultLocation(PC); + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED && defined(ARCHITECTURE_arm64) + IsMemcpyFault |= reinterpret_cast(PC) == UserReadable_FaultLocation; + IsMemcpyFault |= reinterpret_cast(PC) == UserWritable_FaultLocation; +@@ -176,6 +200,10 @@ size_t CopyToUser(void* Dest, const void* Src, size_t Size) { + return Size; + } + ++bool IsStringReadable(const char* Src) { ++ return true; ++} ++ + bool IsFaultLocation(uint64_t PC) { + return false; + } +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +index 2210e4508..62b6a2d27 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +@@ -13,6 +13,7 @@ $end_info$ + #include "FEXCore/Config/Config.h" + #include "LinuxSyscalls/FileManagement.h" + #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h" ++#include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/x64/Syscalls.h" + +@@ -954,6 +955,27 @@ uint64_t FileManager::FAccessat2(int dirfd, const char* pathname, int mode, int + return ::syscall(SYSCALL_DEF(faccessat2), dirfd, SelfPath, mode, flags); + } + ++static std::optional ReadlinkTraceeExe(const char* Path, char* Buf, size_t BufSize) { ++ if (!Path || strncmp(Path, "/proc/", 6) != 0) { ++ return std::nullopt; ++ } ++ char* End = nullptr; ++ const long Pid = strtol(Path + 6, &End, 10); ++ if (End == Path + 6 || strcmp(End, "/exe") != 0) { ++ return std::nullopt; ++ } ++ const auto Exe = PtraceEmu::TraceeExePath(static_cast(Pid)); ++ if (!Exe) { ++ return std::nullopt; ++ } ++ const size_t Len = std::min(BufSize, Exe->size()); ++ if (FaultSafeUserMemAccess::CopyToUser(Buf, Exe->data(), Len)) { ++ errno = EFAULT; ++ return -1; ++ } ++ return Len; ++} ++ + uint64_t FileManager::Readlink(const char* pathname, char* buf, size_t bufsiz) { + // calculate the non-self link to exe + // Some executables do getpid, stat("/proc/$pid/exe") +@@ -962,8 +984,16 @@ uint64_t FileManager::Readlink(const char* pathname, char* buf, size_t bufsiz) { + + if (strcmp(pathname, "/proc/self/exe") == 0 || strcmp(pathname, "/proc/thread-self/exe") == 0 || strcmp(pathname, PidSelfPath) == 0) { + const auto& App = Filename(); +- strncpy(buf, App.c_str(), bufsiz); +- return std::min(bufsiz, App.size()); ++ const size_t Len = std::min(bufsiz, App.size()); ++ if (FaultSafeUserMemAccess::CopyToUser(buf, App.c_str(), Len)) { ++ errno = EFAULT; ++ return -1; ++ } ++ return Len; ++ } ++ ++ if (auto Traced = ReadlinkTraceeExe(pathname, buf, bufsiz)) { ++ return *Traced; + } + + FDPathTmpData TmpFilename; +@@ -1039,8 +1069,18 @@ uint64_t FileManager::Readlinkat(int dirfd, const char* pathname, char* buf, siz + + if (Path == "/proc/self/exe" || Path == "/proc/thread-self/exe" || Path == PidSelfPath) { + const auto& App = Filename(); +- strncpy(buf, App.c_str(), bufsiz); +- return std::min(bufsiz, App.size()); ++ const size_t Len = std::min(bufsiz, App.size()); ++ if (FaultSafeUserMemAccess::CopyToUser(buf, App.c_str(), Len)) { ++ errno = EFAULT; ++ return -1; ++ } ++ return Len; ++ } ++ ++ if (!Path.empty() && Path[0] == '/') { ++ if (auto Traced = ReadlinkTraceeExe(Path.c_str(), buf, bufsiz)) { ++ return *Traced; ++ } + } + + FDPathTmpData TmpFilename; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp +index 7ae8236b3..3be10d097 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp +@@ -50,6 +50,7 @@ public: + + void* Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) override; + int Munmap(void* addr, size_t length) override; ++ void TrackUnmapped(void* addr, size_t length) override; + void* Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) override; + uint64_t Shmat(int shmid, const void* shmaddr, int shmflg, uint32_t* ResultAddress) override; + uint64_t Shmdt(const void* shmaddr) override; +@@ -333,6 +334,17 @@ int MemAllocator32Bit::Munmap(void* addr, size_t length) { + return 0; + } + ++void MemAllocator32Bit::TrackUnmapped(void* addr, size_t length) { ++ std::scoped_lock lk {AllocMutex}; ++ ++ const uint64_t Addr = reinterpret_cast(addr); ++ const uint64_t PageAddr = std::max(Addr >> FEXCore::Utils::FEX_PAGE_SHIFT, BASE_KEY); ++ const uint64_t PageEnd = std::min(FEXCore::AlignUp(Addr + length, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT, TOP_KEY); ++ if (PageAddr < PageEnd) { ++ SetFreePages(PageAddr, PageEnd - PageAddr); ++ } ++} ++ + void* MemAllocator32Bit::Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) { + size_t OldPagesLength = FEXCore::AlignUp(old_size, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT; + size_t NewPagesLength = FEXCore::AlignUp(new_size, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h +index dd6ae074f..c84f85b4a 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h +@@ -14,6 +14,7 @@ public: + virtual ~MemAllocator() = default; + virtual void* Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) = 0; + virtual int Munmap(void* addr, size_t length) = 0; ++ virtual void TrackUnmapped(void* addr, size_t length) {} + virtual void* Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) = 0; + virtual uint64_t Shmat(int shmid, const void* shmaddr, int shmflg, uint32_t* ResultAddress) = 0; + virtual uint64_t Shmdt(const void* shmaddr) = 0; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +new file mode 100644 +index 000000000..ca4c86063 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +@@ -0,0 +1,838 @@ ++// SPDX-License-Identifier: MIT ++ ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/Syscalls.h" ++ ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE::PtraceEmu { ++namespace { ++#ifndef NT_X86_XSTATE ++ constexpr uintptr_t NT_X86_XSTATE = 0x202; ++#endif ++ ++ enum UserReg : unsigned { ++ R15, R14, R13, R12, Rbp, Rbx, R11, R10, R9, R8, Rax, Rcx, Rdx, Rsi, Rdi, OrigRax, Rip, Cs, Eflags, Rsp, Ss, FsBase, GsBase, Ds, Es, Fs, Gs, ++ }; ++ static_assert(Gs + 1 == NumUserRegs); ++ ++ constexpr uintptr_t UserDebugRegByteOffset = 848; ++ constexpr uintptr_t UserDebugRegByteEnd = UserDebugRegByteOffset + 8 * sizeof(uint64_t); ++ constexpr uintptr_t UserStructSize = 928; ++ ++ constexpr uint64_t UserTaskSizeMax = 0x00007ffffffff000ULL; ++ ++ bool DrFieldValid(uint64_t Field, uint64_t* AlignMask) { ++ const uint64_t Len = Field & 0xC; ++ switch (Field & 0x3) { ++ case 0x0: ++ if (Len != 0x0) { ++ return false; ++ } ++ *AlignMask = 0; ++ return true; ++ case 0x1: ++ case 0x3: ++ switch (Len) { ++ case 0x0: *AlignMask = 0; return true; ++ case 0x4: *AlignMask = 1; return true; ++ case 0xC: *AlignMask = 3; return true; ++ case 0x8: *AlignMask = 7; return true; ++ default: return false; ++ } ++ default: ++ return false; ++ } ++ } ++ ++ constexpr unsigned DrEnableShift(unsigned N) { return N * 2; } ++ constexpr unsigned DrFieldShift(unsigned N) { return 16 + N * 4; } ++ ++ bool DrAddressValid(uint64_t Addr, uint64_t AlignMask) { ++ return Addr < UserTaskSizeMax && (Addr & AlignMask) == 0; ++ } ++ ++ bool Dr7Valid(const uint64_t Dr[8], uint64_t NewDr7) { ++ for (unsigned N = 0; N < 4; ++N) { ++ const bool Enabled = (NewDr7 >> DrEnableShift(N)) & 0x3; ++ const bool Registered = Dr[N] != 0; ++ if (!Enabled && !Registered) { ++ continue; ++ } ++ const uint64_t Field = (NewDr7 >> DrFieldShift(N)) & 0xF; ++ uint64_t AlignMask = 0; ++ if (!DrFieldValid(Field, &AlignMask) || !DrAddressValid(Dr[N], AlignMask)) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ constexpr uint16_t UserCodeSegment = 0x33; ++ constexpr uint16_t UserStackSegment = 0x2b; ++ constexpr uint64_t UserFlags = 0x246; ++ constexpr uint64_t NoOverride = ~0ULL; ++ ++ constexpr int X86_PTRACE_GETREGS = 12; ++ constexpr int X86_PTRACE_SETREGS = 13; ++ constexpr int X86_PTRACE_EVENT_EXEC = 4; ++ ++ SharedState StaticState {SharedState::MagicValue}; ++ SharedState* Current = &StaticState; ++ thread_local uint64_t PendingRip = 0; ++ ++ struct OpenSyscall { ++ bool Open = false; ++ uint64_t Nr {}; ++ uint64_t Args[6] {}; ++ } Previous; ++ ++ constexpr const char* SidecarDirs[] = {"/dev/shm", "/tmp"}; ++ ++ std::string SidecarPath(const char* Dir, const char* Kind, pid_t Pid) { ++ return std::string(Dir) + "/fex-ptrace-" + Kind + "-" + std::to_string(Pid); ++ } ++ ++ int OpenSidecar(const char* Kind, pid_t Pid, int Flags) { ++ for (const char* Dir : SidecarDirs) { ++ const int fd = ::open(SidecarPath(Dir, Kind, Pid).c_str(), Flags | O_CLOEXEC, 0600); ++ if (fd >= 0) { ++ return fd; ++ } ++ } ++ return -1; ++ } ++ ++ void RemoveSidecar(const char* Kind, pid_t Pid) { ++ for (const char* Dir : SidecarDirs) { ++ ::unlink(SidecarPath(Dir, Kind, Pid).c_str()); ++ } ++ } ++ ++ bool IsMainThread() { ++ return ::syscall(SYS_gettid) == ::getpid(); ++ } ++ ++ bool HasHostTracer() { ++ const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ if (fd < 0) { ++ return true; ++ } ++ char Buf[2048]; ++ const ssize_t n = ::read(fd, Buf, sizeof(Buf) - 1); ++ ::close(fd); ++ if (n <= 0) { ++ return true; ++ } ++ Buf[n] = 0; ++ const char* Tag = strstr(Buf, "TracerPid:"); ++ return !Tag || atoi(Tag + sizeof("TracerPid:") - 1) != 0; ++ } ++ ++ ++ void BuildRegs(const FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, bool Entry, uint64_t Ret, uint64_t* X) { ++ using namespace FEXCore::X86State; ++ const auto& S = Frame->State; ++ X[R15] = S.gregs[REG_R15]; ++ X[R14] = S.gregs[REG_R14]; ++ X[R13] = S.gregs[REG_R13]; ++ X[R12] = S.gregs[REG_R12]; ++ X[Rbp] = S.gregs[REG_RBP]; ++ X[Rbx] = S.gregs[REG_RBX]; ++ X[R11] = UserFlags; ++ X[R10] = S.gregs[REG_R10]; ++ X[R9] = S.gregs[REG_R9]; ++ X[R8] = S.gregs[REG_R8]; ++ X[Rax] = Entry ? static_cast(-ENOSYS) : Ret; ++ X[Rcx] = S.gregs[REG_RCX]; ++ X[Rdx] = S.gregs[REG_RDX]; ++ X[Rsi] = S.gregs[REG_RSI]; ++ X[Rdi] = S.gregs[REG_RDI]; ++ X[OrigRax] = Nr; ++ X[Rip] = S.gregs[REG_RCX] ? S.gregs[REG_RCX] : S.rip; ++ X[Cs] = UserCodeSegment; ++ X[Eflags] = UserFlags; ++ X[Rsp] = S.gregs[REG_RSP]; ++ X[Ss] = UserStackSegment; ++ X[FsBase] = S.fs_cached; ++ X[GsBase] = S.gs_cached; ++ X[Ds] = X[Es] = X[Fs] = X[Gs] = 0; ++ } ++ ++ void Stop(uint64_t Nr, const uint64_t Args[6], bool Entry, uint64_t Ret, const uint64_t* Regs) { ++ SharedState& S = *Current; ++ if (!HasHostTracer()) { ++ S.SyscallStops = 0; ++ S.Attached = 0; ++ return; ++ } ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ S.Regs[i] = Regs[i]; ++ } ++ S.PendingNr = Nr; ++ for (unsigned i = 0; i < 6; ++i) { ++ S.PendingArgs[i] = Args[i]; ++ } ++ S.PendingRet = Ret; ++ S.PendingIsEntry = Entry ? 1 : 0; ++ S.Pending = 1; ++ ::syscall(SYS_tgkill, ::getpid(), ::syscall(SYS_gettid), SIGSTOP); ++ S.Pending = 0; ++ } ++ ++ uint64_t ApplyTracerWrites(FEXCore::Core::CpuStateFrame* Frame, bool Entry) { ++ using namespace FEXCore::X86State; ++ SharedState& S = *Current; ++ ++ if (S.FlushLen) { ++ const uint64_t Addr = S.FlushAddr; ++ const uint64_t Len = S.FlushLen; ++ S.FlushLen = 0; ++ FEX::HLE::_SyscallHandler->InvalidateGuestCodeRange(Frame->Thread, Addr, Len); ++ } ++ ++ const uint64_t Dirty = S.DirtyMask; ++ if (!Dirty) { ++ return NoOverride; ++ } ++ ++ static constexpr int Map[15] = {REG_R15, REG_R14, REG_R13, REG_R12, REG_RBP, REG_RBX, -1, REG_R10, REG_R9, REG_R8, -1, REG_RCX, REG_RDX, REG_RSI, REG_RDI}; ++ auto& State = Frame->State; ++ uint64_t Override = NoOverride; ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ if (!(Dirty & (1ULL << i))) { ++ continue; ++ } ++ const uint64_t V = S.Regs[i]; ++ if (i < 15) { ++ if (Map[i] >= 0) { ++ State.gregs[Map[i]] = V; ++ } ++ } else if (i == Rip) { ++ PendingRip = V; ++ } else if (i == Rsp) { ++ State.gregs[REG_RSP] = V; ++ } else if (i == FsBase) { ++ State.fs_cached = V; ++ } else if (i == GsBase) { ++ State.gs_cached = V; ++ } ++ if (i == Rax && !Entry) { ++ Override = V; ++ } ++ } ++ if (Entry && (Dirty & (1ULL << OrigRax))) { ++ State.gregs[REG_RAX] = S.Regs[OrigRax]; ++ } ++ S.DirtyMask = 0; ++ return Override; ++ } ++ ++ void PublishSharedPage() { ++ if (Current != &StaticState) { ++ return; ++ } ++ const int fd = OpenSidecar("state", ::getpid(), O_RDWR | O_CREAT | O_TRUNC); ++ if (fd < 0) { ++ return; ++ } ++ if (::ftruncate(fd, 4096) == 0) { ++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ if (Page != MAP_FAILED) { ++ std::memcpy(Page, &StaticState, sizeof(SharedState)); ++ Current = static_cast(Page); ++ } ++ } ++ ::close(fd); ++ } ++ ++ struct Remote { ++ uint8_t* Mapped = nullptr; ++ uintptr_t StaticAddr = 0; ++ std::array FpRegs {}; ++ bool FpValid = false; ++ std::array XState {}; ++ bool XStateValid = false; ++ }; ++ std::mutex RemotesLock; ++ std::unordered_map Remotes; ++ std::unordered_map ExePaths; ++ ++ uintptr_t FindFexImageBase(pid_t Pid) { ++ static const std::string SelfExe = []() { ++ char Buf[512]; ++ const ssize_t n = ::readlink("/proc/self/exe", Buf, sizeof(Buf) - 1); ++ return n > 0 ? std::string(Buf, n) : std::string(); ++ }(); ++ if (SelfExe.empty()) { ++ return 0; ++ } ++ const std::string Maps = Pid ? "/proc/" + std::to_string(Pid) + "/maps" : "/proc/self/maps"; ++ FILE* F = fopen(Maps.c_str(), "r"); ++ if (!F) { ++ return 0; ++ } ++ char Line[1024]; ++ uintptr_t Lowest = 0; ++ while (fgets(Line, sizeof(Line), F)) { ++ if (!strstr(Line, SelfExe.c_str())) { ++ continue; ++ } ++ unsigned long long Start = 0, End = 0, Offset = 0; ++ if (sscanf(Line, "%llx-%llx %*s %llx", &Start, &End, &Offset) == 3 && Offset == 0 && (!Lowest || Start < Lowest)) { ++ Lowest = Start; ++ } ++ } ++ fclose(F); ++ return Lowest; ++ } ++ ++ Remote* Lookup(pid_t Pid) { ++ auto It = Remotes.find(Pid); ++ if (It != Remotes.end()) { ++ return &It->second; ++ } ++ Remote R; ++ const int fd = OpenSidecar("state", Pid, O_RDWR); ++ if (fd >= 0) { ++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ ::close(fd); ++ if (Page != MAP_FAILED) { ++ R.Mapped = static_cast(Page); ++ } ++ } ++ if (!R.Mapped) { ++ static const uintptr_t SelfBase = FindFexImageBase(0); ++ const uintptr_t TraceeBase = FindFexImageBase(Pid); ++ if (!SelfBase || !TraceeBase) { ++ return nullptr; ++ } ++ R.StaticAddr = TraceeBase + (reinterpret_cast(&StaticState) - SelfBase); ++ } ++ return &Remotes.emplace(Pid, std::move(R)).first->second; ++ } ++ ++ void Forget(pid_t Pid, bool Exited) { ++ std::lock_guard lk(RemotesLock); ++ auto It = Remotes.find(Pid); ++ if (It != Remotes.end()) { ++ if (It->second.Mapped) { ++ ::munmap(It->second.Mapped, 4096); ++ } ++ Remotes.erase(It); ++ } ++ RemoveSidecar("state", Pid); ++ if (Exited) { ++ ExePaths.erase(Pid); ++ } ++ } ++ ++ void CaptureExecPath(pid_t Pid) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (R && R->Mapped) { ++ auto* S = reinterpret_cast(R->Mapped); ++ if (S->Magic == SharedState::MagicValue && S->ExePath[0]) { ++ ExePaths[Pid] = std::string(S->ExePath, strnlen(S->ExePath, sizeof(S->ExePath))); ++ } ++ } ++ } ++ ++ uint64_t HostPtrace(int Request, pid_t Pid, void* Addr, void* Data) { ++ const long R = ::syscall(SYS_ptrace, Request, Pid, Addr, Data); ++ return R == -1 ? static_cast(-errno) : static_cast(R); ++ } ++ ++ bool ReadWord(pid_t Pid, size_t Offset, uint64_t* Out) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (!R) { ++ return false; ++ } ++ if (R->Mapped) { ++ *Out = *reinterpret_cast(R->Mapped + Offset); ++ return true; ++ } ++ return ::syscall(SYS_ptrace, PTRACE_PEEKDATA, Pid, R->StaticAddr + Offset, Out) == 0; ++ } ++ ++ bool WriteWord(pid_t Pid, size_t Offset, uint64_t Value) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (!R) { ++ return false; ++ } ++ if (R->Mapped) { ++ *reinterpret_cast(R->Mapped + Offset) = Value; ++ return true; ++ } ++ return ::syscall(SYS_ptrace, PTRACE_POKEDATA, Pid, R->StaticAddr + Offset, Value) == 0; ++ } ++ ++ bool IsFexTracee(pid_t Pid) { ++ uint64_t Magic = 0; ++ return ReadWord(Pid, offsetof(SharedState, Magic), &Magic) && Magic == SharedState::MagicValue; ++ } ++ ++ bool ReadSlot(pid_t Pid, size_t Offset, uint64_t* Out) { ++ return ReadWord(Pid, Offset, Out); ++ } ++ ++ void MarkDirty(pid_t Pid, uint64_t Mask) { ++ uint64_t Dirty = 0; ++ ReadWord(Pid, offsetof(SharedState, DirtyMask), &Dirty); ++ WriteWord(Pid, offsetof(SharedState, DirtyMask), Dirty | Mask); ++ } ++ ++ constexpr size_t RegOffset(unsigned Index) { ++ return offsetof(SharedState, Regs) + Index * sizeof(uint64_t); ++ } ++ ++ bool ReadDebugReg(pid_t Pid, unsigned N, uint64_t* Out) { ++ if (N == 4 || N == 5) { ++ *Out = 0; ++ return true; ++ } ++ if (N > 7) { ++ return false; ++ } ++ return ReadWord(Pid, offsetof(SharedState, DebugRegs) + N * sizeof(uint64_t), Out); ++ } ++ ++ int WriteDebugReg(pid_t Pid, unsigned N, uint64_t Value) { ++ if (N == 4 || N == 5) { ++ return -EIO; ++ } ++ if (N <= 3) { ++ if (!DrAddressValid(Value, 0)) { ++ return -EINVAL; ++ } ++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + N * sizeof(uint64_t), Value) ? 0 : -ESRCH; ++ } ++ if (N == 6) { ++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + 6 * sizeof(uint64_t), Value) ? 0 : -ESRCH; ++ } ++ uint64_t Dr[8] {}; ++ for (unsigned I = 0; I < 8; ++I) { ++ if (!ReadWord(Pid, offsetof(SharedState, DebugRegs) + I * sizeof(uint64_t), &Dr[I])) { ++ return -ESRCH; ++ } ++ } ++ if (!Dr7Valid(Dr, Value)) { ++ return -EINVAL; ++ } ++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + 7 * sizeof(uint64_t), Value) ? 0 : -ESRCH; ++ } ++ ++ Remote* XStateState(pid_t Pid) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (R && !R->XStateValid) { ++ R->XStateValid = true; ++ } ++ return R; ++ } ++ ++ Remote* FpState(pid_t Pid) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (R && !R->FpValid) { ++ const uint16_t Fcw = 0x37f; ++ const uint32_t Mxcsr = 0x1f80, MxcsrMask = 0xffff; ++ std::memcpy(&R->FpRegs[0], &Fcw, sizeof(Fcw)); ++ std::memcpy(&R->FpRegs[24], &Mxcsr, sizeof(Mxcsr)); ++ std::memcpy(&R->FpRegs[28], &MxcsrMask, sizeof(MxcsrMask)); ++ R->FpValid = true; ++ } ++ return R; ++ } ++} ++ ++ ++bool IsAttached() { ++ return Current->Attached != 0; ++} ++ ++bool WantsSyscallStops() { ++ return Current->SyscallStops && IsMainThread(); ++} ++ ++uint64_t SyscallEntryStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6]) { ++ uint64_t Regs[NumUserRegs]; ++ if (Previous.Open) { ++ BuildRegs(Frame, Previous.Nr, false, 0, Regs); ++ Stop(Previous.Nr, Previous.Args, false, 0, Regs); ++ } ++ BuildRegs(Frame, Nr, true, 0, Regs); ++ Stop(Nr, Args, true, 0, Regs); ++ ApplyTracerWrites(Frame, true); ++ ++ const uint64_t NewNr = Frame->State.gregs[FEXCore::X86State::REG_RAX]; ++ Previous.Open = Current->SyscallStops != 0; ++ Previous.Nr = NewNr; ++ std::copy(Args, Args + 6, Previous.Args); ++ return NewNr; ++} ++ ++uint64_t SyscallExitStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6], uint64_t Result) { ++ uint64_t Regs[NumUserRegs]; ++ BuildRegs(Frame, Nr, false, Result, Regs); ++ Stop(Nr, Args, false, Result, Regs); ++ const uint64_t Override = ApplyTracerWrites(Frame, false); ++ Previous.Open = false; ++ return Override != NoOverride ? Override : Result; ++} ++ ++void OnForkedChild(bool SharesAddressSpace) { ++ if (SharesAddressSpace) { ++ return; ++ } ++ Current = &StaticState; ++ StaticState.SyscallStops = 0; ++ StaticState.Attached = 0; ++ StaticState.Pending = 0; ++ Previous.Open = false; ++} ++ ++void ApplyPendingFlush(FEXCore::Core::CpuStateFrame* Frame) { ++ SharedState& S = *Current; ++ if (S.FlushLen) { ++ const uint64_t Addr = S.FlushAddr; ++ const uint64_t Len = S.FlushLen; ++ S.FlushLen = 0; ++ FEX::HLE::_SyscallHandler->InvalidateGuestCodeRange(Frame->Thread, Addr, Len); ++ } ++} ++ ++uint64_t TakePendingRip() { ++ const uint64_t Rip = PendingRip; ++ PendingRip = 0; ++ return Rip; ++} ++ ++bool TryGuestSignalStop(FEXCore::Core::CpuStateFrame* Frame, int Signal) { ++ if (Signal != SIGTRAP && Signal != SIGSEGV) { ++ return false; ++ } ++ if (!Frame->SynchronousFaultData.FaultToTopAndGeneratedException || !Current->Attached || !IsMainThread()) { ++ return false; ++ } ++ ++ uint64_t Regs[NumUserRegs]; ++ const uint64_t NoArgs[6] {}; ++ BuildRegs(Frame, ~0ULL, false, Frame->State.gregs[FEXCore::X86State::REG_RAX], Regs); ++ Regs[Rip] = Frame->State.rip; ++ ++ Current->SignalNumber = static_cast(Signal); ++ Stop(~0ULL, NoArgs, false, 0, Regs); ++ Current->SignalNumber = 0; ++ ++ const uint64_t Override = ApplyTracerWrites(Frame, false); ++ if (Override != NoOverride) { ++ Frame->State.gregs[FEXCore::X86State::REG_RAX] = Override; ++ } ++ if (const uint64_t NewRip = TakePendingRip()) { ++ Frame->State.rip = NewRip; ++ } ++ return true; ++} ++ ++void RecordExecPath(const std::string& GuestPath) { ++ if (!Current->Attached) { ++ return; ++ } ++ const size_t Len = std::min(GuestPath.size(), sizeof(Current->ExePath) - 1); ++ std::memcpy(Current->ExePath, GuestPath.data(), Len); ++ Current->ExePath[Len] = 0; ++} ++ ++ ++std::optional TraceeExePath(pid_t Pid) { ++ if (Pid <= 0 || Pid == ::getpid()) { ++ return std::nullopt; ++ } ++ std::lock_guard lk(RemotesLock); ++ auto It = ExePaths.find(Pid); ++ return It != ExePaths.end() ? std::optional(It->second) : std::nullopt; ++} ++ ++bool FixupWaitStatus(pid_t Pid, int* Status) { ++ if (!Status || Pid <= 0) { ++ return false; ++ } ++ const int St = *Status; ++ ++ if (WIFEXITED(St) || WIFSIGNALED(St)) { ++ Forget(Pid, true); ++ return false; ++ } ++ if (!WIFSTOPPED(St)) { ++ return false; ++ } ++ ++ if ((St >> 16) == 0 && (WSTOPSIG(St) == SIGTRAP || WSTOPSIG(St) == SIGSEGV) && IsFexTracee(Pid)) { ++ HostPtrace(PTRACE_CONT, Pid, nullptr, reinterpret_cast(static_cast(WSTOPSIG(St)))); ++ return true; ++ } ++ ++ if ((St >> 16) == 0 && WSTOPSIG(St) == SIGBUS && IsFexTracee(Pid)) { ++ siginfo_t Info {}; ++ if (HostPtrace(PTRACE_GETSIGINFO, Pid, nullptr, &Info) == 0 && Info.si_code == BUS_ADRALN) { ++ HostPtrace(PTRACE_CONT, Pid, nullptr, reinterpret_cast(static_cast(SIGBUS))); ++ return true; ++ } ++ } ++ ++ if ((St >> 16) == 0 && WSTOPSIG(St) == SIGPROF && IsFexTracee(Pid)) { ++ HostPtrace(PTRACE_CONT, Pid, nullptr, nullptr); ++ return true; ++ } ++ ++ if ((St >> 16) == X86_PTRACE_EVENT_EXEC) { ++ CaptureExecPath(Pid); ++ Forget(Pid, false); ++ } ++ ++ if (WSTOPSIG(St) == SIGSTOP) { ++ uint64_t Pending = 0; ++ if (ReadWord(Pid, offsetof(SharedState, Pending), &Pending) && Pending) { ++ uint64_t Signal = 0; ++ ReadWord(Pid, offsetof(SharedState, SignalNumber), &Signal); ++ *Status = (St & ~0xff00) | (static_cast(Signal ? Signal : (SIGTRAP | 0x80)) << 8); ++ } ++ } ++ return false; ++} ++ ++bool HandleRequest(int Request, pid_t Pid, void* Addr, void* Data, uint64_t* Result) { ++ switch (Request) { ++ case PTRACE_TRACEME: ++ *Result = HostPtrace(Request, Pid, Addr, Data); ++ if (*Result == 0) { ++ PublishSharedPage(); ++ Current->Attached = 1; ++ } ++ return true; ++ ++ case PTRACE_KILL: ++ case PTRACE_SEIZE: ++ case PTRACE_INTERRUPT: ++ case PTRACE_SETOPTIONS: ++ case PTRACE_GETEVENTMSG: ++ case PTRACE_SINGLESTEP: ++ case PTRACE_GETSIGINFO: *Result = HostPtrace(Request, Pid, Addr, Data); return true; ++ ++ case PTRACE_POKETEXT: ++ case PTRACE_POKEDATA: { ++ *Result = HostPtrace(Request, Pid, Addr, Data); ++ if (*Result == 0 && IsFexTracee(Pid)) { ++ const uint64_t Lo = reinterpret_cast(Addr) & ~0xfffULL; ++ const uint64_t Hi = Lo + 0x2000; ++ uint64_t OldAddr = 0, OldLen = 0; ++ ReadWord(Pid, offsetof(SharedState, FlushAddr), &OldAddr); ++ ReadWord(Pid, offsetof(SharedState, FlushLen), &OldLen); ++ uint64_t NewLo = Lo, NewHi = Hi; ++ if (OldLen) { ++ NewLo = std::min(OldAddr, Lo); ++ NewHi = std::max(OldAddr + OldLen, Hi); ++ } ++ WriteWord(Pid, offsetof(SharedState, FlushAddr), NewLo); ++ WriteWord(Pid, offsetof(SharedState, FlushLen), NewHi - NewLo); ++ } ++ return true; ++ } ++ ++ case PTRACE_CONT: ++ case PTRACE_SYSCALL: { ++ uint64_t Magic = 0; ++ if (ReadWord(Pid, offsetof(SharedState, Magic), &Magic) && Magic == SharedState::MagicValue) { ++ WriteWord(Pid, offsetof(SharedState, SyscallStops), Request == PTRACE_SYSCALL ? 1 : 0); ++ WriteWord(Pid, offsetof(SharedState, Attached), 1); ++ } ++ *Result = HostPtrace(PTRACE_CONT, Pid, Addr, Data); ++ return true; ++ } ++ ++ case PTRACE_DETACH: { ++ if (IsFexTracee(Pid)) { ++ WriteWord(Pid, offsetof(SharedState, SyscallStops), 0); ++ WriteWord(Pid, offsetof(SharedState, Attached), 0); ++ } ++ *Result = HostPtrace(Request, Pid, Addr, Data); ++ Forget(Pid, false); ++ return true; ++ } ++ ++ case PTRACE_PEEKUSER: { ++ const uintptr_t Off = reinterpret_cast(Addr); ++ if ((Off % sizeof(uint64_t)) != 0 || Off >= UserStructSize) { ++ *Result = static_cast(-EIO); ++ return true; ++ } ++ uint64_t V = 0; ++ if (Off < NumUserRegs * sizeof(uint64_t)) { ++ if (!ReadSlot(Pid, RegOffset(Off / 8), &V)) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ } else if (Off >= UserDebugRegByteOffset && Off < UserDebugRegByteEnd) { ++ if (!ReadDebugReg(Pid, static_cast((Off - UserDebugRegByteOffset) / sizeof(uint64_t)), &V)) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ } ++ *static_cast(Data) = V; ++ *Result = 0; ++ return true; ++ } ++ ++ case PTRACE_POKEUSER: { ++ const uintptr_t Off = reinterpret_cast(Addr); ++ if ((Off % sizeof(uint64_t)) != 0 || Off >= UserStructSize) { ++ *Result = static_cast(-EIO); ++ return true; ++ } ++ if (Off < NumUserRegs * sizeof(uint64_t)) { ++ if (!WriteWord(Pid, RegOffset(Off / 8), reinterpret_cast(Data))) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ MarkDirty(Pid, 1ULL << (Off / 8)); ++ *Result = 0; ++ return true; ++ } ++ if (Off >= UserDebugRegByteOffset && Off < UserDebugRegByteEnd) { ++ *Result = static_cast(WriteDebugReg(Pid, static_cast((Off - UserDebugRegByteOffset) / sizeof(uint64_t)), reinterpret_cast(Data))); ++ return true; ++ } ++ *Result = static_cast(-EIO); ++ return true; ++ } ++ ++ case X86_PTRACE_GETREGS: { ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ uint64_t V = 0; ++ if (!ReadSlot(Pid, RegOffset(i), &V)) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ static_cast(Data)[i] = V; ++ } ++ *Result = 0; ++ return true; ++ } ++ ++ case X86_PTRACE_SETREGS: { ++ uint64_t Mask = 0; ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ if (!WriteWord(Pid, RegOffset(i), static_cast(Data)[i])) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ Mask |= 1ULL << i; ++ } ++ MarkDirty(Pid, Mask); ++ *Result = 0; ++ return true; ++ } ++ ++ case PTRACE_GETREGSET: ++ case PTRACE_SETREGSET: { ++ const auto NtType = reinterpret_cast(Addr); ++ auto* Iov = static_cast(Data); ++ if (!Iov) { ++ return false; ++ } ++ const bool Get = Request == PTRACE_GETREGSET; ++ ++ if (NtType == NT_PRSTATUS) { ++ if (Get) { ++ uint64_t Image[NumUserRegs]; ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ if (!ReadSlot(Pid, RegOffset(i), &Image[i])) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ } ++ const size_t Len = std::min(Iov->iov_len, sizeof(Image)); ++ std::memcpy(Iov->iov_base, Image, Len); ++ Iov->iov_len = Len; ++ } else { ++ const size_t Slots = std::min(Iov->iov_len / sizeof(uint64_t), NumUserRegs); ++ uint64_t Mask = 0; ++ for (size_t i = 0; i < Slots; ++i) { ++ if (!WriteWord(Pid, RegOffset(i), static_cast(Iov->iov_base)[i])) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ Mask |= 1ULL << i; ++ } ++ MarkDirty(Pid, Mask); ++ Iov->iov_len = NumUserRegs * sizeof(uint64_t); ++ } ++ *Result = 0; ++ return true; ++ } ++ ++ if (NtType == NT_PRFPREG) { ++ Remote* R = FpState(Pid); ++ if (!R) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ const size_t Len = std::min(Iov->iov_len, R->FpRegs.size()); ++ if (Get) { ++ std::memcpy(Iov->iov_base, R->FpRegs.data(), Len); ++ } else { ++ std::memcpy(R->FpRegs.data(), Iov->iov_base, Len); ++ } ++ Iov->iov_len = Len; ++ *Result = 0; ++ return true; ++ } ++ ++ if (NtType == NT_X86_XSTATE) { ++ Remote* R = XStateState(Pid); ++ if (!R) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ const size_t Len = std::min(Iov->iov_len, R->XState.size()); ++ if (Get) { ++ std::memcpy(Iov->iov_base, R->XState.data(), Len); ++ } else { ++ std::memcpy(R->XState.data(), Iov->iov_base, Len); ++ } ++ Iov->iov_len = Len; ++ *Result = 0; ++ return true; ++ } ++ ++ *Result = static_cast(-EINVAL); ++ return true; ++ } ++ ++ default: return false; ++ } ++} ++ ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h +new file mode 100644 +index 000000000..59194979a +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h +@@ -0,0 +1,63 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++#include ++#include ++#include ++ ++namespace FEXCore::Core { ++struct CpuStateFrame; ++} ++ ++namespace FEX::HLE::PtraceEmu { ++ ++constexpr unsigned NumUserRegs = 27; ++ ++struct SharedState { ++ static constexpr uint64_t MagicValue = 0xFE8E5E57CAFE0001ULL; ++ ++ volatile uint64_t Magic; ++ volatile uint64_t SyscallStops; ++ volatile uint64_t Attached; ++ volatile uint64_t Pending; ++ volatile uint64_t PendingIsEntry; ++ volatile uint64_t PendingNr; ++ volatile uint64_t PendingArgs[6]; ++ volatile uint64_t PendingRet; ++ volatile uint64_t Regs[NumUserRegs]; ++ volatile uint64_t DebugRegs[8]; ++ volatile uint64_t DirtyMask; ++ volatile uint64_t SignalNumber; ++ volatile uint64_t FlushAddr; ++ volatile uint64_t FlushLen; ++ char ExePath[1024]; ++}; ++ ++ ++bool WantsSyscallStops(); ++ ++uint64_t SyscallEntryStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6]); ++ ++uint64_t SyscallExitStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6], uint64_t Result); ++ ++void OnForkedChild(bool SharesAddressSpace); ++ ++void ApplyPendingFlush(FEXCore::Core::CpuStateFrame* Frame); ++ ++uint64_t TakePendingRip(); ++ ++bool TryGuestSignalStop(FEXCore::Core::CpuStateFrame* Frame, int Signal); ++ ++void RecordExecPath(const std::string& GuestPath); ++ ++bool IsAttached(); ++ ++ ++bool HandleRequest(int Request, pid_t Pid, void* Addr, void* Data, uint64_t* Result); ++ ++bool FixupWaitStatus(pid_t Pid, int* Status); ++ ++std::optional TraceeExePath(pid_t Pid); ++ ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h +new file mode 100644 +index 000000000..3f36e79fd +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h +@@ -0,0 +1,90 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE { ++ ++class SMCHotPageTracker final { ++public: ++ static constexpr uint64_t PageShift = 12; ++ ++ bool RecordFault(uint64_t Address, uint32_t FaultThreshold) { ++ if (!FaultThreshold) { ++ return false; ++ } ++ const uint64_t Page = Address >> PageShift; ++ auto& Slot = Counters[Hash(Page) & (CounterSlots - 1)]; ++ ++ uint64_t Old = Slot.load(std::memory_order_relaxed); ++ uint64_t New; ++ do { ++ const uint64_t Count = (Old >> CountBits) == Page ? (Old & CountMask) + 1 : 1; ++ New = (Page << CountBits) | (Count < CountMask ? Count : CountMask); ++ } while (!Slot.compare_exchange_weak(Old, New, std::memory_order_relaxed)); ++ ++ return (New & CountMask) == FaultThreshold && MakeHot(Page); ++ } ++ ++ bool MarkHot(uint64_t Address) { ++ return MakeHot(Address >> PageShift); ++ } ++ ++ bool IsHot(uint64_t Address) const { ++ if (HotCount.load(std::memory_order_relaxed) == 0) { ++ return false; ++ } ++ ++ const uint64_t Key = (Address >> PageShift) + 1; ++ for (size_t i = 0, Idx = Hash(Key - 1); i < HotSlots; ++i, ++Idx) { ++ const uint64_t Entry = Hot[Idx & (HotSlots - 1)].load(std::memory_order_relaxed); ++ if (Entry == Key) { ++ return true; ++ } ++ if (Entry == 0) { ++ return false; ++ } ++ } ++ return false; ++ } ++ ++private: ++ static constexpr size_t CounterSlots = 4096; ++ static constexpr size_t HotSlots = 2048; ++ static constexpr unsigned CountBits = 20; ++ static constexpr uint64_t CountMask = (1ULL << CountBits) - 1; ++ static_assert((CounterSlots & (CounterSlots - 1)) == 0 && (HotSlots & (HotSlots - 1)) == 0); ++ ++ static size_t Hash(uint64_t Page) { ++ return static_cast((Page * 0x9E3779B97F4A7C15ULL) >> 40); ++ } ++ ++ bool MakeHot(uint64_t Page) { ++ if (HotCount.load(std::memory_order_relaxed) >= HotSlots / 4 * 3) { ++ return false; ++ } ++ ++ const uint64_t Key = Page + 1; ++ for (size_t i = 0, Idx = Hash(Page); i < HotSlots; ++i, ++Idx) { ++ auto& Entry = Hot[Idx & (HotSlots - 1)]; ++ uint64_t Expected = 0; ++ if (Entry.compare_exchange_strong(Expected, Key, std::memory_order_relaxed)) { ++ HotCount.fetch_add(1, std::memory_order_relaxed); ++ return true; ++ } ++ if (Expected == Key) { ++ return false; ++ } ++ } ++ return false; ++ } ++ ++ std::array, CounterSlots> Counters {}; ++ std::array, HotSlots> Hot {}; ++ std::atomic HotCount {}; ++}; ++ ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp +new file mode 100644 +index 000000000..abc3284a3 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp +@@ -0,0 +1,278 @@ ++// SPDX-License-Identifier: MIT ++#include "LinuxSyscalls/SamplingProfiler.h" ++#include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "ArchHelpers/MContext.h" ++ ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE { ++namespace { ++ struct Sample { ++ uint64_t HostPC; ++ uint64_t Info; ++ }; ++ constexpr size_t MaxSamples = 1 << 18; ++ std::atomic RecordsPtr {nullptr}; ++ Sample* Records = nullptr; ++ std::atomic Count {0}; ++ ++ struct SnapRecord { ++ uint64_t Tid; ++ uint64_t HostPC; ++ uint64_t Rip; ++ uint64_t FutexWord; ++ uint64_t FutexExpected; ++ uint64_t FutexAddr; ++ uint64_t Gregs[16]; ++ uint64_t Stack[138]; ++ }; ++ static_assert(sizeof(SnapRecord) == 160 * 8); ++ constexpr size_t MaxSnaps = 1024; ++ SnapRecord* Snaps = nullptr; ++ std::atomic SnapCount {0}; ++ std::atomic SnapMode {false}; ++ bool ExternalMode = false; ++ FEX::HLE::SignalDelegator* Delegator = nullptr; ++ std::atomic ExternalOpen {false}; ++ ++ void OpenExternalSnaps() { ++ if (ExternalOpen.exchange(true)) { ++ return; ++ } ++ char Path[64]; ++ snprintf(Path, sizeof(Path), "/dev/shm/fex-%d-snap", static_cast(getpid())); ++ const int fd = open(Path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0 || ftruncate(fd, sizeof(SnapRecord) * MaxSnaps) != 0) { ++ return; ++ } ++ void* Map = mmap(nullptr, sizeof(SnapRecord) * MaxSnaps, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map != MAP_FAILED) { ++ Snaps = static_cast(Map); ++ } ++ } ++ ++ bool IsInteresting(pid_t Tid) { ++ static thread_local std::unordered_map Last; ++ char Path[64]; ++ snprintf(Path, sizeof(Path), "/proc/self/task/%d/stat", Tid); ++ FILE* F = fopen(Path, "r"); ++ if (!F) { ++ return false; ++ } ++ char Buf[512]; ++ const bool Ok = fgets(Buf, sizeof(Buf), F) != nullptr; ++ fclose(F); ++ if (!Ok) { ++ return false; ++ } ++ const char* P = strrchr(Buf, ')'); ++ unsigned long Ut = 0, St = 0; ++ if (!P || sscanf(P + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu", &Ut, &St) != 2) { ++ return false; ++ } ++ auto& L = Last[Tid]; ++ const bool Busy = (Ut + St) > L; ++ L = Ut + St; ++ return Busy; ++ } ++ ++ bool OpenRecords(pid_t Pid) { ++ if (Records) { ++ return true; ++ } ++ const std::string Path = "/dev/shm/fex-" + std::to_string(Pid) + "-samples"; ++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0 || ftruncate(fd, sizeof(Sample) * MaxSamples) != 0) { ++ return false; ++ } ++ void* Map = mmap(nullptr, sizeof(Sample) * MaxSamples, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map == MAP_FAILED) { ++ return false; ++ } ++ Records = static_cast(Map); ++ return true; ++ } ++ ++ void TakeSnapshot(pid_t Pid) { ++ if (!Snaps) { ++ const std::string Path = "/dev/shm/fex-" + std::to_string(Pid) + "-snap"; ++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0 || ftruncate(fd, sizeof(SnapRecord) * MaxSnaps) != 0) { ++ return; ++ } ++ void* Map = mmap(nullptr, sizeof(SnapRecord) * MaxSnaps, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map == MAP_FAILED) { ++ return; ++ } ++ Snaps = static_cast(Map); ++ } ++ memset(Snaps, 0, sizeof(SnapRecord) * MaxSnaps); ++ SnapCount = 0; ++ SnapMode = true; ++ if (DIR* D = opendir("/proc/self/task")) { ++ while (auto* E = readdir(D)) { ++ const pid_t Tid = atoi(E->d_name); ++ if (Tid > 0 && Tid != static_cast(syscall(SYS_gettid))) { ++ syscall(SYS_tgkill, Pid, Tid, SIGPROF); ++ } ++ } ++ closedir(D); ++ } ++ usleep(700000); ++ SnapMode = false; ++ } ++ ++ void* SamplerThread(void* Arg) { ++ const uint32_t Hz = static_cast(reinterpret_cast(Arg) & 0xffff); ++ const bool All = (reinterpret_cast(Arg) >> 16) != 0; ++ const pid_t Pid = getpid(); ++ const std::string Trigger = "/dev/shm/fex-" + std::to_string(Pid) + "-sample-on"; ++ const std::string SnapTrigger = "/dev/shm/fex-" + std::to_string(Pid) + "-snapshot"; ++ for (;;) { ++ if (access(SnapTrigger.c_str(), F_OK) == 0) { ++ unlink(SnapTrigger.c_str()); ++ TakeSnapshot(Pid); ++ continue; ++ } ++ if (access(Trigger.c_str(), F_OK) != 0) { ++ usleep(100000); ++ continue; ++ } ++ if (!OpenRecords(Pid)) { ++ usleep(100000); ++ continue; ++ } ++ usleep(1000000 / Hz); ++ if (FEX::HLE::PtraceEmu::IsAttached()) { ++ continue; ++ } ++ if (All) { ++ if (DIR* D = opendir("/proc/self/task")) { ++ while (auto* E = readdir(D)) { ++ const pid_t Tid = atoi(E->d_name); ++ if (Tid > 0 && Tid != static_cast(syscall(SYS_gettid)) && IsInteresting(Tid)) { ++ syscall(SYS_tgkill, Pid, Tid, SIGPROF); ++ } ++ } ++ closedir(D); ++ } ++ } else { ++ syscall(SYS_tgkill, Pid, Pid, SIGPROF); ++ } ++ } ++ return nullptr; ++ } ++} ++ ++void StartSamplingProfiler(FEX::HLE::SignalDelegator* Signals, uint32_t Hz, bool AllThreads, bool External) { ++ if (!Hz) { ++ return; ++ } ++ ExternalMode = External; ++ Delegator = Signals; ++ Signals->RegisterHostSignalHandler( ++ SIGPROF, ++ [](FEXCore::Core::InternalThreadState* Thread, int, void*, void* UContext) { ++ if (ExternalMode) { ++ OpenExternalSnaps(); ++ } ++ if (ExternalMode || SnapMode.load(std::memory_order_relaxed)) { ++ uint32_t SIdx = SnapCount.fetch_add(1, std::memory_order_relaxed); ++ const uint32_t Seq = SIdx; ++ if (ExternalMode) { ++ SIdx %= MaxSnaps; ++ } ++ if (Snaps && SIdx < MaxSnaps) { ++ SnapRecord& R = Snaps[SIdx]; ++ R.Tid = static_cast(syscall(SYS_gettid)); ++ R.HostPC = ArchHelpers::Context::GetPc(UContext); ++ if (Thread) { ++ const auto& St = Thread->CurrentFrame->State; ++ R.Rip = St.rip; ++ for (unsigned i = 0; i < 16; ++i) { ++ R.Gregs[i] = St.gregs[i]; ++ } ++ iovec Local {R.Stack, sizeof(R.Stack)}; ++ iovec Remote {reinterpret_cast(St.gregs[FEXCore::X86State::REG_RSP]), sizeof(R.Stack)}; ++ process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0); ++ ++ const uint64_t Nr = St.gregs[FEXCore::X86State::REG_RAX]; ++ if (Nr == 202 || Nr == 449) { ++ uint64_t Addr = St.gregs[FEXCore::X86State::REG_RDI]; ++ uint64_t Expected = St.gregs[FEXCore::X86State::REG_RDX]; ++ if (Nr == 449) { ++ uint64_t Waiter[3] {}; ++ iovec WL {Waiter, sizeof(Waiter)}; ++ iovec WR {reinterpret_cast(Addr), sizeof(Waiter)}; ++ Addr = process_vm_readv(getpid(), &WL, 1, &WR, 1, 0) == static_cast(sizeof(Waiter)) ? Waiter[1] : 0; ++ Expected = Waiter[0]; ++ } ++ uint32_t Word = 0; ++ iovec FL {&Word, sizeof(Word)}; ++ iovec FR {reinterpret_cast(Addr), sizeof(Word)}; ++ if (Addr && process_vm_readv(getpid(), &FL, 1, &FR, 1, 0) == static_cast(sizeof(Word))) { ++ R.FutexWord = (1ULL << 63) | Word; ++ R.FutexExpected = Expected; ++ R.FutexAddr = Addr; ++ } ++ } ++ } ++ if (ExternalMode) { ++ R.FutexWord = 0; ++ R.FutexExpected = Seq; ++ R.FutexAddr = ArchHelpers::Context::GetSp(UContext); ++ if (Thread && Thread->CTX->IsAddressInCodeBuffer(Thread, R.HostPC)) { ++ R.FutexWord = 1; ++ R.Rip = Thread->CTX->RestoreRIPFromHostPC(Thread, R.HostPC); ++ const auto& Cfg = Delegator->GetConfig(); ++ for (size_t i = 0; i < Cfg.SRAGPRCount && i < 16; ++i) { ++ R.Gregs[i] = ArchHelpers::Context::GetArmReg(UContext, Cfg.SRAGPRMapping[i]); ++ } ++ iovec Local {R.Stack, sizeof(R.Stack)}; ++ iovec Remote {reinterpret_cast(R.Gregs[FEXCore::X86State::REG_RSP]), sizeof(R.Stack)}; ++ process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0); ++ } ++ } ++ } ++ return true; ++ } ++ const uint32_t Idx = Count.fetch_add(1, std::memory_order_relaxed); ++ if (Records && Idx < MaxSamples) { ++ Records[Idx] = {ArchHelpers::Context::GetPc(UContext), ++ static_cast(static_cast(syscall(SYS_gettid))) | (Thread ? (Thread->CurrentFrame->State.rip << 32) : 0)}; ++ } ++ return true; ++ }, ++ true); ++ ++ if (External) { ++ return; ++ } ++ pthread_t T; ++ pthread_attr_t Attr; ++ pthread_attr_init(&Attr); ++ pthread_attr_setdetachstate(&Attr, PTHREAD_CREATE_DETACHED); ++ pthread_create(&T, &Attr, SamplerThread, reinterpret_cast(static_cast(Hz | (AllThreads ? 0x10000 : 0)))); ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h +new file mode 100644 +index 000000000..b6b433eca +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h +@@ -0,0 +1,13 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++ ++namespace FEXCore::Core { ++struct InternalThreadState; ++} ++namespace FEX::HLE { ++class SignalDelegator; ++ ++void StartSamplingProfiler(FEX::HLE::SignalDelegator* Signals, uint32_t Hz, bool AllThreads, bool External = false); ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp +index a7dcd128d..830ae3721 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp +@@ -119,6 +119,16 @@ $end_info$ + // TRACE_syscall + // - ptrace unsupported + ++#ifndef PR_SET_SYSCALL_USER_DISPATCH ++#define PR_SET_SYSCALL_USER_DISPATCH 59 ++#define PR_SYS_DISPATCH_OFF 0 ++#define PR_SYS_DISPATCH_ON 1 ++#endif ++#ifndef SYSCALL_DISPATCH_FILTER_ALLOW ++#define SYSCALL_DISPATCH_FILTER_ALLOW 0 ++#define SYSCALL_DISPATCH_FILTER_BLOCK 1 ++#endif ++ + namespace FEX::HLE { + uint64_t SeccompEmulator::Handle(FEXCore::Core::CpuStateFrame* Frame, uint32_t Op, uint32_t flags, void* arg) { + // If seccomp isn't enabled then say so. +@@ -314,6 +324,60 @@ void SeccompEmulator::DeserializeFilters(FEXCore::Core::CpuStateFrame* Frame, in + close(FD); + } + ++void SeccompEmulator::QueueTrapSignal(FEX::HLE::ThreadStateObject* Thread, int Code, uint32_t Errno, uint64_t PostSyscallRIP, ++ uint64_t SyscallNumber, uint32_t Arch) { ++ siginfo_t Info { ++ .si_signo = SIGSYS, ++ .si_errno = static_cast(Errno), ++ .si_code = Code, ++ }; ++ ++ Info.si_call_addr = reinterpret_cast(PostSyscallRIP); ++ Info.si_syscall = SyscallNumber; ++ Info.si_arch = Arch; ++ ++ Thread->SeccompTrapRIP = PostSyscallRIP; ++ ++ SignalDelegation->PrepareForcedGuestSignal(Thread, SIGSYS); ++ SignalDelegation->QueueSignal(::getpid(), ::gettid(), SIGSYS, &Info, true); ++} ++ ++void SeccompEmulator::ForceExitSignal(FEX::HLE::ThreadStateObject* Thread, int Signal) { ++ uint64_t Mask = 1ULL << (Signal - 1); ++ SignalDelegation->GuestSigProcMask(Thread, SIG_UNBLOCK, &Mask, nullptr); ++ SignalDelegation->UninstallHostHandler(Signal); ++ FHU::Syscalls::tgkill(::getpid(), ::gettid(), Signal); ++} ++ ++SeccompEmulator::ExecuteFilterResult ++SeccompEmulator::ExecuteSyscallUserDispatch(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, uint64_t SyscallNumber) { ++ auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); ++ const auto& SUD = Thread->SyscallUserDispatch; ++ const uint64_t PostSyscallRIP = Thread->Thread->CTX->RestoreRIPFromHostPC(Frame->Thread, JITPC) + 2; ++ ++ if (PostSyscallRIP - SUD.Offset < SUD.Length) { ++ return {false, 0}; ++ } ++ ++ if (SUD.Selector) { ++ uint8_t State {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&State, reinterpret_cast(SUD.Selector), sizeof(State))) { ++ ForceExitSignal(Thread, SIGSEGV); ++ return {true, SyscallNumber}; ++ } ++ if (State == SYSCALL_DISPATCH_FILTER_ALLOW) { ++ return {false, 0}; ++ } ++ if (State != SYSCALL_DISPATCH_FILTER_BLOCK) { ++ ForceExitSignal(Thread, SIGSYS); ++ return {true, SyscallNumber}; ++ } ++ } ++ ++ QueueTrapSignal(Thread, 2 , 0, PostSyscallRIP, SyscallNumber, Is64BitMode() ? AUDIT_ARCH_X86_64 : AUDIT_ARCH_I386); ++ return {true, SyscallNumber}; ++} ++ + SeccompEmulator::ExecuteFilterResult + SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, FEX::HLE::SyscallArguments* Args) { + if (!HasFilter(Frame)) { +@@ -330,6 +394,8 @@ SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JIT + ::prctl(PR_SET_NO_NEW_PRIVS, 1L, 0, 0, 0); + } + ++ const uint64_t PostSyscallRIP = RIP + 2; ++ + const auto Arch = Is64BitMode() ? AUDIT_ARCH_X86_64 : AUDIT_ARCH_I386; + bool ShouldLog {}; + uint32_t SeccompResult {}; +@@ -425,18 +491,9 @@ SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JIT + break; + } + case SECCOMP_RET_TRAP: { +- siginfo_t Info { +- .si_signo = SIGSYS, +- .si_errno = static_cast(DataMasked), +- .si_code = 1, // SYS_SECCOMP +- }; +- +- Info.si_call_addr = reinterpret_cast(RIP); +- Info.si_syscall = Args->Argument[0]; +- Info.si_arch = Arch; ++ QueueTrapSignal(Thread, 1 , DataMasked, PostSyscallRIP, Args->Argument[0], Arch); + +- SignalDelegation->QueueSignal(::getpid(), ::gettid(), SIGSYS, &Info, true); +- break; ++ return {true, Args->Argument[0]}; + } + case SECCOMP_RET_ERRNO: { + // errno return is clamped. +@@ -671,7 +728,8 @@ uint64_t SeccompEmulator::SetModeFilter(FEXCore::Core::CpuStateFrame* Frame, uin + return -EINVAL; + } + +- if (!prog) { ++ sock_fprog UserProg; ++ if (FaultSafeUserMemAccess::CopyFromUser(&UserProg, prog, sizeof(UserProg))) { + return -EFAULT; + } + +@@ -680,12 +738,22 @@ uint64_t SeccompEmulator::SetModeFilter(FEXCore::Core::CpuStateFrame* Frame, uin + return -EACCES; + } + +- if (prog->len > BPF_MAXINSNS || prog->len == 0) { ++ if (UserProg.len > BPF_MAXINSNS || UserProg.len == 0) { + // operation specified SECCOMP_SET_MODE_FILTER, but the filter program pointed to by args was not valid or the length of the filter + // program was zero or exceeded BPF_MAXINSNS (4096) instructions. + return -EINVAL; + } + ++ fextl::vector Instructions(UserProg.len); ++ if (FaultSafeUserMemAccess::CopyFromUser(Instructions.data(), UserProg.filter, UserProg.len * sizeof(sock_filter))) { ++ return -EFAULT; ++ } ++ const sock_fprog LocalProg { ++ .len = UserProg.len, ++ .filter = Instructions.data(), ++ }; ++ prog = &LocalProg; ++ + // Don't interrupt me while I'm jitting. + auto lk = FEXCore::MaskSignalsAndLockMutex(FilterMutex); + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h +index a4c7b70e0..31b489216 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h +@@ -61,6 +61,8 @@ public: + }; + ExecuteFilterResult ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, FEX::HLE::SyscallArguments* Args); + ++ ExecuteFilterResult ExecuteSyscallUserDispatch(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, uint64_t SyscallNumber); ++ + bool HasFilter(FEXCore::Core::CpuStateFrame* Frame) const { + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); + return !Thread->Filters.empty(); +@@ -101,6 +103,9 @@ private: + const sock_fprog* GetStrictModeFilter() const; + void KillProcess(ThreadStateObject* Thread); + void KillThread(FEXCore::Core::CpuStateFrame* Thread); ++ void QueueTrapSignal(FEX::HLE::ThreadStateObject* Thread, int Code, uint32_t Errno, uint64_t PostSyscallRIP, uint64_t SyscallNumber, ++ uint32_t Arch); ++ void ForceExitSignal(FEX::HLE::ThreadStateObject* Thread, int Signal); + + // Multiple filter instruction count penalty. + // When multiple filters are installed there is a penalty per filter counted towards the maximum number of instructions. +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index e8e04b056..87b890e19 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -8,6 +8,8 @@ $end_info$ + + #include "LinuxSyscalls/SignalDelegator.h" + #include "LinuxSyscalls/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/SignalTrace.h" + + #include + #include +@@ -219,6 +221,10 @@ ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore:: + Context->UContextLocation = 0; + Context->SigInfoLocation = 0; + Context->InSyscallInfo = 0; ++ Context->ClearedSyscallInfo = 0; ++ Context->GuestSignalMask = 0; ++ Context->SeccompTrapRIP = 0; ++ Context->SavedJITStackSP = 0; + + // Store fault to top status and then reset it + Context->FaultToTopAndGeneratedException = Thread->CurrentFrame->SynchronousFaultData.FaultToTopAndGeneratedException; +@@ -227,6 +233,8 @@ ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore:: + return Context; + } + ++static void CheckForPendingSignals(const FEX::HLE::ThreadStateObject* Thread); ++ + void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thread, void* ucontext, RestoreType Type) { + uint64_t OldSP {}; + if (Type == RestoreType::TYPE_PAUSE) [[unlikely]] { +@@ -315,8 +323,36 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + uintptr_t NewSP = OldSP; + auto Context = reinterpret_cast(NewSP); + ++ if (Type != RestoreType::TYPE_PAUSE) { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ for (size_t i = ThreadObject->TrapSignalFrameCount; i > 0; --i) { ++ if (ThreadObject->TrapSignalFrames[i - 1].ContextBackup == NewSP) { ++ ThreadObject->TrapSignalFrameCount = i - 1; ++ break; ++ } ++ } ++ } ++ + // Restore host state + ArchHelpers::Context::RestoreContext(ucontext, Context); ++ Thread->CurrentFrame->InSyscallInfo = ArchHelpers::Context::SavedSyscallInfo(Context); ++ ++ { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::SigReturn, 0, Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RSP], ++ Context->GuestSignalMask); ++ if (Type != RestoreType::TYPE_PAUSE && SignalMaskFix()) { ++ uint64_t NewGuestMask = Context->GuestSignalMask; ++ if (Is64BitMode && Context->UContextLocation) { ++ auto* GuestUContext = reinterpret_cast(Context->UContextLocation); ++ NewGuestMask = GuestUContext->uc_sigmask.val[0] & ~((1ULL << (SIGKILL - 1)) | (1ULL << (SIGSTOP - 1))); ++ } ++ ThreadObject->SignalInfo.CurrentSignalMask.Val = NewGuestMask; ++ CheckForPendingSignals(ThreadObject); ++ } ++ } ++ ++ FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->JITStackSP = Context->SavedJITStackSP; + + // Reset the guest state + memcpy(&Thread->CurrentFrame->State, &Context->GuestState, sizeof(FEXCore::Core::CPUState)); +@@ -327,7 +363,7 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + // XXX: Unsupported since it needs state reconstruction + // If we are in the JIT then SRA might need to be restored to values from the context + // We can't currently support this since it might result in tearing without real state reconstruction +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ Frame->InSyscallInfo = ArchHelpers::Context::SavedSyscallInfo(Context); + + if (Is64BitMode) { + RestoreFrame_x64(Thread, Context, Frame, ucontext); +@@ -343,7 +379,36 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + + bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext, + GuestSigAction* GuestAction, stack_t* GuestStack) { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ ++ const int SigSysCode = Signal == SIGSYS ? static_cast(info)->si_code : 0; ++ const bool IsTrapSignal = (SigSysCode == 1 || SigSysCode == 2 ) && ThreadObject->SeccompTrapRIP && ++ !CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext)); ++ if (IsTrapSignal) { ++ const uint64_t GuestRSP = Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RSP]; ++ while (ThreadObject->TrapSignalFrameCount) { ++ const auto& Abandoned = ThreadObject->TrapSignalFrames[ThreadObject->TrapSignalFrameCount - 1]; ++ if (GuestRSP <= Abandoned.GuestFrame || GuestRSP < Abandoned.GuestRSP) { ++ break; ++ } ++ ThreadObject->JITStackSP = Abandoned.JITStackSP; ++ --ThreadObject->TrapSignalFrameCount; ++ --Thread->CurrentFrame->SignalHandlerRefCounter; ++ } ++ const uint64_t Level = ThreadObject->JITStackSP ? ThreadObject->JITStackSP : Thread->CurrentFrame->ReturningStackLocation; ++ if (Level > ArchHelpers::Context::GetSp(ucontext)) { ++ ArchHelpers::Context::SetSp(ucontext, Level); ++ } ++ } ++ + auto ContextBackup = StoreThreadState(Thread, Signal, ucontext); ++ ContextBackup->GuestSignalMask = ThreadObject->SignalInfo.CurrentSignalMask.Val; ++ ++ if (SigSysCode == 1 || SigSysCode == 2 ) { ++ ContextBackup->SeccompTrapRIP = ThreadObject->SeccompTrapRIP; ++ ThreadObject->SeccompTrapRIP = 0; ++ } ++ ContextBackup->SavedJITStackSP = ThreadObject->JITStackSP; + + auto Frame = Thread->CurrentFrame; + auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; +@@ -382,8 +447,13 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo; + Thread->CurrentFrame->InSyscallInfo = 0; + } else { +- ContextBackup->InSyscallInfo = Frame->InSyscallInfo; +- Frame->InSyscallInfo = 0; ++ ThreadObject->JITStackSP = ArchHelpers::Context::GetSp(ucontext); ++ ++ if (Thread->CurrentFrame->InSyscallInfo != 0) { ++ ContextBackup->ClearedSyscallInfo = Thread->CurrentFrame->InSyscallInfo; ++ ContextBackup->Flags |= ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_SYSCALLINFO_CLEARED; ++ Thread->CurrentFrame->InSyscallInfo = 0; ++ } + + if (!IsAddressInDispatcher(OldPC)) { + // This is likely to cause issues but in some cases it isn't fatal +@@ -462,6 +532,14 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + + if (Is64BitMode) { + NewGuestSP = SetupFrame_x64(Thread, ContextBackup, Frame, Signal, HostSigInfo, ucontext, GuestAction, GuestStack, NewGuestSP, eflags); ++ if (IsTrapSignal && ThreadObject->TrapSignalFrameCount < ThreadObject->MaxTrapSignalFrames) { ++ ThreadObject->TrapSignalFrames[ThreadObject->TrapSignalFrameCount++] = { ++ .GuestFrame = NewGuestSP, ++ .GuestRSP = OldGuestSP, ++ .JITStackSP = ContextBackup->SavedJITStackSP, ++ .ContextBackup = reinterpret_cast(ContextBackup), ++ }; ++ } + } else { + const bool SigInfoFrame = (GuestAction->sa_flags & SA_SIGINFO) == SA_SIGINFO; + if (SigInfoFrame) { +@@ -483,8 +561,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + // This way signal handlers always go back to their original operating mode. + // Doesn't matter for 32-bit processes as they can only be 32-bit, but does + // matter for 64-bit processes as they could have potentially installed a 32-bit code segment. +- Frame->State.cs_idx = FEXCore::Core::CPUState::DEFAULT_USER_CS << 3; +- Frame->State.ss_idx = 0; ++ Frame->State.cs_idx = Is64BitMode ? FEXCore::Core::CPUState::DEFAULT_USER_CS_SEL : FEXCore::Core::CPUState::DEFAULT_USER32_CS_SEL; ++ Frame->State.ss_idx = FEXCore::Core::CPUState::DEFAULT_USER_DS_SEL; + Frame->State.cs_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.cs_idx)); + Frame->State.ss_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.ss_idx)); + +@@ -690,7 +768,7 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* + auto SigInfo = *static_cast(Info); + + if (FaultSafeUserMemAccess::TryHandleSafeFault(Signal, SigInfo, UContext)) { +- ERROR_AND_DIE_FMT("Received invalid data to syscall. Crashing now!"); ++ return true; + } + + #ifdef ARCHITECTURE_arm64 +@@ -714,10 +792,21 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* + + void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObject, int Signal, void* Info, void* UContext) { + auto Thread = ThreadObject->Thread; ++ ++ if (PtraceEmu::TryGuestSignalStop(Thread->CurrentFrame, Signal)) { ++ Thread->CurrentFrame->SynchronousFaultData.FaultToTopAndGeneratedException = false; ++ ArchHelpers::Context::SetPc(UContext, Config.AbsoluteLoopTopAddressFillSRA); ++ ArchHelpers::Context::SetFillSRASingleInst(UContext, false); ++ ArchHelpers::Context::SetState(UContext, reinterpret_cast(Thread->CurrentFrame)); ++ return; ++ } ++ + ucontext_t* _context = (ucontext_t*)UContext; + auto SigInfo = *static_cast(Info); + + auto MustDeferSignal = (Thread->CurrentFrame->State.DeferredSignalRefCount.Load() != 0); ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::HostArrive, Signal, ThreadObject->SignalInfo.CurrentSignalMask.Val, ++ (static_cast(MustDeferSignal) << 32) | static_cast(SigInfo.si_code)); + if (Signal == SIGSEGV && SigInfo.si_code == SEGV_ACCERR && SigInfo.si_addr == reinterpret_cast(&Thread->InterruptFaultPage)) { + if (!MustDeferSignal) { + // We just reached the end of the outermost signal-deferring section and faulted to check for pending signals. +@@ -781,6 +870,8 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec + // This allows us to maintain the expected signal mask through the guest signal handling and then all the way back again + sigmask_val[0] = GetNewSigMask(Signal); + ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Deferred, Signal, 0, 0); ++ + // Now update the faulting page permissions so it will fault on write. + mprotect(reinterpret_cast(&Thread->InterruptFaultPage), sizeof(Thread->InterruptFaultPage), PROT_NONE); + +@@ -793,6 +884,7 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec + // This signal is masked, must defer until the guest updates the signal mask. + // Add it to the pending signal list + ThreadObject->SignalInfo.PendingSignals |= 1ULL << (Signal - 1); ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Masked, Signal, ThreadObject->SignalInfo.CurrentSignalMask.Val, ThreadObject->SignalInfo.PendingSignals); + return; + } + +@@ -814,6 +906,21 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec + if (Handler.GuestHandler && + Handler.GuestHandler(Thread, Signal, &SigInfo, UContext, &Handler.GuestAction, &ThreadObject->SignalInfo.GuestAltStack)) { + uint64_t NewMask = GetNewSigMask(Signal); ++ if (SignalMaskFix()) { ++ uint64_t GuestNew = ThreadObject->SignalInfo.CurrentSignalMask.Val | Handler.GuestAction.sa_mask.Val; ++ if (!(Handler.GuestAction.sa_flags & SA_NODEFER)) { ++ GuestNew |= 1ULL << (Signal - 1); ++ } ++ GuestNew &= ~((1ULL << (SIGKILL - 1)) | (1ULL << (SIGSTOP - 1))); ++ ThreadObject->SignalInfo.CurrentSignalMask.Val = GuestNew; ++ NewMask = GuestNew; ++ for (size_t i = 0; i < MAX_SIGNALS; ++i) { ++ if (HostHandlers[i + 1].Required.load(std::memory_order_relaxed)) { ++ NewMask &= ~(1ULL << i); ++ } ++ } ++ } ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Delivered, Signal, reinterpret_cast(Handler.GuestAction.sigaction_handler.sigaction), NewMask); + + // Update our host signal mask so we don't hit race conditions with signals + // This allows us to maintain the expected signal mask through the guest signal handling and then all the way back again +@@ -961,6 +1068,30 @@ void SignalDelegator::UninstallHostHandler(int Signal) { + ::syscall(SYS_rt_sigaction, Signal, &SignalHandler.OldAction, nullptr, 8); + } + ++void SignalDelegator::ForceGuestSigSegv(uint64_t BadSP) { ++ static std::atomic Logged {false}; ++ if (!Logged.exchange(true, std::memory_order_relaxed)) { ++ LogMan::Msg::EFmt("Cannot write the guest signal frame at stack pointer 0x{:x}; forcing SIGSEGV " ++ "(Linux force_sigsegv). The guest stack pointer is not a live, writable mapping.", ++ BadSP); ++ } ++ ++ SignalHandler& Handler = HostHandlers[SIGSEGV]; ++ Handler.GuestAction.sigaction_handler.handler = SIG_DFL; ++ Handler.OldAction.handler = SIG_DFL; ++ ::signal(SIGSEGV, SIG_DFL); ++ ++ CTX->FlushAndCloseCodeMap(); ++ FEX::HLE::_SyscallHandler->TM.CleanupForExit(); ++ ++ uint64_t SegvMask = 1ULL << (SIGSEGV - 1); ++ ::syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &SegvMask, nullptr, 8); ++ ::raise(SIGSEGV); ++ ++ ::syscall(SYS_exit, 128 + SIGSEGV); ++ FEX_UNREACHABLE; ++} ++ + void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* info, bool IgnoreMask) { + bool WasIgnored {}; + bool WasMasked {}; +@@ -995,11 +1126,34 @@ void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* + } + } + ++void SignalDelegator::PrepareForcedGuestSignal(FEX::HLE::ThreadStateObject* Thread, int Signal) { ++ const uint64_t SignalMask = 1ULL << (Signal - 1); ++ const bool Blocked = Thread->SignalInfo.CurrentSignalMask.Val & SignalMask; ++ ++ GuestSigAction Action {}; ++ RegisterGuestSignalHandler(Signal, nullptr, &Action); ++ const bool Ignored = Action.sigaction_handler.handler == SIG_IGN; ++ ++ if (!Blocked && !Ignored) { ++ return; ++ } ++ ++ Action.sigaction_handler.handler = SIG_DFL; ++ RegisterGuestSignalHandler(Signal, &Action, nullptr); ++ if (Blocked) { ++ GuestSigProcMask(Thread, SIG_UNBLOCK, &SignalMask, nullptr); ++ } ++} ++ + SignalDelegator::SignalDelegator(FEXCore::Context::Context* _CTX, const std::string_view ApplicationName, bool SupportsAVX, bool SupportsSVE256) + : CTX {_CTX} + , ApplicationName {ApplicationName} + , SupportsAVX {SupportsAVX} + , SupportsSVE256 {SupportsSVE256} { ++ if (SignalTrace()) { ++ SigTrace::Init(); ++ } ++ + // Signal zero isn't real + HostHandlers[0].Installed = true; + +@@ -1162,23 +1316,36 @@ void SignalDelegator::RegisterTLSState(FEX::HLE::ThreadStateObject* Thread) { + } + } + +-void SignalDelegator::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) { +- FEXCore::Allocator::munmap(Thread->SignalInfo.AltStackPtr, SIGSTKSZ * 16); +- +- Thread->SignalInfo.AltStackPtr = nullptr; +- ++void SignalDelegator::ReleaseAltStack(FEX::HLE::ThreadStateObject* Thread) { + stack_t altstack {}; + altstack.ss_flags = SS_DISABLE; +- +- // Uninstall the alt stack + const int Result = sigaltstack(&altstack, nullptr); + if (Result == -1) { + LogMan::Msg::EFmt("Failed to uninstall alternative signal stack {}", strerror(errno)); + } + ++ FEXCore::Allocator::munmap(Thread->SignalInfo.AltStackPtr, SIGSTKSZ * 16); ++ Thread->SignalInfo.AltStackPtr = nullptr; ++ Thread->SignalInfo.AltStackReleaseDeferred = false; ++} ++ ++void SignalDelegator::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) { ++ stack_t Current {}; ++ if (sigaltstack(nullptr, &Current) == 0 && (Current.ss_flags & SS_ONSTACK)) { ++ Thread->SignalInfo.AltStackReleaseDeferred = true; ++ } else { ++ ReleaseAltStack(Thread); ++ } ++ + FEXCore::Allocator::UninstallTLSData(Thread->Thread); + } + ++void SignalDelegator::ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread) { ++ if (Thread->SignalInfo.AltStackReleaseDeferred) { ++ ReleaseAltStack(Thread); ++ } ++} ++ + void SignalDelegator::FrontendRegisterHostSignalHandler(int Signal, bool Required) { + // Linux signal handlers are per-process rather than per thread + // Multiple threads could be calling in to this +@@ -1321,6 +1488,7 @@ static void CheckForPendingSignals(const FEX::HLE::ThreadStateObject* Thread) { + if (PendingSignals != 0) { + for (int i = 0; i < 64; ++i) { + if (PendingSignals & (1ULL << i)) { ++ SigTrace::Log(Thread->ThreadInfo.TID, SigTrace::Reraise, i + 1, Thread->SignalInfo.CurrentSignalMask.Val, Thread->SignalInfo.PendingSignals); + FHU::Syscalls::tgkill(Thread->ThreadInfo.PID, Thread->ThreadInfo.TID, i + 1); + // We might not even return here which is spooky + } +@@ -1361,6 +1529,9 @@ uint64_t SignalDelegator::GuestSigProcMask(FEX::HLE::ThreadStateObject* Thread, + } + + ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &HostMask, nullptr, 8); ++ if (Thread->Thread->CurrentFrame->SignalHandlerRefCounter != 0) { ++ SigTrace::Log(Thread->ThreadInfo.TID, SigTrace::ProcMask, how, *set, Thread->SignalInfo.CurrentSignalMask.Val); ++ } + } + + if (oldset) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +index 43898e700..0d5b5597d 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +@@ -65,6 +65,8 @@ public: + + void RegisterTLSState(FEX::HLE::ThreadStateObject* Thread); + void UninstallTLSState(FEX::HLE::ThreadStateObject* Thread); ++ void ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread); ++ void ReleaseAltStack(FEX::HLE::ThreadStateObject* Thread); + + /** + * @brief Registers a signal handler for the host to handle a signal +@@ -109,6 +111,10 @@ public: + void UninstallHostHandler(int Signal); + void QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* info, bool IgnoreMask); + ++ void PrepareForcedGuestSignal(FEX::HLE::ThreadStateObject* Thread, int Signal); ++ ++ [[noreturn]] void ForceGuestSigSegv(uint64_t BadSP); ++ + void SetVDSOSymbols() { + // Get symbols from VDSO. + VDSOPointers = FEX::VDSO::GetVDSOSymbols(); +@@ -187,6 +193,8 @@ private: + FEXCore::Context::Context* CTX; + + FEX_CONFIG_OPT(Is64BitMode, IS64BIT_MODE); ++ FEX_CONFIG_OPT(SignalMaskFix, SIGNALMASKFIX); ++ FEX_CONFIG_OPT(SignalTrace, SIGNALTRACE); + const fextl::string ApplicationName; + FEX_CONFIG_OPT(HalfBarrierTSOEnabled, HALFBARRIERTSOENABLED); + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +index 38dc524f1..d0bcdbecb 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -7,6 +7,7 @@ $end_info$ + */ + + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/Syscalls.h" + + #include + #include +@@ -14,11 +15,15 @@ $end_info$ + #include + #include + #include ++#include + ++#include + #include + #include + #include + #include ++#include ++#include + + namespace FEX::HLE { + constexpr uint32_t X86_SA_RESTORER = 0x04000000; +@@ -106,26 +111,42 @@ template + static void SetXStateInfo(T* xstate, bool is_avx_enabled) { + auto* fpstate = &xstate->fpstate; + +- fpstate->sw_reserved.magic1 = is_avx_enabled ? FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_1 : 0; +- fpstate->sw_reserved.extended_size = is_avx_enabled ? sizeof(T) : 0; ++ fpstate->sw_reserved.magic1 = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_1; + + fpstate->sw_reserved.xfeatures |= FEXCore::x86_64::fpx_sw_bytes::FEATURE_FP | FEXCore::x86_64::fpx_sw_bytes::FEATURE_SSE; + if (is_avx_enabled) { + fpstate->sw_reserved.xfeatures |= FEXCore::x86_64::fpx_sw_bytes::FEATURE_YMM; + } + +- fpstate->sw_reserved.xstate_size = fpstate->sw_reserved.extended_size; ++ if constexpr (std::is_same_v) { ++ if (!is_avx_enabled) { ++ fpstate->sw_reserved.xstate_size = sizeof(FEXCore::x86_64::_libc_fpstate); ++ fpstate->sw_reserved.extended_size = sizeof(FEXCore::x86_64::_libc_fpstate) + sizeof(uint32_t); ++ return; ++ } + +- if (is_avx_enabled) { +- xstate->xstate_hdr.xfeatures = 0; +- xstate->magic2.magic = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ const uint32_t UserSize = offsetof(FEXCore::x86_64::xstate, ymmh) + sizeof(FEXCore::x86_64::ymmh_state); ++ fpstate->sw_reserved.xstate_size = UserSize; ++ fpstate->sw_reserved.extended_size = UserSize + sizeof(uint32_t); ++ ++ xstate->xstate_hdr.xfeatures = fpstate->sw_reserved.xfeatures; ++ ++ *reinterpret_cast(reinterpret_cast(fpstate) + UserSize) = ++ FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ } else { ++ fpstate->sw_reserved.extended_size = is_avx_enabled ? sizeof(T) : 0; ++ fpstate->sw_reserved.xstate_size = fpstate->sw_reserved.extended_size; ++ if (is_avx_enabled) { ++ xstate->xstate_hdr.xfeatures = 0; ++ xstate->magic2.magic = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ } + } + } + + void SignalDelegator::ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext, + const uint64_t* GuestGPRs, size_t Count, uint64_t Mask) { + #ifdef ARCHITECTURE_arm64 +- const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF; ++ const uint32_t Spilled = ArchHelpers::Context::SavedSyscallInfo(Context) & 0xFFFF; + const bool AllSpilled = Spilled == 0xFFFF; + if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { + return; +@@ -153,14 +174,19 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa + auto* guest_uctx = reinterpret_cast(Context->UContextLocation); + [[maybe_unused]] auto* guest_siginfo = reinterpret_cast(Context->SigInfoLocation); + +- // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) { ++ CTX->SetFlagsFromCompactedEFLAGS(Thread, guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL]); ++ ++ if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException || ++ Context->SeccompTrapRIP) { + + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -176,9 +202,6 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa + Frame->State.cs_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.cs_idx)); + Frame->State.ss_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.ss_idx)); + +- // XXX: Full context setting +- CTX->SetFlagsFromCompactedEFLAGS(Thread, guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL]); +- + #define COPY_REG(x) Frame->State.gregs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x]; + COPY_REG(R8); + COPY_REG(R9); +@@ -256,12 +279,15 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + SigFrame_i32* guest_uctx = reinterpret_cast(Context->UContextLocation); + // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) { ++ if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException || Context->SeccompTrapRIP) { + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -345,13 +371,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + RTSigFrame_i32* guest_uctx = reinterpret_cast(Context->UContextLocation); + // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) { ++ if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException || ++ Context->SeccompTrapRIP) { + + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -431,9 +461,42 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th + } + } + ++static bool GuestFrameWritable(uint64_t Begin, uint64_t End) { ++ if (End < Begin) { ++ return false; ++ } ++ ++ auto& VMATracking = FEX::HLE::_SyscallHandler->VMATracking; ++ ++ constexpr uint64_t PageSize = 4096; ++ constexpr uint64_t MaxPages = 4096; ++ const uint64_t FirstPage = Begin & ~(PageSize - 1); ++ const uint64_t LastPage = End & ~(PageSize - 1); ++ ++ auto lk = FEXCore::MaskSignalsAndLockMutex(VMATracking.Mutex); ++ ++ for (uint64_t Page = FirstPage, PageCount = 0; Page <= LastPage; Page += PageSize, ++PageCount) { ++ if (PageCount >= MaxPages) { ++ return false; ++ } ++ ++ const auto Entry = VMATracking.FindVMAEntry(Page); ++ if (Entry == VMATracking.VMAs.end()) { ++ return false; ++ } ++ ++ if (!Entry->second.Prot.Writable || (Entry->first + Entry->second.Length) < (Page + PageSize)) { ++ return false; ++ } ++ } ++ ++ return true; ++} ++ + uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup, + FEXCore::Core::CpuStateFrame* Frame, int Signal, siginfo_t* HostSigInfo, void* ucontext, + GuestSigAction* GuestAction, stack_t* GuestStack, uint64_t NewGuestSP, const uint32_t eflags) { ++ const uint64_t RequestedGuestSP = NewGuestSP; + + // Back up past the redzone, which is 128bytes + // 32-bit doesn't have a redzone +@@ -475,6 +538,16 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + ContextBackup->UContextLocation = UContextLocation; + ContextBackup->SigInfoLocation = SigInfoLocation; + ++ const uint64_t UContextEnd = UContextLocation + sizeof(FEXCore::x86_64::ucontext_t); ++ const uint64_t FPStateEnd = ++ FPStateLocation + (SupportsAVX ? sizeof(FEXCore::x86_64::xstate) : sizeof(FEXCore::x86_64::_libc_fpstate)); ++ const uint64_t HostStackEnd = HostStackLocation + sizeof(uint64_t); ++ const uint64_t FrameEnd = std::max({UContextEnd, FPStateEnd, HostStackEnd}); ++ ++ if (!GuestFrameWritable(UContextLocation, FrameEnd)) { ++ ForceGuestSigSegv(RequestedGuestSP); ++ } ++ + FEXCore::x86_64::ucontext_t* guest_uctx = reinterpret_cast(UContextLocation); + siginfo_t* guest_siginfo = reinterpret_cast(SigInfoLocation); + // Store where the host context lives in the guest stack. +@@ -488,7 +561,8 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + auto* xstate = reinterpret_cast(FPStateLocation); + SetXStateInfo(xstate, SupportsAVX); + +- guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] = ContextBackup->OriginalRIP; ++ guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] = ++ ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL] = eflags; + // This stores the CS/GS/FS selectors. It ALSO stores the SS selector in the top 16 bits...For some reason. + // Despite the naming, the endianness is swapped from what you'd expect. +@@ -568,6 +642,9 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + guest_uctx->uc_stack.ss_sp = GuestStack->ss_sp; + guest_uctx->uc_stack.ss_size = GuestStack->ss_size; + ++ memset(guest_uctx->uc_sigmask.val, 0, sizeof(guest_uctx->uc_sigmask.val)); ++ guest_uctx->uc_sigmask.val[0] = ContextBackup->GuestSignalMask; ++ + // Apparently RAX is always set to zero in case of badly misbehaving C applications and variadics. + Frame->State.gregs[FEXCore::X86State::REG_RAX] = 0; + Frame->State.gregs[FEXCore::X86State::REG_RDI] = Signal; +@@ -643,7 +720,7 @@ uint64_t SignalDelegator::SetupFrame_ia32(FEXCore::Core::InternalThreadState* Th + guest_uctx->sc.err = ConvertSignalToError(ucontext, Signal, HostSigInfo); + } + +- guest_uctx->sc.ip = ContextBackup->OriginalRIP; ++ guest_uctx->sc.ip = ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->sc.flags = eflags; + guest_uctx->sc.sp_at_signal = 0; + +@@ -779,7 +856,8 @@ uint64_t SignalDelegator::SetupRTFrame_ia32(FEXCore::Core::InternalThreadState* + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_ERR] = ConvertSignalToError(ucontext, Signal, HostSigInfo); + } + +- guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] = ContextBackup->OriginalRIP; ++ guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] = ++ ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EFL] = eflags; + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_UESP] = Frame->State.gregs[FEXCore::X86State::REG_RSP]; + guest_uctx->uc.uc_mcontext.cr2 = 0; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp +new file mode 100644 +index 000000000..5db61d312 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp +@@ -0,0 +1,45 @@ ++// SPDX-License-Identifier: MIT ++#include "LinuxSyscalls/SignalTrace.h" ++ ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE::SigTrace { ++Rec* Buf = nullptr; ++std::atomic Idx {0}; ++ ++namespace { ++ std::string PathFor(pid_t Pid) { ++ return "/dev/shm/fex-" + std::to_string(Pid) + "-sigtrace"; ++ } ++} ++ ++void Init() { ++ if (Buf) { ++ return; ++ } ++ const std::string Path = PathFor(getpid()); ++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0) { ++ return; ++ } ++ if (ftruncate(fd, sizeof(Rec) * Recs) != 0) { ++ close(fd); ++ return; ++ } ++ void* Map = mmap(nullptr, sizeof(Rec) * Recs, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map != MAP_FAILED) { ++ Buf = static_cast(Map); ++ } ++} ++ ++void CleanupForExit() { ++ if (!Buf) { ++ return; ++ } ++ unlink(PathFor(getpid()).c_str()); ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h +new file mode 100644 +index 000000000..d1a1bb8a6 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h +@@ -0,0 +1,54 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++#include ++ ++namespace FEX::HLE::SigTrace { ++enum Event : uint16_t { ++ HostArrive = 1, ++ Masked = 2, ++ Deferred = 3, ++ Delivered = 4, ++ SigReturn = 5, ++ ProcMask = 6, ++ Reraise = 7, ++ Kill = 8, ++ Read16 = 9, ++ Write16 = 10, ++ EpollCtl = 11, ++}; ++ ++struct Rec { ++ uint64_t Tsc; ++ uint32_t Tid; ++ uint16_t Ev; ++ uint16_t Sig; ++ uint64_t A; ++ uint64_t B; ++}; ++ ++constexpr uint32_t Recs = 1u << 19; ++extern Rec* Buf; ++extern std::atomic Idx; ++ ++void Init(); ++ ++void CleanupForExit(); ++ ++inline bool Enabled() { ++ return Buf != nullptr; ++} ++ ++inline void Log(uint32_t Tid, uint16_t Ev, uint16_t Sig, uint64_t A, uint64_t B) { ++ if (!Buf) { ++ return; ++ } ++ uint64_t Tsc = 0; ++#if defined(__aarch64__) ++ asm volatile("mrs %0, cntvct_el0" : "=r"(Tsc)); ++#endif ++ Rec& R = Buf[Idx.fetch_add(1, std::memory_order_relaxed) & (Recs - 1)]; ++ R = {Tsc, Tid, Ev, Sig, A, B}; ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +index 4a77d8716..607ab0b97 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +@@ -15,6 +15,8 @@ $end_info$ + + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" + #include "LinuxSyscalls/Utils/Threads.h" +@@ -235,6 +237,11 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + return -ENOENT; + } + ++ if (PtraceEmu::IsAttached()) { ++ char Resolved[PATH_MAX]; ++ PtraceEmu::RecordExecPath(pathname[0] == '/' ? std::string(pathname) : std::string(realpath(Filename.c_str(), Resolved) ? Resolved : pathname)); ++ } ++ + int pid = getpid(); + + char PidSelfPath[50]; +@@ -332,7 +339,8 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + // - seccomp inheritance + // - FEXServer FD inheritance (unshare(CLONE_NEWNET)) + // - FD_CLOEXEC set on FD on anonymous file FD. +- const bool NeedsEnvpCopy = (IsFDExec && !(IsBinfmtCompatible || IsOtherELF)) || HasSeccomp || NeedsFDCopy || NeedsLoaderFD; ++ const bool NeedsExecveFD = (IsFDExec && !(IsBinfmtCompatible || IsOtherELF)) || NeedsFDCopy || NeedsLoaderFD; ++ const bool NeedsEnvpCopy = NeedsExecveFD || HasSeccomp; + + // We are trying to execute a shebang handled by a different architecture interpreter (e.g. /usr/bin/python from the host FS). + // In this case we just defer to the kernel. +@@ -348,7 +356,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + } + } + +- if (!IsBinfmtCompatible || NeedsFDCopy) { ++ if (NeedsExecveFD) { + if (NeedsFDCopy) { + // FEX needs the FD to live past execve when binfmt_misc isn't used, + // so duplicate the FD if FD_CLOEXEC is set, which removes the FD_CLOEXEC flag. +@@ -439,9 +447,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + + // It is valid to provide nullptr first argument. + if (*OldArgv) { +- // The direct fallback uses the executable path as argv[0]. An FD-backed load uses the +- // binfmt preserve-argv0 layout, so the caller-supplied argv[0] has to stay in the vector. +- if (!NeedsLoaderFD && !IsFDExec) { ++ if (!IsFDExec && !NeedsLoaderFD) { + ++OldArgv; + } + while (*OldArgv) { +@@ -814,6 +820,9 @@ SyscallHandler::SyscallHandler(FEXCore::Context::Context* _CTX, FEX::HLE::Signal + + SignalDelegation->RegisterHostSignalHandler(SIGSEGV, HandleSegfault, true); + ++ SignalDelegation->RegisterHostSignalHandler( ++ SIGTRAP, [](FEXCore::Core::InternalThreadState*, int, void*, void*) { return false; }, true); ++ + ExtendedMetaData = FEX::VolatileMetadata::ParseExtendedVolatileMetadata(FEXCore::Config::Get_EXTENDEDVOLATILEMETADATA()()); + } + +@@ -835,6 +844,14 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + Thread->Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RAX] = Result & Mask; + }; + ++ if (FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame)->SyscallUserDispatch.Enabled) [[unlikely]] { ++ const auto Result = SeccompEmulator.ExecuteSyscallUserDispatch(Frame, JITPC, GetArg(Is64Bit, Frame, 0)); ++ if (Result.EarlyReturn) { ++ SetResult(Frame, Result.Result); ++ return; ++ } ++ } ++ + if (SeccompEmulator.HasFilter(Frame)) { + FEX::HLE::SyscallArguments Args { + .Argument = +@@ -856,9 +873,23 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + } + } + +- const auto SyscallNum = GetArg(Is64Bit, Frame, 0); ++ auto SyscallNum = GetArg(Is64Bit, Frame, 0); ++ ++ uint64_t TraceArgs[6] {}; ++ const bool ReportStops = Is64Bit && PtraceEmu::WantsSyscallStops(); ++ if (ReportStops) { ++ for (unsigned i = 0; i < 6; ++i) { ++ TraceArgs[i] = GetArg(Is64Bit, Frame, i + 1); ++ } ++ SyscallNum = PtraceEmu::SyscallEntryStop(Frame, SyscallNum, TraceArgs); ++ } ++ + if (SyscallNum >= Definitions.size()) { +- SetResult(Frame, -ENOSYS); ++ uint64_t Result = -ENOSYS; ++ if (ReportStops && PtraceEmu::WantsSyscallStops()) { ++ Result = PtraceEmu::SyscallExitStop(Frame, SyscallNum, TraceArgs, Result); ++ } ++ SetResult(Frame, Result); + return; + } + +@@ -891,6 +922,23 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + #ifdef DEBUG_STRACE + Strace(Frame, Result); + #endif ++ ++ if constexpr (Is64Bit) { ++ PtraceEmu::ApplyPendingFlush(Frame); ++ if (Result == 0 && (SyscallNum == 56 || SyscallNum == 57 || SyscallNum == 58 || SyscallNum == 435)) { ++ constexpr uint64_t CloneVM = 0x100; ++ uint64_t Flags = 0; ++ if (SyscallNum == 56) { ++ Flags = GetArg(Is64Bit, Frame, 1); ++ } else if (SyscallNum == 435) { ++ Flags = *reinterpret_cast(GetArg(Is64Bit, Frame, 1)); ++ } ++ PtraceEmu::OnForkedChild((Flags & CloneVM) != 0); ++ } ++ if (ReportStops && PtraceEmu::WantsSyscallStops()) { ++ Result = PtraceEmu::SyscallExitStop(Frame, SyscallNum, TraceArgs, Result); ++ } ++ } + SetResult(Frame, Result); + } + +@@ -906,9 +954,12 @@ void SyscallHandler::HandleSyscall(FEXCore::Core::CpuStateFrame* Frame) { + HandleSyscallImpl(Frame, JITPC); + } + +- // Skip past the `syscall` or `int 0x80` instruction. Both of which are 2-bytes. + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); +- Thread->Thread->CurrentFrame->State.rip += 2; ++ if (const uint64_t NewRip = PtraceEmu::TakePendingRip()) { ++ Thread->Thread->CurrentFrame->State.rip = NewRip; ++ } else { ++ Thread->Thread->CurrentFrame->State.rip += 2; ++ } + } + + #ifdef DEBUG_STRACE +@@ -969,6 +1020,8 @@ void SyscallHandler::UnlockAfterFork(FEXCore::Core::InternalThreadState* LiveThr + // Code maps are closed upon fork in the child + FM.SetProtectedCodeMapFD(-1); + ++ FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(LiveThread)->SyscallUserDispatch = {}; ++ + VMATracking.Mutex.StealAndDropActiveLocks(); + CodeCachePatchingMutex.StealAndDropActiveLocks(); + } else { +@@ -985,10 +1038,16 @@ void SyscallHandler::UnlockAfterFork(FEXCore::Core::InternalThreadState* LiveThr + void SyscallHandler::RegisterTLSState(FEX::HLE::ThreadStateObject* Thread) { + SignalDelegation->RegisterTLSState(Thread); + ThunkHandler->RegisterTLSState(Thread); ++ FEX::HLE::ThreadManager::SetCurrentThreadObject(Thread); + } + + void SyscallHandler::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) { + SignalDelegation->UninstallTLSState(Thread); ++ FEX::HLE::ThreadManager::SetCurrentThreadObject(nullptr); ++} ++ ++void SyscallHandler::ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread) { ++ SignalDelegation->ReleaseDeferredTLSState(Thread); + } + + static bool isHEX(char c) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +index f55bce4fc..d643b4975 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +@@ -14,6 +14,7 @@ $end_info$ + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/ThreadManager.h" + #include "LinuxSyscalls/Seccomp/SeccompEmulator.h" ++#include "LinuxSyscalls/SMCHotPages.h" + #include "LinuxSyscalls/SyscallsVMATracking.h" + #include "ArchHelpers/MContext.h" + +@@ -203,6 +204,7 @@ public: + FEX_CONFIG_OPT(RootFSPath, ROOTFS); + FEX_CONFIG_OPT(Is64BitMode, IS64BIT_MODE); + FEX_CONFIG_OPT(SMCChecks, SMCCHECKS); ++ FEX_CONFIG_OPT(SMCHotPageFaults, SMCHOTPAGEFAULTS); + FEX_CONFIG_OPT(NeedsSeccomp, NEEDSSECCOMP); + FEX_CONFIG_OPT(EnableCodeCaching, ENABLECODECACHINGWIP); + FEX_CONFIG_OPT(EnableDiskCache, DISKCACHE); +@@ -287,8 +289,13 @@ public: + + ///// VMA (Virtual Memory Area) tracking ///// + static bool HandleSegfault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext); ++ static void InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, ++ const FEX::HLE::VMATracking::VMAEntry& Mapping); + void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length); ++ bool IsSMCHotPage(uint64_t Address) override; ++ ++ void PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThreadState* Thread, const void* Buf, size_t Length); + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + std::optional + LookupExecutableFileSection(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestAddr) final override; +@@ -304,6 +311,7 @@ public: + + void RegisterTLSState(FEX::HLE::ThreadStateObject* Thread); + void UninstallTLSState(FEX::HLE::ThreadStateObject* Thread); ++ void ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread); + + SourcecodeResolver* GetSourcecodeResolver() override { + return this; +@@ -363,6 +371,8 @@ private: + // std::mutex CodeCachePatchingMutex; + FEXCore::ForkableUniqueMutex CodeCachePatchingMutex; + ++ SMCHotPageTracker SMCHotPages; ++ + FEX::CodeLoader* LocalLoader {}; + bool NeedToCheckXID {true}; + +@@ -607,11 +617,13 @@ uint64_t GetDentsEmulation(int fd, T* dirp, uint32_t count); + namespace FaultSafeUserMemAccess { + // These are little helper functions for cases when FEX needs to copy data to or from the application in a robust fashion. + // CopyFromUser and CopyToUser are memcpy routines that expect to safely SIGSEGV when reading or writing application memory respectively. +- // Returns zero if the memcpy completed, or crashes with SIGABRT and a log message if it faults. + [[nodiscard]] + size_t CopyFromUser(void* Dest, const void* Src, size_t Size); + [[nodiscard]] + size_t CopyToUser(void* Dest, const void* Src, size_t Size); ++ ++ [[nodiscard]] ++ bool IsStringReadable(const char* Src); + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED && defined(ARCHITECTURE_arm64) + // These helpers just check if the user pointer is readable and writable. + // This is useful in an assert build that can be safely sprinkled through the syscall handler without overhead in release builds. +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp +index 9acf01ff5..1601de1ef 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp +@@ -38,6 +38,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(open, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, int flags, uint32_t mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + flags = FEX::HLE::RemapFromX86Flags(flags); + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Open(pathname, flags, mode); + SYSCALL_ERRNO(); +@@ -59,6 +62,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(access, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, int mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Access(pathname, mode); + SYSCALL_ERRNO(); + }); +@@ -80,22 +86,34 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(openat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfs, const char* pathname, int flags, uint32_t mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + flags = FEX::HLE::RemapFromX86Flags(flags); + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Openat(dirfs, pathname, flags, mode); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(readlinkat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, char* buf, size_t bufsiz) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Readlinkat(dirfd, pathname, buf, bufsiz); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(faccessat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, int mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.FAccessat(dirfd, pathname, mode); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(faccessat2, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, int mode, int flags) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.FAccessat2(dirfd, pathname, mode, flags); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp +index 64c9aae22..9eee296ec 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp +@@ -52,6 +52,9 @@ void RegisterFS(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(readlink, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, char* buf, size_t bufsiz) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Readlink(pathname, buf, bufsiz); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp +index 1b61282d3..f83006c0a 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp +@@ -6,6 +6,7 @@ $end_info$ + */ + + #include "LinuxSyscalls/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" + +@@ -34,9 +35,11 @@ using cap_user_header_t = void*; + using cap_user_data_t = void*; + + void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(uname, [](FEXCore::Core::CpuStateFrame* Frame, struct utsname* buf) -> uint64_t { ++ REGISTER_SYSCALL_IMPL(uname, [](FEXCore::Core::CpuStateFrame* Frame, struct utsname* ubuf) -> uint64_t { + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); + ++ struct utsname Out {}; ++ auto buf = &Out; + struct utsname Local {}; + if (::uname(&Local) == 0) { + memcpy(buf->nodename, Local.nodename, sizeof(Local.nodename)); +@@ -66,6 +69,9 @@ void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { + // Tell the guest that we are a 64bit kernel + strcpy(buf->machine, "x86_64"); + } ++ if (FaultSafeUserMemAccess::CopyToUser(ubuf, &Out, sizeof(Out))) { ++ return -EFAULT; ++ } + return 0; + }); + +@@ -97,13 +103,14 @@ void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { + ptrace, [](FEXCore::Core::CpuStateFrame* Frame, int /*enum __ptrace_request*/ request, pid_t pid, void* addr, void* data) -> uint64_t { + uint64_t Result {}; + ++ if (PtraceEmu::HandleRequest(request, pid, addr, data, &Result)) { ++ return Result; ++ } ++ + switch (request) { + case PTRACE_PEEKTEXT: + case PTRACE_PEEKDATA: +- case PTRACE_POKETEXT: +- case PTRACE_POKEDATA: + case PTRACE_ATTACH: +- case PTRACE_DETACH: + // Passthrough these requests. Allows Wine to run the Ubisoft launcher. + Result = ::syscall(SYSCALL_DEF(ptrace), request, pid, addr, data); + SYSCALL_ERRNO(); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 21816674e..602e17570 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -9,6 +9,13 @@ $end_info$ + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/SignalTrace.h" ++ ++#include ++#include ++#include ++#include + + #include + #include +@@ -252,8 +259,23 @@ uint64_t SyscallPathPassthrough5(FEXCore::Core::CpuStateFrame* Frame, uint64_t a + } + + static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(read, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, size_t count) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); ++ uint64_t Result = ::syscall(SYSCALL_DEF(read), fd, buf, count); ++ if (count == 16 && SigTrace::Enabled()) { ++ const int Errno = errno; ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Read16, fd, Result, Result == 16 ? *static_cast(buf) : (1ULL << 63) | Errno); ++ } ++ SYSCALL_ERRNO(); ++ }); ++ REGISTER_SYSCALL_IMPL(write, [](FEXCore::Core::CpuStateFrame* Frame, int fd, const void* buf, size_t count) -> uint64_t { ++ uint64_t Result = ::syscall(SYSCALL_DEF(write), fd, buf, count); ++ if (count == 16 && SigTrace::Enabled()) { ++ const int Errno = errno; ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Write16, fd, Result, Result == 16 ? *static_cast(buf) : (1ULL << 63) | Errno); ++ } ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(lseek, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_yield, SyscallPassthrough0); + REGISTER_SYSCALL_IMPL(msync, SyscallPassthrough3); +@@ -264,14 +286,26 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(socket, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(connect, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(sendto, SyscallPassthrough6); +- REGISTER_SYSCALL_IMPL(recvfrom, SyscallPassthrough6); ++ REGISTER_SYSCALL_IMPL(recvfrom, ++ [](FEXCore::Core::CpuStateFrame* Frame, int sockfd, void* buf, size_t len, int flags, struct sockaddr* src_addr, ++ socklen_t* addrlen) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, len); ++ uint64_t Result = ::syscall(SYSCALL_DEF(recvfrom), sockfd, buf, len, flags, src_addr, addrlen); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(shutdown, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(bind, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(listen, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(getsockname, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(getpeername, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(socketpair, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(kill, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(kill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t pid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, pid, 0); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(kill), pid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(semget, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(msgget, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(msgsnd, SyscallPassthrough4); +@@ -334,7 +368,13 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(fgetxattr, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL(flistxattr, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(fremovexattr, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(tkill, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(tkill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t tid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, tid, 0); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(tkill), tid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(sched_setaffinity, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_getaffinity, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(io_setup, SyscallPassthrough2); +@@ -344,7 +384,13 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(remap_file_pages, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL(timer_getoverrun, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(timer_delete, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(tgkill, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(tgkill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t tgid, pid_t tid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, tid, tgid); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(tgkill), tgid, tid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(mbind, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL(set_mempolicy, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(get_mempolicy, SyscallPassthrough5); +@@ -459,7 +505,11 @@ namespace x64 { + RegisterCommon(Handler); + REGISTER_SYSCALL_IMPL_X64(ftruncate, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X64(ioctl, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X64(pread_64, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(pread_64, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, size_t count, off_t offset) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); ++ uint64_t Result = ::syscall(SYSCALL_DEF(pread_64), fd, buf, count, offset); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL_X64(pwrite_64, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(readv, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(writev, SyscallPassthrough3); +@@ -473,7 +523,14 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL_X64(setsockopt, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPathPassthrough5); +- REGISTER_SYSCALL_IMPL_X64(wait4, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(wait4, [](FEXCore::Core::CpuStateFrame* Frame, pid_t pid, int* status, int options, struct rusage* ru) -> uint64_t { ++ uint64_t Result; ++ do { ++ Result = ::syscall(SYSCALL_DEF(wait4), pid, status, options, ru); ++ Result = Result == -1 ? -errno : Result; ++ } while (static_cast(Result) > 0 && PtraceEmu::FixupWaitStatus(static_cast(Result), status)); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL_X64(semop, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(getrlimit, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X64(getrusage, SyscallPassthrough2); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp +index 8723026ef..1956b0d52 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp +@@ -25,13 +25,27 @@ struct GuestSigAction; + namespace FEX::HLE { + void RegisterSignals(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(rt_sigprocmask, [](FEXCore::Core::CpuStateFrame* Frame, int how, const uint64_t* set, uint64_t* oldset) -> uint64_t { +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigProcMask(FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), +- how, set, oldset); ++ uint64_t NewSet; ++ uint64_t OldSet; ++ if (set && FaultSafeUserMemAccess::CopyFromUser(&NewSet, set, sizeof(NewSet))) { ++ return -EFAULT; ++ } ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigProcMask( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), how, set ? &NewSet : nullptr, oldset ? &OldSet : nullptr); ++ if (Result == 0 && oldset && FaultSafeUserMemAccess::CopyToUser(oldset, &OldSet, sizeof(OldSet))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL(rt_sigpending, [](FEXCore::Core::CpuStateFrame* Frame, uint64_t* set, size_t sigsetsize) -> uint64_t { +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigPending(FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), set, +- sigsetsize); ++ uint64_t Pending {}; ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigPending( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), &Pending, sigsetsize); ++ if (Result == 0 && FaultSafeUserMemAccess::CopyToUser(set, &Pending, std::min(sigsetsize, sizeof(Pending)))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL(rt_sigsuspend, [](FEXCore::Core::CpuStateFrame* Frame, uint64_t* unewset, size_t sigsetsize) -> uint64_t { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp +index 2c3edeef1..5ce7ee8bd 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp +@@ -27,7 +27,9 @@ struct CpuStateFrame; + + namespace FEX::HLE { + void RegisterStubs(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(restart_syscall, [](FEXCore::Core::CpuStateFrame* Frame) -> uint64_t { SYSCALL_STUB(restart_syscall); }); ++ REGISTER_SYSCALL_IMPL(restart_syscall, [](FEXCore::Core::CpuStateFrame* Frame) -> uint64_t { ++ return -EINTR; ++ }); + + REGISTER_SYSCALL_IMPL(rseq, [](FEXCore::Core::CpuStateFrame* Frame, struct rseq* rseq, uint32_t rseq_len, int flags, uint32_t sig) -> uint64_t { + // We don't support this +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp +index 068fee23e..5f4a60480 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp +@@ -8,6 +8,7 @@ $end_info$ + #include "CodeLoader.h" + + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/SignalTrace.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" + #include "LinuxSyscalls/x64/Syscalls.h" +@@ -43,6 +44,12 @@ $end_info$ + #include + #include + ++#ifndef PR_SET_SYSCALL_USER_DISPATCH ++#define PR_SET_SYSCALL_USER_DISPATCH 59 ++#define PR_SYS_DISPATCH_OFF 0 ++#define PR_SYS_DISPATCH_ON 1 ++#endif ++ + ARG_TO_STR(idtype_t, "%u") + + namespace FEX::HLE { +@@ -500,6 +507,30 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return FEX::HLE::_SyscallHandler->SeccompEmulator.Handle(Frame, Operation, 0, reinterpret_cast(arg3)); + } + case PR_GET_SECCOMP: return FEX::HLE::_SyscallHandler->SeccompEmulator.GetSeccomp(Frame); ++ case PR_SET_SYSCALL_USER_DISPATCH: { ++ auto& SUD = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame)->SyscallUserDispatch; ++ switch (arg2) { ++ case PR_SYS_DISPATCH_OFF: ++ if (arg3 || arg4 || arg5) { ++ return -EINVAL; ++ } ++ SUD = {}; ++ return 0; ++ case PR_SYS_DISPATCH_ON: ++ if (arg3 && arg3 + arg4 <= arg3) { ++ return -EINVAL; ++ } ++ if (arg5 && arg5 >= SyscallHandler::TASK_MAX_64BIT) { ++ return -EFAULT; ++ } ++ SUD.Offset = arg3; ++ SUD.Length = arg4; ++ SUD.Selector = arg5; ++ SUD.Enabled = true; ++ return 0; ++ default: return -EINVAL; ++ } ++ } + case PR_GET_AUXV: { + if (arg4 || arg5) { + return -EINVAL; +@@ -532,6 +563,7 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return -EPERM; + } + Frame->State.gs_cached = addr; ++ Frame->State.gs_idx = 0; + Result = 0; + break; + case 0x1002: // ARCH_SET_FS +@@ -540,22 +572,27 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return -EPERM; + } + Frame->State.fs_cached = addr; ++ Frame->State.fs_idx = 0; + Result = 0; + break; + case 0x1003: // ARCH_GET_FS +- *reinterpret_cast(addr) = Frame->State.fs_cached; +- Result = 0; ++ Result = FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(addr), &Frame->State.fs_cached, sizeof(uint64_t)) ? -EFAULT : 0; + break; + case 0x1004: // ARCH_GET_GS +- *reinterpret_cast(addr) = Frame->State.gs_cached; +- Result = 0; ++ Result = FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(addr), &Frame->State.gs_cached, sizeof(uint64_t)) ? -EFAULT : 0; + break; + case 0x3001: // ARCH_CET_STATUS + Result = -EINVAL; // We don't support CET, return EINVAL + break; + case 0x1011: // ARCH_GET_CPUID ++ if (!FEX::HLE::_SyscallHandler->TM.EnableCPUIDFaulting()) { ++ return 1; ++ } + return (Frame->State.CoreFlags & FEXCore::Core::CoreFlagsEnum::CPUID_ENABLED) == FEXCore::Core::CoreFlagsEnum::CPUID_ENABLED ? 1 : 0; + case 0x1012: // ARCH_SET_CPUID ++ if (!FEX::HLE::_SyscallHandler->TM.EnableCPUIDFaulting()) { ++ return -ENODEV; ++ } + if (addr == 0) { + // Disable CPUID (thus enabling CPUID faulting) + Frame->State.CoreFlags = Frame->State.CoreFlags & ~FEXCore::Core::CoreFlagsEnum::CPUID_ENABLED; +@@ -584,6 +621,7 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + // Save telemetry if we're exiting. + FEX::HLE::_SyscallHandler->GetSignalDelegator()->SaveTelemetry(); + FEX::HLE::_SyscallHandler->TM.CleanupForExit(); ++ FEX::HLE::SigTrace::CleanupForExit(); + + syscall(SYSCALL_DEF(exit_group), status); + // This will never be reached +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +index 5d6c850d8..f9e85a26f 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +@@ -42,6 +42,40 @@ static void HandleSegfaultForCodeCacheFinalization(FEXCore::Core::InternalThread + } + } + ++void SyscallHandler::InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, ++ const FEX::HLE::VMATracking::VMAEntry& Mapping) { ++ auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { ++ auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }; ++ ++ if (Mapping.Flags.Shared) { ++ LOGMAN_THROW_A_FMT(Mapping.Resource, "VMA tracking error"); ++ ++ auto Offset = FaultBase - EntryBase + Mapping.Offset; ++ ++ auto VMA = Mapping.Resource->FirstVMA; ++ LOGMAN_THROW_A_FMT(VMA, "VMA tracking error"); ++ ++ do { ++ if (VMA->Offset <= Offset && (VMA->Offset + VMA->Length) > Offset) { ++ auto FaultBaseMirrored = Offset - VMA->Offset + VMA->Base; ++ ++ if (VMA->Prot.Writable) { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); ++ } else { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE); ++ } ++ ++ _SyscallHandler->SMCHotPages.RecordFault(FaultBaseMirrored, _SyscallHandler->SMCHotPageFaults()); ++ } ++ } while ((VMA = VMA->ResourceNextVMA)); ++ } else { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); ++ _SyscallHandler->SMCHotPages.RecordFault(FaultBase, _SyscallHandler->SMCHotPageFaults()); ++ } ++} ++ + // Handles segfaults from: + // - call-ret shadow stack overflow + // - guest-side self-modifying code (SMC) +@@ -52,9 +86,11 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); + auto CallRetStackInfo = ThreadObject->GetCallRetStackInfo(); + if (FaultAddress >= CallRetStackInfo.AllocationBase && FaultAddress < CallRetStackInfo.AllocationEnd) { +- // Reset REG_CALLRET_SP to the default location to allow for underflows/overflows +- ArchHelpers::Context::SetArmReg(ucontext, 25, CallRetStackInfo.DefaultLocation); +- return true; ++ const uint64_t CallRetSP = ArchHelpers::Context::GetArmReg(ucontext, 25); ++ if (FaultAddress - (CallRetSP - 16) < 32) { ++ ArchHelpers::Context::SetArmReg(ucontext, 25, CallRetStackInfo.DefaultLocation); ++ return true; ++ } + } + + { +@@ -84,41 +120,16 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + + auto FaultBase = FEXCore::AlignDown(FaultAddress, FEXCore::Utils::FEX_PAGE_SIZE); +- +- auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { +- auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); +- LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); +- }; +- +- if (Entry->second.Flags.Shared) { +- LOGMAN_THROW_A_FMT(Entry->second.Resource, "VMA tracking error"); +- +- auto Offset = FaultBase - Entry->first + Entry->second.Offset; +- +- auto VMA = Entry->second.Resource->FirstVMA; +- LOGMAN_THROW_A_FMT(VMA, "VMA tracking error"); +- +- // Flush all mirrors, remap the page writable as needed +- do { +- if (VMA->Offset <= Offset && (VMA->Offset + VMA->Length) > Offset) { +- auto FaultBaseMirrored = Offset - VMA->Offset + VMA->Base; +- +- if (VMA->Prot.Writable) { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); +- } else { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE); +- } +- } +- } while ((VMA = VMA->ResourceNextVMA)); +- } else { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); +- } ++ InvalidateWrittenCodePage(Thread, FaultBase, Entry->first, Entry->second); + + FEXCORE_PROFILE_INSTANT_INCREMENT(Thread, AccumulatedSMCCount, 1); + ++ constexpr uint64_t MaxStoreSize = 64; ++ const uint64_t StoreWindowStart = FaultAddress > MaxStoreSize ? FaultAddress - MaxStoreSize : 0; ++ + auto CTX = Thread->CTX; + if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext)) && !CTX->IsCurrentBlockSingleInst(Thread) && +- CTX->IsAddressInCurrentBlock(Thread, FaultAddress & FEXCore::Utils::FEX_PAGE_MASK, FEXCore::Utils::FEX_PAGE_SIZE)) { ++ CTX->IsAddressInCurrentBlock(Thread, StoreWindowStart, 2 * MaxStoreSize)) { + // If we are not in a single-instruction block, and the SMC write address could intersect with the current block, + // reconstruct the context and repeat the faulting instruction as a single-instruction block so any SMC it performs + // is immediately picked up. +@@ -134,6 +145,48 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + } + ++void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThreadState* Thread, const void* Buf, size_t Length) { ++ if (SMCChecks != FEXCore::Config::CONFIG_SMC_MTRACK || Length == 0) [[likely]] { ++ return; ++ } ++ ++ const uint64_t Start = FEXCore::AlignDown(reinterpret_cast(Buf), FEXCore::Utils::FEX_PAGE_SIZE); ++ const uint64_t Last = reinterpret_cast(Buf) + Length - 1 < reinterpret_cast(Buf) ? ++ UINT64_MAX : ++ reinterpret_cast(Buf) + Length - 1; ++ const uint64_t End = FEXCore::AlignDown(Last, FEXCore::Utils::FEX_PAGE_SIZE) + (Last >= UINT64_MAX - FEXCore::Utils::FEX_PAGE_SIZE ? 0 : FEXCore::Utils::FEX_PAGE_SIZE); ++ ++ auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); ++ ++ auto Entry = VMATracking.VMAs.upper_bound(Start); ++ if (Entry != VMATracking.VMAs.begin() && std::prev(Entry)->first + std::prev(Entry)->second.Length > Start) { ++ --Entry; ++ } ++ ++ for (; Entry != VMATracking.VMAs.end() && Entry->first < End; ++Entry) { ++ const auto& Mapping = Entry->second; ++ if (!Mapping.Prot.Writable || !(Mapping.Prot.Executable || Mapping.Flags.Shared)) [[likely]] { ++ continue; ++ } ++ const uint64_t From = std::max(Start, Entry->first); ++ const uint64_t To = std::min(End, Entry->first + Mapping.Length); ++ if (Mapping.Flags.Shared) { ++ for (uint64_t Page = From; Page < To; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ InvalidateWrittenCodePage(Thread, Page, Entry->first, Mapping); ++ } ++ } else { ++ TM.InvalidateGuestCodeRange(Thread, From, To - From, [](uintptr_t Start, uintptr_t Length) { ++ auto rv = mprotect(reinterpret_cast(Start), Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }); ++ } ++ } ++} ++ ++bool SyscallHandler::IsSMCHotPage(uint64_t Address) { ++ return SMCHotPages.IsHot(Address); ++} ++ + void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) { + const auto Base = Start & FEXCore::Utils::FEX_PAGE_MASK; + const auto Top = FEXCore::AlignUp(Start + Length, FEXCore::Utils::FEX_PAGE_SIZE); +@@ -143,6 +196,18 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + return; + } + ++ for (auto Page = Base; Page < Top; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ if (SMCHotPages.IsHot(Page)) { ++ if (Page > Base) { ++ MarkGuestExecutableRange(Thread, Base, Page - Base); ++ } ++ if (Page + FEXCore::Utils::FEX_PAGE_SIZE < Top) { ++ MarkGuestExecutableRange(Thread, Page + FEXCore::Utils::FEX_PAGE_SIZE, Top - (Page + FEXCore::Utils::FEX_PAGE_SIZE)); ++ } ++ return; ++ } ++ } ++ + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); + + // Find the first mapping at or after the range ends, or ::end(). +@@ -407,16 +472,24 @@ uint64_t SyscallHandler::GuestMunmap(bool Is64Bit, FEXCore::Core::InternalThread + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto lk = FEXCore::GuardSignalDeferringSectionWithFallback(VMATracking.Mutex, Thread); + +- if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { ++ if (!Is64Bit) { + Result = Get32BitAllocator()->Munmap(addr, length); + if (FEX::HLE::HasSyscallError(Result)) { + return Result; + } + } else { ++ constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - FEXCore::Utils::FEX_PAGE_SIZE; ++ const uint64_t Addr = reinterpret_cast(addr); ++ if (Addr > X86_64TaskSizeMax || Size > X86_64TaskSizeMax - Addr || (length != 0 && Size == 0)) { ++ return -EINVAL; ++ } + Result = ::munmap(addr, length); + if (Result == -1) { + return -errno; + } ++ if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { ++ Get32BitAllocator()->TrackUnmapped(addr, length); ++ } + } + TrackMunmap(Thread, addr, length); + PendingResourceDeletion = VMATracking.HasPendingResourceDeletions(); +@@ -514,6 +587,21 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + + { + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); ++ ++ fextl::vector UnlockedCode; ++ constexpr uint64_t MaxUnlockedCodePages = 64; ++ const auto Base = reinterpret_cast(addr) & FEXCore::Utils::FEX_PAGE_MASK; ++ const auto Top = FEXCore::AlignUp(reinterpret_cast(addr) + len, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (SMCChecks == FEXCore::Config::CONFIG_SMC_MTRACK && SMCHotPageFaults() && (prot & PROT_WRITE) && (prot & PROT_EXEC) && ++ Top > Base && (Top - Base) / FEXCore::Utils::FEX_PAGE_SIZE <= MaxUnlockedCodePages) { ++ for (auto Page = Base; Page < Top; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ auto Entry = VMATracking.FindVMAEntry(Page); ++ if (Entry != VMATracking.VMAs.end() && Entry->second.Prot.Executable && !Entry->second.Prot.Writable) { ++ UnlockedCode.push_back(Page); ++ } ++ } ++ } ++ + Result = ::mprotect(addr, len, prot); + if (Result == -1) { + return -errno; +@@ -523,6 +611,10 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + if (prot & PROT_WRITE) { + ProtectWritableAliasOfCode(reinterpret_cast(addr), FEXCore::AlignUp(len, FEXCore::Utils::FEX_PAGE_SIZE)); + } ++ ++ for (auto Page : UnlockedCode) { ++ SMCHotPages.MarkHot(Page); ++ } + } + + InvalidateCodeRangeIfNecessary(Thread, reinterpret_cast(addr), len, false); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +index 8e7d466ed..2e59f2fb5 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +@@ -1,6 +1,7 @@ + // SPDX-License-Identifier: MIT + + #include "LinuxSyscalls/ThreadManager.h" ++#include "LinuxSyscalls/SamplingProfiler.h" + + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/SignalDelegator.h" +@@ -158,6 +159,16 @@ void ThreadManager::StatAlloc::UnlockAfterFork(FEXCore::Core::InternalThreadStat + ThreadObject->Thread->ThreadStats = AllocateSlot(ThreadObject->ThreadInfo.TID); + } + ++static thread_local FEX::HLE::ThreadStateObject* CurrentThreadObject {}; ++ ++FEX::HLE::ThreadStateObject* ThreadManager::GetCurrentThreadObject() { ++ return CurrentThreadObject; ++} ++ ++void ThreadManager::SetCurrentThreadObject(FEX::HLE::ThreadStateObject* Thread) { ++ CurrentThreadObject = Thread; ++} ++ + uint64_t ThreadManager::SetSignalMask(uint64_t Mask) { + ::syscall(SYSCALL_DEF(rt_sigprocmask), SIG_SETMASK, &Mask, &Mask, 8); + return Mask; +@@ -197,6 +208,16 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + Frame->State.callret_sp = ThreadStateObject->GetCallRetStackInfo().DefaultLocation; + + ThreadStateObject->Thread->FrontendPtr = ThreadStateObject; ++ ++ { ++ static std::atomic ThreadCount {0}; ++ FEX_CONFIG_OPT(ProfileSampleHz, PROFILESAMPLEHZ); ++ FEX_CONFIG_OPT(ProfileSampleAllThreads, PROFILESAMPLEALLTHREADS); ++ FEX_CONFIG_OPT(ProfileSampleMinThreads, PROFILESAMPLEMINTHREADS); ++ if (ProfileSampleHz() && ThreadCount.fetch_add(1) + 1 == std::max(ProfileSampleMinThreads(), 1)) { ++ StartSamplingProfiler(SignalDelegation, ProfileSampleHz(), ProfileSampleAllThreads(), ProfileSampleMinThreads() == 0); ++ } ++ } + if (ProfileStats()) { + ThreadStateObject->Thread->ThreadStats = Stat.AllocateSlot(ThreadStateObject->ThreadInfo.TID); + } +@@ -222,8 +243,8 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + } + } else { + // Without any thread data to inherit, setup the default gdt. +- // Default code segment indexes match the numbers that the Linux kernel uses. +- Frame->State.cs_idx = FEXCore::Core::CPUState::DEFAULT_USER_CS << 3; ++ Frame->State.cs_idx = ++ Is64BitMode() ? FEXCore::Core::CPUState::DEFAULT_USER_CS_SEL : FEXCore::Core::CPUState::DEFAULT_USER32_CS_SEL; + auto GDT = FEXCore::Core::CPUState::GetSegmentFromIndex(Frame->State, Frame->State.cs_idx); + FEXCore::Core::CPUState::SetGDTBase(GDT, 0); + FEXCore::Core::CPUState::SetGDTLimit(GDT, 0xF'FFFFU); +@@ -237,6 +258,14 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + GDT->L = 0; // L = Long Mode = 32-bit + GDT->D = 1; // D = Default Operand Size = 32-bit + } ++ ++ Frame->State.ss_idx = FEXCore::Core::CPUState::DEFAULT_USER_DS_SEL; ++ auto SSGDT = FEXCore::Core::CPUState::GetSegmentFromIndex(Frame->State, Frame->State.ss_idx); ++ FEXCore::Core::CPUState::SetGDTBase(SSGDT, 0); ++ FEXCore::Core::CPUState::SetGDTLimit(SSGDT, 0xF'FFFFU); ++ SSGDT->L = 0; ++ SSGDT->D = 1; ++ Frame->State.ss_cached = FEXCore::Core::CPUState::CalculateGDTBase(*SSGDT); + } + + if (InheritThread) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index 408cddf71..0a46703ca 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -15,6 +15,7 @@ $end_info$ + + #include + #include ++#include + #include + #include + #include +@@ -68,6 +69,7 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + SignalDelegator* Delegator {}; + + void* AltStackPtr {}; ++ bool AltStackReleaseDeferred {}; + stack_t GuestAltStack { + .ss_sp = nullptr, + .ss_flags = SS_DISABLE, // By default the guest alt stack is disabled +@@ -93,6 +95,27 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + fextl::vector Filters {}; + std::atomic PrctlSetPending {false}; + ++ uint64_t SeccompTrapRIP {}; ++ ++ struct { ++ uint64_t Offset; ++ uint64_t Length; ++ uint64_t Selector; ++ bool Enabled; ++ } SyscallUserDispatch {}; ++ ++ uint64_t JITStackSP {}; ++ ++ struct TrapSignalFrame { ++ uint64_t GuestFrame; ++ uint64_t GuestRSP; ++ uint64_t JITStackSP; ++ uint64_t ContextBackup; ++ }; ++ static constexpr size_t MaxTrapSignalFrames = 16; ++ TrapSignalFrame TrapSignalFrames[MaxTrapSignalFrames] {}; ++ size_t TrapSignalFrameCount {}; ++ + // personality emulation. + uint32_t persona {}; + +@@ -190,6 +213,11 @@ public: + return static_cast(Thread->FrontendPtr); + } + ++ static FEX::HLE::ThreadStateObject* GetCurrentThreadObject(); ++ static void SetCurrentThreadObject(FEX::HLE::ThreadStateObject* Thread); ++ ++ FEX_CONFIG_OPT(EnableCPUIDFaulting, ENABLECPUIDFAULTING); ++ + FEX::HLE::ThreadStateObject* CreateThread(const FEXCore::Core::CPUState* NewThreadState = nullptr, uint64_t ParentTID = 0, + FEX::HLE::ThreadStateObject* InheritThread = nullptr); + void TrackThread(FEX::HLE::ThreadStateObject* Thread) { +@@ -220,29 +248,38 @@ public: + } + + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* CallingThread, uint64_t Start, uint64_t Length) { ++ InvalidationStats Stats(CallingThread); + std::lock_guard lk(ThreadCreationMutex); + + // Potential deferred since Thread might not be valid. + // Thread object isn't valid very early in frontend's initialization. + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto CodeInvalidationlk = FEXCore::GuardSignalDeferringSectionWithFallback(CTX->GetCodeInvalidationMutex(), CallingThread); +- CTX->InvalidateCodeBuffersCodeRange(Start, Length); +- for (auto& Thread : Threads) { +- CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length); ++ const bool HadCode = CTX->InvalidateCodeBuffersCodeRange(Start, Length); ++ if (HadCode) { ++ for (auto& Thread : Threads) { ++ CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length, true); ++ } ++ } else { ++ CTX->InvalidateExecutableRangeCaches(); + } + } + + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* CallingThread, uint64_t Start, uint64_t Length, + FEXCore::Context::CodeRangeInvalidationFn after_callback) { ++ InvalidationStats Stats(CallingThread); + std::lock_guard lk(ThreadCreationMutex); + + // Potential deferred since Thread might not be valid. + // Thread object isn't valid very early in frontend's initialization. + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto CodeInvalidationlk = FEXCore::GuardSignalDeferringSectionWithFallback(CTX->GetCodeInvalidationMutex(), CallingThread); +- CTX->InvalidateCodeBuffersCodeRange(Start, Length); +- for (auto& Thread : Threads) { +- CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length); ++ if (CTX->InvalidateCodeBuffersCodeRange(Start, Length)) { ++ for (auto& Thread : Threads) { ++ CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length, true); ++ } ++ } else { ++ CTX->InvalidateExecutableRangeCaches(); + } + + // Callback while holding the locks. +@@ -254,6 +291,20 @@ public: + } + + private: ++ struct InvalidationStats { ++ explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread) ++ : Thread {Thread} ++ , Begin {Thread && Thread->ThreadStats ? FEXCore::SHMStats::GetCycleCounter() : 0} {} ++ ~InvalidationStats() { ++ if (Thread && Thread->ThreadStats) { ++ Thread->ThreadStats->AccumulatedInvalidationCount += 1; ++ Thread->ThreadStats->AccumulatedInvalidationTime += FEXCore::SHMStats::GetCycleCounter() - Begin; ++ } ++ } ++ FEXCore::Core::InternalThreadState* Thread; ++ uint64_t Begin; ++ }; ++ + StatAlloc Stat; + FEXCore::Context::Context* CTX; + FEX::HLE::SignalDelegator* SignalDelegation; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp +index 8b9c25948..3b37e4a3e 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp +@@ -347,6 +347,7 @@ namespace PThreads { + Thread->detach(); + + if (LongJumpExit) { ++ FEX::HLE::_SyscallHandler->ReleaseDeferredTLSState(ThreadObject); + // We have ownership of the thread object. Make sure to clean it up to prevent memory leaks. + FEX::HLE::_SyscallHandler->TM.DestroyThread(ThreadObject, true); + if (Status == 0) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp +index 361bfbec1..25b3b0742 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp +@@ -802,6 +802,7 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL_X32( + pread_64, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, uint32_t count, uint32_t offset_low, uint32_t offset_high) -> uint64_t { + uint64_t Offset = (uint64_t(offset_high) << 32) | offset_low; ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); + uint64_t Result = ::pread64(fd, buf, count, Offset); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp +index d1ab9cdf8..84c612940 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp +@@ -6,6 +6,7 @@ tags: LinuxSyscalls|syscalls-x86-64 + $end_info$ + */ + ++#include "LinuxSyscalls/SignalTrace.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Types.h" + #include "LinuxSyscalls/x64/Syscalls.h" +@@ -14,6 +15,7 @@ $end_info$ + #include + + #include ++#include + #include + #include + #include +@@ -50,6 +52,9 @@ void RegisterEpoll(FEX::HLE::SyscallHandler* Handler) { + EventPtr = &Event; + } + uint64_t Result = ::syscall(SYSCALL_DEF(epoll_ctl), epfd, op, fd, EventPtr); ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::EpollCtl, op, fd, (EventPtr ? EventPtr->events : 0) | (Result << 32)); ++ } + if (Result != -1 && event) { + FaultSafeUserMemAccess::VerifyIsWritable(event, sizeof(FEX::HLE::epoll_event_x86)); + *event = Event; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp +index 91b5a103d..4eab76a59 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp +@@ -63,14 +63,16 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL_X64(stat, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, FEX::HLE::x64::guest_stat* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(pathname); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(pathname, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Stat(pathname, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); +@@ -79,36 +81,41 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + struct stat host_stat; + uint64_t Result = ::fstat(fd, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL_X64(lstat, [](FEXCore::Core::CpuStateFrame* Frame, const char* path, FEX::HLE::x64::guest_stat* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(path); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(path, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(path)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Lstat(path, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL_X64( + newfstatat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, FEX::HLE::x64::guest_stat* buf, int flag) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(pathname); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(pathname, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.NewFSStatAt(dirfd, pathname, &host_stat, flag); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); +@@ -140,8 +147,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL_X64(statfs, [](FEXCore::Core::CpuStateFrame* Frame, const char* path, struct statfs* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(path); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(path, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(path)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Statfs(path, buf); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp +index 36726ece6..c7b39bb46 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp +@@ -25,10 +25,18 @@ void RegisterSignals(FEX::HLE::SyscallHandler* Handler) { + if (sigsetsize != 8) { + return -EINVAL; + } +- FaultSafeUserMemAccess::VerifyIsReadableOrNull(act, sizeof(GuestSigAction)); +- FaultSafeUserMemAccess::VerifyIsWritableOrNull(oldact, sizeof(GuestSigAction)); ++ GuestSigAction NewAct; ++ GuestSigAction OldAct; ++ if (act && FaultSafeUserMemAccess::CopyFromUser(&NewAct, act, sizeof(NewAct))) { ++ return -EFAULT; ++ } + +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSignalHandler(signum, act, oldact); ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSignalHandler(signum, act ? &NewAct : nullptr, ++ oldact ? &OldAct : nullptr); ++ if (Result == 0 && oldact && FaultSafeUserMemAccess::CopyToUser(oldact, &OldAct, sizeof(OldAct))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL_X64( +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp +index c25ff5b94..0ec2933bc 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp +@@ -233,6 +233,22 @@ enum Modify_ldt_func : int32_t { + LDT_WRITE = 0x11, + }; + ++static bool GatherStringArray(char* const* User, fextl::vector& Out) { ++ for (size_t i = 0;; ++i) { ++ const char* Str; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Str, &User[i], sizeof(Str))) { ++ return false; ++ } ++ Out.push_back(Str); ++ if (!Str) { ++ return true; ++ } ++ if (!FaultSafeUserMemAccess::IsStringReadable(Str)) { ++ return false; ++ } ++ } ++} ++ + void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL_X64(modify_ldt, [](FEXCore::Core::CpuStateFrame* Frame, int func, void* ptr, unsigned long bytecount) -> uint64_t { + switch (func) { +@@ -278,10 +294,17 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + })); + + REGISTER_SYSCALL_IMPL_X64(sigaltstack, [](FEXCore::Core::CpuStateFrame* Frame, const stack_t* ss, stack_t* old_ss) -> uint64_t { +- FaultSafeUserMemAccess::VerifyIsReadableOrNull(ss, sizeof(*ss)); +- FaultSafeUserMemAccess::VerifyIsWritableOrNull(old_ss, sizeof(*old_ss)); +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSigAltStack( +- FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), ss, old_ss); ++ stack_t NewStack; ++ stack_t OldStack; ++ if (ss && FaultSafeUserMemAccess::CopyFromUser(&NewStack, ss, sizeof(NewStack))) { ++ return -EFAULT; ++ } ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSigAltStack( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), ss ? &NewStack : nullptr, old_ss ? &OldStack : nullptr); ++ if (Result == 0 && old_ss && FaultSafeUserMemAccess::CopyToUser(old_ss, &OldStack, sizeof(OldStack))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + // launch a new process under fex +@@ -290,20 +313,9 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + fextl::vector Args; + fextl::vector Envp; + +- if (argv) { +- for (int i = 0; argv[i]; i++) { +- Args.push_back(argv[i]); +- } +- +- Args.push_back(nullptr); +- } +- +- if (envp) { +- for (int i = 0; envp[i]; i++) { +- Envp.push_back(envp[i]); +- } +- +- Envp.push_back(nullptr); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname) || (argv && !GatherStringArray(argv, Args)) || ++ (envp && !GatherStringArray(envp, Envp))) { ++ return -EFAULT; + } + + auto* const* ArgsPtr = argv ? const_cast(Args.data()) : nullptr; +@@ -319,20 +331,9 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + fextl::vector Args; + fextl::vector Envp; + +- if (argv) { +- for (int i = 0; argv[i]; i++) { +- Args.push_back(argv[i]); +- } +- +- Args.push_back(nullptr); +- } +- +- if (envp) { +- for (int i = 0; envp[i]; i++) { +- Envp.push_back(envp[i]); +- } +- +- Envp.push_back(nullptr); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname) || (argv && !GatherStringArray(argv, Args)) || ++ (envp && !GatherStringArray(envp, Envp))) { ++ return -EFAULT; + } + + FEX::HLE::ExecveAtArgs AtArgs { diff --git a/tools/fex/patches/0022-proc-maps-guest-only-on-small-address-space-hosts.patch b/tools/fex/patches/0022-proc-maps-guest-only-on-small-address-space-hosts.patch new file mode 100644 index 0000000000..0d62f092d4 --- /dev/null +++ b/tools/fex/patches/0022-proc-maps-guest-only-on-small-address-space-hosts.patch @@ -0,0 +1,132 @@ +From: maxjivi05 +Subject: [PATCH] List only guest mappings in /proc//maps on hosts below 47 address bits + +Builds on StonkGuy's /proc emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index eb12945e4..65b0521c9 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -17,7 +17,11 @@ $end_info$ + #include + #include + #include ++#include + #include ++#include ++#include ++#include + #include + #include + #include +@@ -25,9 +29,13 @@ $end_info$ + + #include + ++#include + #include + #include + #include ++#include ++#include ++#include + #include + #include + #include +@@ -609,6 +617,37 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx) + + EmulatedFDManager::~EmulatedFDManager() {} + ++static bool IsSelfProcPath(const char* Path) { ++ const char* P = Path + 6; ++ if (!isdigit(*P)) { ++ return true; ++ } ++ return strtol(P, nullptr, 10) == ::getpid(); ++} ++ ++static bool IsHostArchModule(const char* Path, fextl::unordered_map& Seen) { ++ auto Known = Seen.find(Path); ++ if (Known != Seen.end()) { ++ return Known->second; ++ } ++ bool Host = false; ++ int FD = ::open(Path, O_RDONLY | O_CLOEXEC); ++ if (FD >= 0) { ++ Elf64_Ehdr Header {}; ++ if (::pread(FD, &Header, sizeof(Header), 0) >= static_cast(offsetof(Elf64_Ehdr, e_version)) && ++ memcmp(Header.e_ident, ELFMAG, SELFMAG) == 0) { ++#if defined(__aarch64__) ++ Host = Header.e_machine == EM_AARCH64; ++#else ++ Host = Header.e_machine != EM_X86_64 && Header.e_machine != EM_386; ++#endif ++ } ++ ::close(FD); ++ } ++ Seen.emplace(Path, Host); ++ return Host; ++} ++ + static bool IsProcMapsPath(const char* Path) { + if (strncmp(Path, "/proc/", 6) != 0) { + return false; +@@ -661,14 +700,56 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, + ::close(HostFD); + + constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096; ++ const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47; ++ const bool Self = IsSelfProcPath(pathname); ++ fextl::vector> GuestRanges; ++ if (HostSharesGuestRange && Self && FEX::HLE::_SyscallHandler) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(FEX::HLE::_SyscallHandler->VMATracking.Mutex); ++ GuestRanges.reserve(FEX::HLE::_SyscallHandler->VMATracking.VMAs.size()); ++ for (const auto& [Base, VMA] : FEX::HLE::_SyscallHandler->VMATracking.VMAs) { ++ if (!GuestRanges.empty() && GuestRanges.back().second >= Base) { ++ GuestRanges.back().second = std::max(GuestRanges.back().second, Base + VMA.Length); ++ } else { ++ GuestRanges.emplace_back(Base, Base + VMA.Length); ++ } ++ } ++ } ++ auto IsGuestRange = [&GuestRanges](uint64_t Start, uint64_t End) { ++ auto It = std::upper_bound(GuestRanges.begin(), GuestRanges.end(), Start, ++ [](uint64_t Value, const std::pair& Range) { return Value < Range.first; }); ++ if (It != GuestRanges.begin() && std::prev(It)->second > Start) { ++ return true; ++ } ++ return It != GuestRanges.end() && It->first < End; ++ }; ++ fextl::unordered_map ModuleArch; + fextl::string Out; + Out.reserve(In.size()); + size_t Pos = 0; + while (Pos < In.size()) { + size_t Eol = In.find('\n', Pos); + const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1; +- const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16); +- if (Start < X86_64TaskSizeMax) { ++ char* Cursor {}; ++ const uint64_t Start = strtoull(In.c_str() + Pos, &Cursor, 16); ++ const uint64_t Stop = *Cursor == '-' ? strtoull(Cursor + 1, nullptr, 16) : Start; ++ bool Keep = Start < X86_64TaskSizeMax; ++ if (Keep && HostSharesGuestRange) { ++ if (Self) { ++ Keep = IsGuestRange(Start, Stop); ++ } else { ++ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol; ++ size_t Name = In.find_first_of("/[", Pos); ++ if (Name != fextl::string::npos && Name < LineEnd) { ++ fextl::string Path(In, Name, LineEnd - Name); ++ if (Path.starts_with("[anon:FEX")) { ++ Keep = false; ++ } else if (Path[0] == '/') { ++ Keep = !IsHostArchModule(Path.c_str(), ModuleArch); ++ } ++ } ++ } ++ } ++ if (Keep) { + Out.append(In, Pos, End - Pos); + } + Pos = End; diff --git a/tools/fex/patches/0023-proc-status-seccomp-of-calling-thread.patch b/tools/fex/patches/0023-proc-status-seccomp-of-calling-thread.patch new file mode 100644 index 0000000000..d0550e8db0 --- /dev/null +++ b/tools/fex/patches/0023-proc-status-seccomp-of-calling-thread.patch @@ -0,0 +1,53 @@ +From 597bfab6ff068e0f6c08f63d6940486446967b0d Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:21:23 -0500 +Subject: [PATCH] Report the calling thread's seccomp mode in /proc/self/status + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +--- + .../LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp | 6 +++++- + .../Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h | 10 ++++++++++ + 2 files changed, 15 insertions(+), 1 deletion(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index 65b0521c9..ce36b988b 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -797,7 +797,11 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd + Buf[Len] = '\0'; + + uint32_t SeccompMode = SECCOMP_MODE_DISABLED; +- if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) { ++ auto* Thread = FEX::HLE::_SyscallHandler ? FEX::HLE::_SyscallHandler->TM.FindThreadByTID(::gettid()) : nullptr; ++ if (!Thread) { ++ Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject(); ++ } ++ if (Thread) { + SeccompMode = Thread->SeccompMode; + } + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index 0a46703ca..9c5f9f1c2 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -290,6 +290,16 @@ public: + return &Threads; + } + ++ FEX::HLE::ThreadStateObject* FindThreadByTID(uint32_t TID) { ++ std::lock_guard lk(ThreadCreationMutex); ++ for (auto* Thread : Threads) { ++ if (Thread->ThreadInfo.TID == TID) { ++ return Thread; ++ } ++ } ++ return nullptr; ++ } ++ + private: + struct InvalidationStats { + explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread) +-- +2.43.0 + diff --git a/tools/fex/patches/0024-read-host-status-directly.patch b/tools/fex/patches/0024-read-host-status-directly.patch new file mode 100644 index 0000000000..8a5268c7e7 --- /dev/null +++ b/tools/fex/patches/0024-read-host-status-directly.patch @@ -0,0 +1,105 @@ +From ab6a01db9e93e7f143b9a3da5b40dcb160b960f3 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:25:20 -0500 +Subject: [PATCH] Read FEX's own /proc/self/status with a direct openat system + call + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +--- + FEXHeaderUtils/FEXHeaderUtils/Syscalls.h | 30 +++++++++++++++++++ + .../EmulatedFiles/EmulatedFiles.cpp | 3 +- + .../LinuxSyscalls/PtraceEmu.cpp | 3 +- + 3 files changed, 34 insertions(+), 2 deletions(-) + +diff --git a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h +index dae3d3bcc..c0f3eb3ed 100644 +--- a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h ++++ b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h +@@ -4,6 +4,7 @@ + #include + + #include ++#include + #include + #include + #include +@@ -123,4 +124,33 @@ inline int32_t gettid() { + + #endif + ++#ifndef _WIN32 ++inline int32_t openat_kernel(int dirfd, const char* pathname, int flags) { ++#if defined(__aarch64__) ++ register long x0 asm("x0") = dirfd; ++ register long x1 asm("x1") = reinterpret_cast(pathname); ++ register long x2 asm("x2") = flags; ++ register long x3 asm("x3") = 0; ++ register long x8 asm("x8") = SYS_openat; ++ asm volatile("svc #0" : "+r"(x0) : "r"(x1), "r"(x2), "r"(x3), "r"(x8) : "memory"); ++ if (x0 < 0) { ++ errno = static_cast(-x0); ++ return -1; ++ } ++ return static_cast(x0); ++#elif defined(__x86_64__) ++ long ret; ++ register long r10 asm("r10") = 0; ++ asm volatile("syscall" : "=a"(ret) : "a"(SYS_openat), "D"(dirfd), "S"(pathname), "d"(flags), "r"(r10) : "rcx", "r11", "memory"); ++ if (ret < 0) { ++ errno = static_cast(-ret); ++ return -1; ++ } ++ return static_cast(ret); ++#else ++ return static_cast(::syscall(SYS_openat, dirfd, pathname, flags)); ++#endif ++} ++#endif ++ + } // namespace FHU::Syscalls +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index ce36b988b..19bfc814f 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -14,6 +14,7 @@ $end_info$ + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h" + ++#include + #include + #include + #include +@@ -785,7 +786,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd + char Buf[8192]; + ssize_t Len = 0; + { +- int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ int HostFD = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC); + if (HostFD >= 0) { + Len = ::read(HostFD, Buf, sizeof(Buf) - 1); + ::close(HostFD); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +index ca4c86063..49ece24a3 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +@@ -3,6 +3,7 @@ + #include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/Syscalls.h" + ++#include + #include + #include + +@@ -133,7 +134,7 @@ namespace { + } + + bool HasHostTracer() { +- const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ const int fd = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC); + if (fd < 0) { + return true; + } +-- +2.43.0 + diff --git a/tools/fex/patches/0025-ptrace-state-across-exec.patch b/tools/fex/patches/0025-ptrace-state-across-exec.patch new file mode 100644 index 0000000000..6c1bcc618f --- /dev/null +++ b/tools/fex/patches/0025-ptrace-state-across-exec.patch @@ -0,0 +1,104 @@ +From 38ee3ef08d9bfd8312fccff688290572da82ef2a Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:41:52 -0500 +Subject: [PATCH] Hand the tracee's ptrace state across exec + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +--- + .../LinuxSyscalls/PtraceEmu.cpp | 54 ++++++++++++++++++- + 1 file changed, 53 insertions(+), 1 deletion(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +index 49ece24a3..62acdb0da 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +@@ -266,6 +266,38 @@ namespace { + ::close(fd); + } + ++ bool AdoptionTried = false; ++ ++ void AdoptSharedPage() { ++ if (AdoptionTried || Current != &StaticState || !IsMainThread()) { ++ return; ++ } ++ AdoptionTried = true; ++ const int fd = OpenSidecar("state", ::getpid(), O_RDWR); ++ if (fd < 0) { ++ return; ++ } ++ if (!HasHostTracer()) { ++ ::close(fd); ++ return; ++ } ++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ ::close(fd); ++ if (Page == MAP_FAILED) { ++ return; ++ } ++ auto* S = static_cast(Page); ++ if (S->Magic != SharedState::MagicValue) { ++ ::munmap(Page, 4096); ++ return; ++ } ++ S->Pending = 0; ++ S->DirtyMask = 0; ++ S->SignalNumber = 0; ++ S->FlushLen = 0; ++ Current = S; ++ } ++ + struct Remote { + uint8_t* Mapped = nullptr; + uintptr_t StaticAddr = 0; +@@ -332,6 +364,22 @@ namespace { + return &Remotes.emplace(Pid, std::move(R)).first->second; + } + ++ bool KeepAcrossExec(pid_t Pid) { ++ { ++ std::lock_guard lk(RemotesLock); ++ auto It = Remotes.find(Pid); ++ if (It != Remotes.end()) { ++ return It->second.Mapped != nullptr; ++ } ++ } ++ const int fd = OpenSidecar("state", Pid, O_RDONLY); ++ if (fd < 0) { ++ return false; ++ } ++ ::close(fd); ++ return true; ++ } ++ + void Forget(pid_t Pid, bool Exited) { + std::lock_guard lk(RemotesLock); + auto It = Remotes.find(Pid); +@@ -470,10 +518,12 @@ namespace { + + + bool IsAttached() { ++ AdoptSharedPage(); + return Current->Attached != 0; + } + + bool WantsSyscallStops() { ++ AdoptSharedPage(); + return Current->SyscallStops && IsMainThread(); + } + +@@ -610,7 +660,9 @@ bool FixupWaitStatus(pid_t Pid, int* Status) { + + if ((St >> 16) == X86_PTRACE_EVENT_EXEC) { + CaptureExecPath(Pid); +- Forget(Pid, false); ++ if (!KeepAcrossExec(Pid)) { ++ Forget(Pid, false); ++ } + } + + if (WSTOPSIG(St) == SIGSTOP) { +-- +2.43.0 + diff --git a/tools/fex/patches/0026-emulated-proc-files-behind-host-memfd.patch b/tools/fex/patches/0026-emulated-proc-files-behind-host-memfd.patch new file mode 100644 index 0000000000..0ebaff5209 --- /dev/null +++ b/tools/fex/patches/0026-emulated-proc-files-behind-host-memfd.patch @@ -0,0 +1,78 @@ +From 834075bdee10fb0a1c7a7f499a0bb97162370b5d Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:58:13 -0500 +Subject: [PATCH] Serve emulated proc files by the requested path when the host + returns a memfd + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). +--- + .../LinuxEmulation/LinuxSyscalls/FileManagement.cpp | 11 +++++++---- + .../LinuxEmulation/LinuxSyscalls/FileManagement.h | 2 +- + 2 files changed, 8 insertions(+), 5 deletions(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +index 62b6a2d27..b76e96e58 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +@@ -785,7 +785,7 @@ static int OpenatWithoutOpenat2(int DirFD, const char* Pathname, int Flags, uint + return ::syscall(SYSCALL_DEF(openat), DirFD, Resolved, Flags, Mode); + } + +-bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) { ++bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath) { + char Tmp[PATH_MAX + 1]; + + if (fd < 0) { +@@ -801,6 +801,9 @@ bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) { + + // And try to open via EmuFD + auto EmuFd = EmuFD.Open(Tmp, flags, mode); ++ if (EmuFd == -1 && RequestedPath && RequestedPath[0] == '/' && strncmp(Tmp, "/memfd:", 7) == 0) { ++ EmuFd = EmuFD.Open(RequestedPath, flags, mode); ++ } + if (EmuFd == -1) { + return false; + } +@@ -841,7 +844,7 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) { + fd = ::open(SelfPath, flags, mode); + } + +- ReplaceEmuFd(fd, flags, mode); ++ ReplaceEmuFd(fd, flags, mode, SelfPath); + } else { + fd = ::open(SelfPath, flags, mode); + } +@@ -1135,7 +1138,7 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i + fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode); + } + +- ReplaceEmuFd(fd, flags, mode); ++ ReplaceEmuFd(fd, flags, mode, SelfPath); + } else { + fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode); + } +@@ -1173,7 +1176,7 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho + fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize); + } + +- ReplaceEmuFd(fd, how->flags, how->mode); ++ ReplaceEmuFd(fd, how->flags, how->mode, SelfPath); + } else { + fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize); + } +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h +index b11f096f7..a86539972 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h +@@ -102,7 +102,7 @@ public: + fextl::string GetEmulatedPath(const char* pathname, bool FollowSymlink = false) const; + fextl::string GetHostPath(fextl::string& Path, bool AliasedOnly) const; + +- bool ReplaceEmuFd(int fd, int flags, uint32_t mode); ++ bool ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath); + + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED + void TrackFEXFD(int FD) noexcept { +-- +2.43.0 + diff --git a/tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch b/tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch new file mode 100644 index 0000000000..b19386b095 --- /dev/null +++ b/tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch @@ -0,0 +1,3258 @@ +From 4e237204720bf57c8e4b7dae1ff74b5e341763e6 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 20:01:44 -0500 +Subject: [PATCH] Map fixed guest memory above a small host address space + +Hosts with 39-bit or 42-bit user address spaces cannot place x86-64 +mappings that ask for a fixed address above that limit. Such mappings +are now backed by host memory at any address, and guest accesses to +them are redirected through a per-thread single-instruction trampoline. +Syscall arguments that point into these mappings are translated, and +writes to code in them invalidate translated blocks. + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). +--- + Source/Tools/LinuxEmulation/CMakeLists.txt | 1 + + .../LinuxSyscalls/GuestHighMemory.cpp | 2754 +++++++++++++++++ + .../LinuxSyscalls/GuestHighMemory.h | 74 + + .../LinuxSyscalls/SignalDelegator.cpp | 5 + + .../LinuxEmulation/LinuxSyscalls/Syscalls.cpp | 53 +- + .../LinuxSyscalls/Syscalls/Memory.cpp | 30 + + .../LinuxSyscalls/SyscallsSMCTracking.cpp | 61 +- + .../LinuxSyscalls/ThreadManager.cpp | 2 + + .../LinuxSyscalls/ThreadManager.h | 34 + + 9 files changed, 2984 insertions(+), 30 deletions(-) + create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp + create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h + +diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt +index 3f02104..acf4c4c 100644 +--- a/Source/Tools/LinuxEmulation/CMakeLists.txt ++++ b/Source/Tools/LinuxEmulation/CMakeLists.txt +@@ -18,6 +18,7 @@ add_library(LinuxEmulation STATIC + LinuxSyscalls/Seccomp/BPFEmitter.cpp + LinuxSyscalls/Seccomp/Dumper.cpp + LinuxSyscalls/SignalDelegator.cpp ++ LinuxSyscalls/GuestHighMemory.cpp + LinuxSyscalls/Syscalls.cpp + LinuxSyscalls/SyscallsSMCTracking.cpp + LinuxSyscalls/SyscallsVMATracking.cpp +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp +new file mode 100644 +index 0000000..4483499 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp +@@ -0,0 +1,2754 @@ ++#include "LinuxSyscalls/GuestHighMemory.h" ++#include "LinuxSyscalls/Syscalls.h" ++#include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/ThreadManager.h" ++#include "LinuxSyscalls/x64/SyscallsEnum.h" ++#include "ArchHelpers/MContext.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE::GuestHighMemory { ++namespace { ++ constexpr uint64_t TaskTop = (1ULL << 47) - FEXCore::Utils::FEX_PAGE_SIZE; ++ constexpr uint32_t MaxRegions = 1024; ++ ++ struct Region { ++ std::atomic Guest; ++ std::atomic Size; ++ std::atomic Host; ++ std::atomic Code; ++ std::atomic Prot; ++ }; ++ ++ struct RegionView { ++ uint64_t Guest; ++ uint64_t Size; ++ uint64_t Host; ++ uint32_t Index; ++ bool Code; ++ uint8_t Prot; ++ }; ++ ++ struct HostRange { ++ uint64_t Start; ++ uint64_t Size; ++ }; ++ ++ constexpr uint32_t MaxAccessPieces = 2; ++ ++ struct AccessPiece { ++ uint64_t Guest; ++ uint64_t Host; ++ uint64_t Size; ++ uint8_t Prot; ++ bool Code; ++ }; ++ ++ Region Regions[MaxRegions]; ++ std::atomic Count {0}; ++ HostRange Retired[MaxRegions]; ++ uint32_t RetiredCount {}; ++ std::atomic Sequence {0}; ++ ++ uint64_t HostLimit() { ++ static const uint64_t Limit = [] { ++ const auto Bits = FEXCore::Allocator::GetHostVABits(); ++ return Bits >= 47 ? TaskTop : (1ULL << Bits); ++ }(); ++ return Limit; ++ } ++ ++ void BeginWrite() { ++ Sequence.fetch_add(1, std::memory_order_acq_rel); ++ } ++ ++ void EndWrite() { ++ Sequence.fetch_add(1, std::memory_order_release); ++ } ++ ++ bool FindLocked(uint64_t Address, RegionView* Out) { ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ if (Address >= Guest && Address - Guest < Size) { ++ Out->Guest = Guest; ++ Out->Size = Size; ++ Out->Host = Regions[i].Host.load(std::memory_order_relaxed); ++ Out->Code = Regions[i].Code.load(std::memory_order_relaxed); ++ Out->Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ Out->Index = i; ++ return true; ++ } ++ } ++ return false; ++ } ++ ++ template ++ auto ReadConsistent(Fn&& Body) { ++ for (;;) { ++ const auto Before = Sequence.load(std::memory_order_acquire); ++ if (Before & 1) { ++ continue; ++ } ++ const auto Result = Body(); ++ std::atomic_thread_fence(std::memory_order_acquire); ++ if (Sequence.load(std::memory_order_relaxed) == Before) { ++ return Result; ++ } ++ } ++ } ++ ++ bool SpanLocked(uint64_t Address, uint64_t Length, uint64_t* Host) { ++ RegionView View; ++ if (!FindLocked(Address, &View)) { ++ *Host = Address; ++ return true; ++ } ++ *Host = View.Host + (Address - View.Guest); ++ if (Length > TaskTop - Address) { ++ return false; ++ } ++ const auto End = Address + Length; ++ auto GuestEnd = View.Guest + View.Size; ++ auto HostEnd = View.Host + View.Size; ++ while (End > GuestEnd) { ++ if (!FindLocked(GuestEnd, &View) || View.Host != HostEnd) { ++ return false; ++ } ++ GuestEnd += View.Size; ++ HostEnd += View.Size; ++ } ++ return true; ++ } ++ ++ uint32_t PlanAccessLocked(uint64_t Address, uint64_t Size, AccessPiece* Pieces) { ++ uint32_t Parts = 0; ++ uint64_t Done = 0; ++ while (Done < Size) { ++ RegionView View; ++ if (Parts == MaxAccessPieces || !FindLocked(Address + Done, &View)) { ++ return 0; ++ } ++ const auto Offset = Address + Done - View.Guest; ++ const auto Length = std::min(Size - Done, View.Size - Offset); ++ Pieces[Parts++] = {Address + Done, View.Host + Offset, Length, View.Prot, View.Code}; ++ Done += Length; ++ } ++ return Parts; ++ } ++ ++ template ++ uint64_t ApplyToRegionsLocked(uint64_t Address, uint64_t Length, uint64_t WrapError, Fn&& Apply) { ++ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) { ++ return -EINVAL; ++ } ++ if (Length == 0) { ++ return 0; ++ } ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (Size == 0 || Size > UINT64_MAX - Address) { ++ return WrapError; ++ } ++ const auto End = Address + std::min(Size, TaskTop - Address); ++ uint64_t Covered = 0; ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed); ++ if (RegionEnd <= Address || Guest >= End) { ++ continue; ++ } ++ const auto OverlapStart = std::max(Guest, Address); ++ const auto OverlapEnd = std::min(RegionEnd, End); ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed) + (OverlapStart - Guest); ++ if (Apply(reinterpret_cast(Host), OverlapEnd - OverlapStart, i) != 0) { ++ return -errno; ++ } ++ Covered += OverlapEnd - OverlapStart; ++ } ++ return Covered == Size ? 0 : -ENOMEM; ++ } ++ ++ uint64_t NeighbourHint(uint64_t Address, uint64_t Size) { ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionSize = Regions[i].Size.load(std::memory_order_relaxed); ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ if (Guest + RegionSize == Address) { ++ return Host + RegionSize; ++ } ++ if (Guest == Address + Size && Host >= Size) { ++ return Host - Size; ++ } ++ } ++ return 0; ++ } ++ ++ void SetEntry(uint32_t i, uint64_t Guest, uint64_t Size, uint64_t Host, bool Code, uint8_t Prot) { ++ Regions[i].Guest.store(Guest, std::memory_order_relaxed); ++ Regions[i].Size.store(Size, std::memory_order_relaxed); ++ Regions[i].Host.store(Host, std::memory_order_relaxed); ++ Regions[i].Code.store(Code, std::memory_order_relaxed); ++ Regions[i].Prot.store(Prot, std::memory_order_relaxed); ++ } ++ ++ void RemoveEntry(uint32_t i) { ++ const auto Last = Count.load(std::memory_order_relaxed) - 1; ++ if (i != Last) { ++ SetEntry(i, Regions[Last].Guest.load(std::memory_order_relaxed), Regions[Last].Size.load(std::memory_order_relaxed), ++ Regions[Last].Host.load(std::memory_order_relaxed), Regions[Last].Code.load(std::memory_order_relaxed), ++ Regions[Last].Prot.load(std::memory_order_relaxed)); ++ } ++ Count.store(Last, std::memory_order_release); ++ } ++ ++ bool AddEntry(uint64_t Guest, uint64_t Size, uint64_t Host, bool Code, uint8_t Prot) { ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ if (Entries >= MaxRegions) { ++ return false; ++ } ++ SetEntry(Entries, Guest, Size, Host, Code, Prot); ++ Count.store(Entries + 1, std::memory_order_release); ++ return true; ++ } ++ ++ bool HasRoomLocked(uint64_t Address, uint64_t Length, uint32_t Added) { ++ const auto End = Address + Length; ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ uint64_t After = Entries + Added; ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed); ++ if (RegionEnd <= Address || Guest >= End) { ++ continue; ++ } ++ if (Guest >= Address && RegionEnd <= End) { ++ --After; ++ } else if (Guest < Address && RegionEnd > End) { ++ ++After; ++ } ++ } ++ return After <= MaxRegions; ++ } ++ ++ void ReleaseRetiredLocked() { ++ uint32_t i = 0; ++ while (i < RetiredCount) { ++ if (::munmap(reinterpret_cast(Retired[i].Start), Retired[i].Size) == 0) { ++ Retired[i] = Retired[--RetiredCount]; ++ } else { ++ ++i; ++ } ++ } ++ } ++ ++ void UnmapHost(uint64_t Start, uint64_t Size) { ++ if (::munmap(reinterpret_cast(Start), Size) == 0) { ++ return; ++ } ++ ::madvise(reinterpret_cast(Start), Size, MADV_DONTNEED); ++ for (uint32_t i = 0; i < RetiredCount; ++i) { ++ if (Retired[i].Start + Retired[i].Size == Start) { ++ Retired[i].Size += Size; ++ return; ++ } ++ if (Start + Size == Retired[i].Start) { ++ Retired[i] = {Start, Retired[i].Size + Size}; ++ return; ++ } ++ } ++ if (RetiredCount < MaxRegions) { ++ Retired[RetiredCount++] = {Start, Size}; ++ } ++ } ++ ++ int UnmapLocked(uint64_t Address, uint64_t Length) { ++ ReleaseRetiredLocked(); ++ if (!HasRoomLocked(Address, Length, 0)) { ++ return -ENOMEM; ++ } ++ const auto End = Address + Length; ++ uint32_t Overlapping = 0; ++ for (uint32_t i = 0; i < Count.load(std::memory_order_relaxed); ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ if (Guest < End && Guest + Regions[i].Size.load(std::memory_order_relaxed) > Address) { ++ ++Overlapping; ++ } ++ } ++ if (RetiredCount + Overlapping > MaxRegions) { ++ return -ENOMEM; ++ } ++ uint32_t i = 0; ++ while (i < Count.load(std::memory_order_relaxed)) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ const auto Code = Regions[i].Code.load(std::memory_order_relaxed); ++ const auto Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Size; ++ if (RegionEnd <= Address || Guest >= End) { ++ ++i; ++ continue; ++ } ++ const auto OverlapStart = std::max(Guest, Address); ++ const auto OverlapEnd = std::min(RegionEnd, End); ++ UnmapHost(Host + (OverlapStart - Guest), OverlapEnd - OverlapStart); ++ ++ if (OverlapStart == Guest && OverlapEnd == RegionEnd) { ++ RemoveEntry(i); ++ continue; ++ } ++ if (OverlapStart == Guest) { ++ SetEntry(i, OverlapEnd, RegionEnd - OverlapEnd, Host + (OverlapEnd - Guest), Code, Prot); ++ } else if (OverlapEnd == RegionEnd) { ++ SetEntry(i, Guest, OverlapStart - Guest, Host, Code, Prot); ++ } else { ++ if (!AddEntry(OverlapEnd, RegionEnd - OverlapEnd, Host + (OverlapEnd - Guest), Code, Prot)) { ++ return -ENOMEM; ++ } ++ SetEntry(i, Guest, OverlapStart - Guest, Host, Code, Prot); ++ } ++ ++i; ++ } ++ return 0; ++ } ++ ++ constexpr uint8_t TrackedProt(int Prot) { ++ return Prot & (PROT_READ | PROT_WRITE | PROT_EXEC); ++ } ++ ++ int SplitLocked(uint64_t Address, uint64_t Length) { ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (Size == 0) { ++ return 0; ++ } ++ const uint64_t Boundaries[] = {Address, Address + std::min(Size, TaskTop - Address)}; ++ uint32_t Needed = 0; ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ for (const auto Boundary : Boundaries) { ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ if (Boundary > Guest && Boundary - Guest < Regions[i].Size.load(std::memory_order_relaxed)) { ++ ++Needed; ++ } ++ } ++ } ++ if (Entries + Needed > MaxRegions) { ++ return -ENOMEM; ++ } ++ for (const auto Boundary : Boundaries) { ++ for (uint32_t i = 0; i < Count.load(std::memory_order_relaxed); ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionSize = Regions[i].Size.load(std::memory_order_relaxed); ++ if (Boundary <= Guest || Boundary - Guest >= RegionSize) { ++ continue; ++ } ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ const auto Code = Regions[i].Code.load(std::memory_order_relaxed); ++ const auto Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ AddEntry(Boundary, Guest + RegionSize - Boundary, Host + (Boundary - Guest), Code, Prot); ++ SetEntry(i, Guest, Boundary - Guest, Host, Code, Prot); ++ break; ++ } ++ } ++ return 0; ++ } ++ ++ void CoalesceLocked(uint64_t Address, uint64_t End) { ++ uint32_t i = 0; ++ while (i < Count.load(std::memory_order_relaxed)) { ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ const auto RegionEnd = Regions[i].Guest.load(std::memory_order_relaxed) + Size; ++ const auto HostEnd = Regions[i].Host.load(std::memory_order_relaxed) + Size; ++ const auto Code = Regions[i].Code.load(std::memory_order_relaxed); ++ const auto Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ uint32_t Next = Entries; ++ if (RegionEnd >= Address && RegionEnd <= End) { ++ for (uint32_t j = 0; j < Entries; ++j) { ++ if (Regions[j].Guest.load(std::memory_order_relaxed) == RegionEnd && Regions[j].Host.load(std::memory_order_relaxed) == HostEnd && ++ Regions[j].Code.load(std::memory_order_relaxed) == Code && Regions[j].Prot.load(std::memory_order_relaxed) == Prot) { ++ Next = j; ++ break; ++ } ++ } ++ } ++ if (Next == Entries) { ++ ++i; ++ continue; ++ } ++ Regions[i].Size.store(Size + Regions[Next].Size.load(std::memory_order_relaxed), std::memory_order_relaxed); ++ RemoveEntry(Next); ++ if (i == Entries - 1 || Next < i) { ++ i = Next; ++ } ++ } ++ } ++ ++ constexpr uint32_t RtField(uint32_t Insn) { ++ return Insn & 0x1f; ++ } ++ ++ constexpr uint32_t RnField(uint32_t Insn) { ++ return (Insn >> 5) & 0x1f; ++ } ++ ++ constexpr uint32_t Rt2Field(uint32_t Insn) { ++ return (Insn >> 10) & 0x1f; ++ } ++ ++ constexpr uint32_t RsField(uint32_t Insn) { ++ return (Insn >> 16) & 0x1f; ++ } ++ ++ constexpr bool IsLoadStore(uint32_t Insn) { ++ return (Insn & 0x0a000000) == 0x08000000; ++ } ++ ++ constexpr bool IsLiteralLoad(uint32_t Insn) { ++ return (Insn & 0x3b000000) == 0x18000000; ++ } ++ ++ constexpr bool IsExclusive(uint32_t Insn) { ++ if ((Insn & 0x3f800000) != 0x08000000) { ++ return false; ++ } ++ return (Insn & (1U << 21)) == 0 || (Insn & (1U << 31)) != 0; ++ } ++ ++ constexpr bool IsSingleRegister(uint32_t Insn) { ++ return (Insn & 0x3a000000) == 0x38000000 || (Insn & 0x3f200c00) == 0x19000000; ++ } ++ ++ constexpr bool IsWrite(uint32_t Insn) { ++ if ((Insn & 0x3b200c00) == 0x38200000) { ++ return ((Insn >> 12) & 0xf) != 0xc; ++ } ++ if ((Insn & 0x3f200000) == 0x08200000 && Rt2Field(Insn) == 0x1f) { ++ return true; ++ } ++ if (IsSingleRegister(Insn)) { ++ const auto Opc = (Insn >> 22) & 3; ++ return ((Insn >> 26) & 1) ? (Opc & 1) == 0 : Opc == 0; ++ } ++ return (Insn & (1U << 22)) == 0; ++ } ++ ++ constexpr bool IsOrderedAccess(uint32_t Insn) { ++ if ((Insn & 0x3f200c00) == 0x19000000) { ++ const auto Opc = (Insn >> 22) & 3; ++ const auto SizeBits = Insn >> 30; ++ return Opc < 2 || (Opc == 2 && SizeBits < 3) || (Opc == 3 && SizeBits < 2); ++ } ++ return (Insn & 0x3fbf7c00) == 0x089f7c00 || (Insn & 0x3ffffc00) == 0x38bfc000; ++ } ++ ++ constexpr uint64_t ExtendOrdered(uint32_t Insn, uint64_t Value) { ++ const auto Bits = 8U << (Insn >> 30); ++ const auto Opc = (Insn >> 22) & 3; ++ if ((Insn & 0x3f200c00) != 0x19000000 || Bits == 64 || Opc < 2) { ++ return Value; ++ } ++ const auto Signed = static_cast(static_cast(Value << (64 - Bits)) >> (64 - Bits)); ++ return Opc == 3 ? Signed & 0xffffffffULL : Signed; ++ } ++ ++ constexpr uint32_t ProbeInstruction(uint32_t Scratch) { ++ return 0x39400000 | (Scratch << 5) | Scratch; ++ } ++ ++ constexpr bool IsExclusiveLoad(uint32_t Insn) { ++ return (Insn & (1U << 22)) != 0; ++ } ++ ++ constexpr bool IsExclusivePair(uint32_t Insn) { ++ return (Insn & (1U << 21)) != 0; ++ } ++ ++ constexpr bool ExclusiveReachable(uint32_t Insn, uint8_t Prot) { ++ if (IsExclusiveLoad(Insn)) { ++ return (Prot & (PROT_READ | PROT_WRITE)) != 0; ++ } ++ return (Prot & PROT_WRITE) != 0; ++ } ++ ++ constexpr uint32_t ExclusiveElementSize(uint32_t Insn) { ++ return 1U << (Insn >> 30); ++ } ++ ++ uint64_t ReadReg(void* UContext, uint32_t Reg) { ++ return Reg == 31 ? 0 : ArchHelpers::Context::GetArmReg(UContext, Reg); ++ } ++ ++ void WriteReg(void* UContext, uint32_t Reg, uint64_t Value) { ++ if (Reg != 31) { ++ ArchHelpers::Context::SetArmReg(UContext, Reg, Value); ++ } ++ } ++ ++ uint64_t ElementMask(uint32_t Size) { ++ return Size == 8 ? ~0ULL : (1ULL << (Size * 8)) - 1; ++ } ++ ++ uint64_t LoadElement(uint64_t Host, uint32_t Size) { ++ switch (Size) { ++ case 1: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ case 2: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ case 4: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ default: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ } ++ } ++ ++ bool CompareExchange(uint64_t Host, uint32_t Size, uint64_t ExpectedLow, uint64_t ExpectedHigh, uint64_t Low, uint64_t High) { ++ switch (Size) { ++ case 1: { ++ auto Expected = static_cast(ExpectedLow); ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, static_cast(Low), false, ++ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ case 2: { ++ auto Expected = static_cast(ExpectedLow); ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, static_cast(Low), false, ++ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ case 4: { ++ auto Expected = static_cast(ExpectedLow); ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, static_cast(Low), false, ++ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ case 8: { ++ auto Expected = ExpectedLow; ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, Low, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ default: { ++ auto Expected = (static_cast(ExpectedHigh) << 64) | ExpectedLow; ++ const auto Desired = (static_cast(High) << 64) | Low; ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, Desired, false, __ATOMIC_SEQ_CST, ++ __ATOMIC_SEQ_CST); ++ } ++ } ++ } ++ ++ template ++ bool EmulateExclusive(MonitorType& Monitor, uint32_t Insn, uint64_t Host, void* UContext) { ++ const auto Element = ExclusiveElementSize(Insn); ++ const bool Pair = IsExclusivePair(Insn); ++ const auto Size = Pair ? Element * 2 : Element; ++ if (Host & (Size - 1)) { ++ return false; ++ } ++ ++ if (IsExclusiveLoad(Insn)) { ++ uint64_t Low {}; ++ uint64_t High {}; ++ if (Pair && Element == 8) { ++ Low = LoadElement(Host, 8); ++ High = LoadElement(Host + 8, 8); ++ WriteReg(UContext, RtField(Insn), Low); ++ WriteReg(UContext, Rt2Field(Insn), High); ++ } else if (Pair) { ++ Low = LoadElement(Host, 8); ++ WriteReg(UContext, RtField(Insn), Low & 0xffffffffULL); ++ WriteReg(UContext, Rt2Field(Insn), Low >> 32); ++ } else { ++ Low = LoadElement(Host, Element); ++ WriteReg(UContext, RtField(Insn), Low); ++ } ++ Monitor.Host = Host; ++ Monitor.Size = Size; ++ Monitor.Low = Low; ++ Monitor.High = High; ++ Monitor.Valid = true; ++ return true; ++ } ++ ++ uint64_t Low {}; ++ uint64_t High {}; ++ if (Pair && Element == 8) { ++ Low = ReadReg(UContext, RtField(Insn)); ++ High = ReadReg(UContext, Rt2Field(Insn)); ++ } else if (Pair) { ++ Low = (ReadReg(UContext, RtField(Insn)) & 0xffffffffULL) | (ReadReg(UContext, Rt2Field(Insn)) << 32); ++ } else { ++ Low = ReadReg(UContext, RtField(Insn)) & ElementMask(Element); ++ } ++ const bool Stored = Monitor.Valid && Monitor.Host == Host && Monitor.Size == Size && ++ CompareExchange(Host, Size, Monitor.Low, Monitor.High, Low, High); ++ Monitor.Valid = false; ++ WriteReg(UContext, RsField(Insn), Stored ? 0 : 1); ++ return true; ++ } ++ ++ int64_t SignedField(uint32_t Insn, uint32_t Shift, uint32_t Bits) { ++ return static_cast(static_cast(Insn >> Shift) << (64 - Bits)) >> (64 - Bits); ++ } ++ ++ bool DecodeAccess(uint32_t Insn, void* UContext, uint64_t* Address, uint32_t* Size, bool* Plain) { ++ const auto Base = ArchHelpers::Context::GetArmReg(UContext, RnField(Insn)); ++ const auto SizeBits = Insn >> 30; ++ const bool Vector = (Insn >> 26) & 1; ++ const auto Scale = Vector && ((Insn >> 23) & 1) && SizeBits == 0 ? 4U : SizeBits; ++ *Address = Base; ++ *Plain = false; ++ if ((Insn & 0x3f000000) == 0x08000000) { ++ const bool Pair = (Insn & (1U << 21)) && !(Insn & (1U << 23)); ++ *Size = Pair ? 8U << (SizeBits & 1) : 1U << SizeBits; ++ return true; ++ } ++ if ((Insn & 0x3f200c00) == 0x19000000) { ++ *Address = Base + SignedField(Insn, 12, 9); ++ *Size = 1U << SizeBits; ++ return true; ++ } ++ if ((Insn & 0x3b200c00) == 0x38200000) { ++ *Size = 1U << SizeBits; ++ return !Vector; ++ } ++ *Plain = true; ++ if ((Insn & 0x3b000000) == 0x39000000) { ++ *Address = Base + (static_cast((Insn >> 10) & 0xfff) << Scale); ++ *Size = 1U << Scale; ++ return true; ++ } ++ if ((Insn & 0x3b200000) == 0x38000000) { ++ *Address = ((Insn >> 10) & 3) == 1 ? Base : Base + SignedField(Insn, 12, 9); ++ *Size = 1U << Scale; ++ return true; ++ } ++ if ((Insn & 0x3b200c00) == 0x38200800) { ++ const auto Option = (Insn >> 13) & 7; ++ if ((Option & 2) == 0) { ++ return false; ++ } ++ auto Offset = ReadReg(UContext, RsField(Insn)); ++ if ((Option & 1) == 0) { ++ Offset = (Option & 4) ? static_cast(static_cast(static_cast(Offset))) : static_cast(Offset); ++ } ++ *Address = Base + (Offset << (((Insn >> 12) & 1) ? Scale : 0)); ++ *Size = 1U << Scale; ++ return true; ++ } ++ if ((Insn & 0x3a000000) == 0x28000000) { ++ if (SizeBits == 3) { ++ return false; ++ } ++ const auto Element = Vector ? 4U << SizeBits : (SizeBits == 2 ? 8U : 4U); ++ *Address = ((Insn >> 23) & 3) == 1 ? Base : Base + SignedField(Insn, 15, 7) * static_cast(Element); ++ *Size = 2 * Element; ++ return true; ++ } ++ if ((Insn & 0xbfbf0000) == 0x0c000000 || (Insn & 0xbfa00000) == 0x0c800000) { ++ uint32_t Registers = 0; ++ switch ((Insn >> 12) & 0xf) { ++ case 0x0: ++ case 0x2: Registers = 4; break; ++ case 0x4: ++ case 0x6: Registers = 3; break; ++ case 0x7: Registers = 1; break; ++ case 0x8: ++ case 0xa: Registers = 2; break; ++ default: return false; ++ } ++ *Size = Registers * ((Insn & (1U << 30)) ? 16U : 8U); ++ return true; ++ } ++ if ((Insn & 0xbf9f0000) == 0x0d000000 || (Insn & 0xbf800000) == 0x0d800000) { ++ const auto Opcode = (Insn >> 13) & 7; ++ const auto Elements = (((Opcode & 1) << 1) | ((Insn >> 21) & 1)) + 1; ++ const auto Bits = (Insn >> 10) & 3; ++ uint32_t Element = 0; ++ switch (Opcode >> 1) { ++ case 0: Element = 1; break; ++ case 1: Element = (Bits & 1) ? 0 : 2; break; ++ case 2: Element = Bits == 0 ? 4 : (Bits == 1 && !((Insn >> 12) & 1) ? 8 : 0); break; ++ default: Element = 1U << Bits; break; ++ } ++ *Size = Elements * Element; ++ return Element != 0; ++ } ++ return false; ++ } ++ ++ bool HostContiguous(const AccessPiece* Pieces, uint32_t Parts) { ++ for (uint32_t i = 1; i < Parts; ++i) { ++ if (Pieces[i - 1].Host + Pieces[i - 1].Size != Pieces[i].Host) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ bool PiecesReachable(const AccessPiece* Pieces, uint32_t Parts, bool Write) { ++ const uint8_t Need = Write ? PROT_WRITE : PROT_READ | PROT_WRITE; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ if ((Pieces[i].Prot & Need) == 0) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ template ++ uint32_t CopyPieces(uint8_t* Bounce, const PieceType* Pieces, uint32_t Parts, bool Gather) { ++ uint64_t Offset = 0; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ auto* Host = reinterpret_cast(Pieces[i].Host); ++ const auto Failed = Gather ? FaultSafeUserMemAccess::CopyFromUser(Bounce + Offset, Host, Pieces[i].Size) : ++ FaultSafeUserMemAccess::CopyToUser(Host, Bounce + Offset, Pieces[i].Size); ++ if (Failed != 0) { ++ return i; ++ } ++ Offset += Pieces[i].Size; ++ } ++ return Parts; ++ } ++ ++ template ++ uint32_t EmulateOrdered(uint32_t Insn, const PieceType* Pieces, uint32_t Parts, void* UContext) { ++ const auto Size = 1U << (Insn >> 30); ++ uint8_t Bytes[8] {}; ++ std::atomic_thread_fence(std::memory_order_seq_cst); ++ const auto Gathered = CopyPieces(Bytes, Pieces, Parts, true); ++ if (Gathered != Parts) { ++ return Gathered; ++ } ++ uint64_t Value {}; ++ if (IsWrite(Insn)) { ++ Value = ReadReg(UContext, RtField(Insn)); ++ memcpy(Bytes, &Value, Size); ++ const auto Scattered = CopyPieces(Bytes, Pieces, Parts, false); ++ std::atomic_thread_fence(std::memory_order_seq_cst); ++ return Scattered; ++ } ++ memcpy(&Value, Bytes, Size); ++ std::atomic_thread_fence(std::memory_order_seq_cst); ++ WriteReg(UContext, RtField(Insn), ExtendOrdered(Insn, Value)); ++ return Parts; ++ } ++ ++ constexpr int HeldSignals[] = {SIGSEGV, SIGBUS, SIGTRAP}; ++ ++ constexpr uint64_t HeldSignalMask() { ++ uint64_t Mask = 0; ++ for (int Sig : HeldSignals) { ++ Mask |= 1ULL << (Sig - 1); ++ } ++ return Mask; ++ } ++ ++ constexpr int HeldSignalSlot(int Signal) { ++ for (int Slot = 0; Slot < static_cast(std::size(HeldSignals)); ++Slot) { ++ if (HeldSignals[Slot] == Signal) { ++ return Slot; ++ } ++ } ++ return -1; ++ } ++ ++ template ++ bool DeferWhileHeld(HoldState& Hold, int Signal, const siginfo_t* Info) { ++ const int Slot = HeldSignalSlot(Signal); ++ if (!Hold.Held || Info->si_code > SI_USER || Slot < 0) { ++ return false; ++ } ++ Hold.Deferred |= 1U << Slot; ++ Hold.DeferredInfo[Slot] = *Info; ++ return true; ++ } ++ ++ template ++ uint64_t ReleaseMappings(HoldState& Hold) { ++ if (!Hold.Held) { ++ return 0; ++ } ++ FEX::HLE::_SyscallHandler->VMATracking.Mutex.unlock_shared(); ++ Hold.Held = false; ++ uint64_t Requeued = 0; ++ for (int Slot = 0; Slot < static_cast(std::size(HeldSignals)); ++Slot) { ++ if (Hold.Deferred & (1U << Slot)) { ++ Requeued |= 1ULL << (HeldSignals[Slot] - 1); ++ } ++ } ++ if (Requeued == 0) { ++ return 0; ++ } ++ ::syscall(SYS_rt_sigprocmask, SIG_BLOCK, &Requeued, nullptr, sizeof(Requeued)); ++ const auto Process = ::syscall(SYS_getpid); ++ const auto Self = ::syscall(SYS_gettid); ++ for (int Slot = 0; Slot < static_cast(std::size(HeldSignals)); ++Slot) { ++ if (Hold.Deferred & (1U << Slot)) { ++ ::syscall(SYS_rt_tgsigqueueinfo, Process, Self, HeldSignals[Slot], &Hold.DeferredInfo[Slot]); ++ } ++ } ++ Hold.Deferred = 0; ++ return Requeued; ++ } ++ ++ template ++ class MappingHold final { ++ public: ++ explicit MappingHold(HoldState& Hold, bool Deliver = false) ++ : Hold {Hold} ++ , Deliver {Deliver} { ++ const uint64_t All = ~0ULL; ++ ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &All, &Mask, sizeof(Mask)); ++ FEX::HLE::_SyscallHandler->VMATracking.Mutex.lock_shared(); ++ Hold.Held = true; ++ const uint64_t Blocked = ~HeldSignalMask(); ++ ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &Blocked, nullptr, sizeof(Blocked)); ++ } ++ MappingHold(const MappingHold&) = delete; ++ MappingHold& operator=(const MappingHold&) = delete; ++ ~MappingHold() { ++ if (!Kept) { ++ const uint64_t Requeued = ReleaseMappings(Hold); ++ const uint64_t Restored = Deliver ? Mask : Mask | Requeued; ++ ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &Restored, nullptr, sizeof(Restored)); ++ } ++ } ++ void Keep() { ++ Kept = true; ++ } ++ ++ private: ++ HoldState& Hold; ++ uint64_t Mask {}; ++ bool Deliver {}; ++ bool Kept {}; ++ }; ++ ++ int PickScratch(uint32_t Insn) { ++ constexpr int Candidates[] = {16, 17, 9, 10, 11, 12, 13, 14, 15, 8, 7, 6, 5, 4, 3, 2}; ++ for (auto Reg : Candidates) { ++ const auto R = static_cast(Reg); ++ if (R != RtField(Insn) && R != RnField(Insn) && R != Rt2Field(Insn) && R != RsField(Insn)) { ++ return Reg; ++ } ++ } ++ return -1; ++ } ++ ++ constexpr uint32_t TrapInstruction = 0xd4200000 | (0xf3e << 5); ++ ++ using TrapState = decltype(FEX::HLE::ThreadStateObject::HighMemoryTrap); ++ ++ bool EnsureTrapCode(TrapState& Trap) { ++ if (!Trap.Code) { ++ void* Page = FEXCore::Allocator::VirtualAlloc(FEXCore::Utils::FEX_PAGE_SIZE, true); ++ if (Page == MAP_FAILED || Page == nullptr) { ++ return false; ++ } ++ Trap.Code = static_cast(Page); ++ } ++ return true; ++ } ++ ++ void ArmTrap(TrapState& Trap, void* UContext, uint32_t Instruction, uint64_t ScratchValue, bool Probe) { ++ auto* Code = reinterpret_cast(Trap.Code); ++ Code[0] = Instruction; ++ Code[1] = TrapInstruction; ++ __builtin___clear_cache(reinterpret_cast(Code), reinterpret_cast(Code + 2)); ++ Trap.Probe = Probe; ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, ScratchValue); ++ ArchHelpers::Context::SetPc(UContext, reinterpret_cast(Code)); ++ Trap.Active = true; ++ } ++ ++ void ArmProbe(TrapState& Trap, void* UContext, uint64_t Guest, uint64_t Host) { ++ Trap.Parts = 0; ++ Trap.Delta = Host - Guest; ++ ArmTrap(Trap, UContext, ProbeInstruction(Trap.Scratch), Host, true); ++ } ++ ++ void LeaveTrap(TrapState& Trap, void* UContext, uint64_t ResumePC) { ++ memcpy(&ArchHelpers::Context::GetUContext(UContext)->uc_sigmask, &Trap.SavedMask, sizeof(Trap.SavedMask)); ++ ArchHelpers::Context::SetPc(UContext, ResumePC); ++ Trap.Parts = 0; ++ Trap.Probe = false; ++ Trap.Active = false; ++ ReleaseMappings(Trap.Mappings); ++ } ++ ++ void RedeliverFromTrap(TrapState& Trap, siginfo_t* SigInfo, void* UContext) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch); ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, Trap.BaseBefore); ++ SigInfo->si_addr = reinterpret_cast(reinterpret_cast(SigInfo->si_addr) - Trap.Delta); ++ LeaveTrap(Trap, UContext, Trap.ResumePC - 4); ++ } ++ ++ constexpr uint64_t MaxIoVectors = 1024; ++ ++ enum class VectorKind : uint8_t { ++ None, ++ Io, ++ SentMessage, ++ ReceivedMessage, ++ SentMessageArray, ++ ReceivedMessageArray, ++ IoSubmit, ++ IoEvents, ++ PageList, ++ FutexWaiters, ++ FutexRequeue, ++ FileControl, ++ Capabilities, ++ PerfAttribute, ++ SchedulerAttribute, ++ HandleAt, ++ OpenHandle, ++ MountRequest, ++ LandlockRule, ++ }; ++ ++ constexpr uint8_t BitmapElements = 0xff; ++ constexpr uint8_t MessageElements = 0xfe; ++ constexpr uint8_t PageElements = 0xfd; ++ ++ struct Layout { ++ uint8_t Pointers; ++ uint64_t Lengths; ++ VectorKind Vector {VectorKind::None}; ++ uint64_t ElementSizes {}; ++ uint64_t FixedSizes {}; ++ uint8_t Strings {}; ++ }; ++ ++ struct LayoutEntry { ++ uint32_t Syscall; ++ Layout Arguments; ++ }; ++ ++ constexpr uint8_t Ptr(uint32_t Arg) { ++ return 1U << Arg; ++ } ++ ++ constexpr uint64_t CountWord = 0x10; ++ constexpr uint64_t CountSigned = 0x20; ++ ++ constexpr uint64_t Sized(uint32_t Pointer, uint32_t Length) { ++ return static_cast(Length + 1) << (Pointer * 8); ++ } ++ ++ constexpr uint64_t IntSized(uint32_t Pointer, uint32_t Length) { ++ return Sized(Pointer, Length) | ((CountWord | CountSigned) << (Pointer * 8)); ++ } ++ ++ constexpr uint64_t UintSized(uint32_t Pointer, uint32_t Length) { ++ return Sized(Pointer, Length) | (CountWord << (Pointer * 8)); ++ } ++ ++ constexpr uint64_t LongSized(uint32_t Pointer, uint32_t Length) { ++ return Sized(Pointer, Length) | (CountSigned << (Pointer * 8)); ++ } ++ ++ constexpr uint64_t Through(uint32_t Pointer, uint32_t Length) { ++ return static_cast(Length + 9) << (Pointer * 8); ++ } ++ ++ constexpr uint32_t LengthArgument(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.Lengths >> (Pointer * 8)) & 0x7; ++ } ++ ++ constexpr bool LengthThroughPointer(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.Lengths >> (Pointer * 8)) & 0x8; ++ } ++ ++ constexpr uint64_t CountKind(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.Lengths >> (Pointer * 8)) & (CountWord | CountSigned); ++ } ++ ++ constexpr uint64_t CountValue(const Layout& Arguments, uint32_t Pointer, uint64_t Raw) { ++ const auto Kind = CountKind(Arguments, Pointer); ++ int64_t Value = static_cast(Raw); ++ if (Kind == (CountWord | CountSigned)) { ++ Value = static_cast(Raw); ++ } else if (Kind == CountWord) { ++ return static_cast(Raw); ++ } else if (Kind == 0) { ++ return Raw; ++ } ++ return Value < 0 ? 0 : static_cast(Value); ++ } ++ ++ constexpr uint64_t Fixed(uint32_t Pointer, uint64_t Bytes) { ++ return Bytes << (Pointer * 10); ++ } ++ ++ constexpr uint64_t FixedSize(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.FixedSizes >> (Pointer * 10)) & 0x3ff; ++ } ++ ++ constexpr uint8_t Text(uint32_t Arg) { ++ return 1U << Arg; ++ } ++ ++ constexpr uint64_t Each(uint32_t Pointer, uint8_t Size) { ++ return static_cast(Size) << (Pointer * 8); ++ } ++ ++ constexpr uint8_t ElementSize(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.ElementSizes >> (Pointer * 8)) & 0xff; ++ } ++ ++ constexpr uint64_t PollFdSize = 8; ++ constexpr uint64_t EpollEventSize = 12; ++ constexpr uint64_t GroupIdSize = 4; ++ constexpr uint64_t IntSize = 4; ++ constexpr uint64_t PointerSize = 8; ++ constexpr uint64_t SemaphoreOpSize = 6; ++ constexpr uint64_t IoEventSize = 32; ++ constexpr uint64_t FutexWaitSize = 24; ++ constexpr uint64_t StatSize = 144; ++ constexpr uint64_t StatfsSize = 120; ++ constexpr uint64_t StatxSize = 256; ++ constexpr uint64_t TimeSize = 16; ++ constexpr uint64_t TimePairSize = 32; ++ constexpr uint64_t TimezoneSize = 8; ++ constexpr uint64_t LongSize = 8; ++ constexpr uint64_t FdPairSize = 8; ++ constexpr uint64_t UtimbufSize = 16; ++ constexpr uint64_t SigactionSize = 32; ++ constexpr uint64_t SiginfoSize = 128; ++ constexpr uint64_t SigeventSize = 64; ++ constexpr uint64_t StackSize = 24; ++ constexpr uint64_t RlimitSize = 16; ++ constexpr uint64_t RusageSize = 144; ++ constexpr uint64_t SysinfoSize = 112; ++ constexpr uint64_t TmsSize = 32; ++ constexpr uint64_t UtsnameSize = 390; ++ constexpr uint64_t TimexSize = 208; ++ constexpr uint64_t UstatSize = 32; ++ constexpr uint64_t UserDescSize = 16; ++ constexpr uint64_t MqAttrSize = 64; ++ constexpr uint64_t IoControlBlockSize = 64; ++ constexpr uint64_t IoEventObjectOffset = 8; ++ constexpr uint64_t CapHeaderSize = 8; ++ constexpr uint64_t CapDataSize = 12; ++ constexpr uint32_t CapVersion1 = 0x19980330; ++ constexpr uint32_t CapVersion2 = 0x20071026; ++ constexpr uint32_t CapVersion3 = 0x20080522; ++ constexpr uint64_t FileLockSize = 32; ++ constexpr uint64_t IoUringParamsSize = 120; ++ constexpr uint64_t CachestatRangeSize = 16; ++ constexpr uint64_t CachestatSize = 40; ++ constexpr uint64_t LandlockPathRuleSize = 12; ++ constexpr uint64_t LandlockPortRuleSize = 16; ++ constexpr uint64_t KcmpSlotSize = 12; ++ constexpr uint64_t KexecSegmentSize = 32; ++ constexpr uint64_t SigsetArgumentSize = 16; ++ constexpr uint64_t SocketAddressSize = 128; ++ constexpr uint64_t MessageHeaderSize = 8; ++ constexpr uint64_t MaxString = 4096; ++ constexpr uint64_t StringChunk = 256; ++ constexpr uint64_t MaxPageList = 65536; ++ constexpr uint64_t MaxFutexWaiters = 128; ++ constexpr uint64_t MaxElements = 1ULL << 32; ++ ++ bool ByteLength(const Layout& Arguments, uint32_t Pointer, uint64_t Count, uint64_t* Bytes) { ++ const auto Size = ElementSize(Arguments, Pointer); ++ if (Size == 0) { ++ *Bytes = Count; ++ return true; ++ } ++ if (Size == BitmapElements) { ++ const auto Elements = static_cast(Count); ++ *Bytes = (static_cast(Elements) + 63) / 64 * 8; ++ return true; ++ } ++ if (Size == PageElements) { ++ *Bytes = Count / FEXCore::Utils::FEX_PAGE_SIZE + (Count % FEXCore::Utils::FEX_PAGE_SIZE != 0); ++ return true; ++ } ++ if (Count >= MaxElements) { ++ return false; ++ } ++ if (Size == MessageElements) { ++ *Bytes = Count + MessageHeaderSize; ++ return true; ++ } ++ *Bytes = Count * Size; ++ return true; ++ } ++ ++ constexpr LayoutEntry LayoutEntries[] = { ++ {x64::SYSCALL_x64_read, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_write, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_open, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_stat, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatSize), Text(0)}}, ++ {x64::SYSCALL_x64_fstat, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatSize)}}, ++ {x64::SYSCALL_x64_lstat, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatSize), Text(0)}}, ++ {x64::SYSCALL_x64_poll, {Ptr(0), UintSized(0, 1), VectorKind::None, Each(0, PollFdSize)}}, ++ {x64::SYSCALL_x64_rt_sigaction, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, SigactionSize) | Fixed(2, SigactionSize)}}, ++ {x64::SYSCALL_x64_rt_sigprocmask, {Ptr(1) | Ptr(2), Sized(1, 3) | Sized(2, 3)}}, ++ {x64::SYSCALL_x64_ioctl, {Ptr(2)}}, ++ {x64::SYSCALL_x64_pread_64, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_pwrite_64, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_readv, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_writev, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_access, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_pipe, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, FdPairSize)}}, ++ {x64::SYSCALL_x64_select, {Ptr(1) | Ptr(2) | Ptr(3) | Ptr(4), IntSized(1, 0) | IntSized(2, 0) | IntSized(3, 0), VectorKind::None, Each(1, BitmapElements) | Each(2, BitmapElements) | Each(3, BitmapElements), Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_msync, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_mincore, {Ptr(0) | Ptr(2), Sized(0, 1) | Sized(2, 1), VectorKind::None, Each(2, PageElements)}}, ++ {x64::SYSCALL_x64_shmctl, {Ptr(2)}}, ++ {x64::SYSCALL_x64_nanosleep, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, TimeSize) | Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_getitimer, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize)}}, ++ {x64::SYSCALL_x64_setitimer, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, TimePairSize) | Fixed(2, TimePairSize)}}, ++ {x64::SYSCALL_x64_sendfile, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, LongSize)}}, ++ {x64::SYSCALL_x64_connect, {Ptr(1), IntSized(1, 2)}}, ++ {x64::SYSCALL_x64_accept, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_sendto, {Ptr(1) | Ptr(4), Sized(1, 2) | IntSized(4, 5)}}, ++ {x64::SYSCALL_x64_recvfrom, {Ptr(1) | Ptr(4) | Ptr(5), Sized(1, 2) | Through(4, 5), VectorKind::None, 0, Fixed(4, SocketAddressSize) | Fixed(5, IntSize)}}, ++ {x64::SYSCALL_x64_sendmsg, {0, 0, VectorKind::SentMessage}}, ++ {x64::SYSCALL_x64_recvmsg, {0, 0, VectorKind::ReceivedMessage}}, ++ {x64::SYSCALL_x64_bind, {Ptr(1), IntSized(1, 2)}}, ++ {x64::SYSCALL_x64_getsockname, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_getpeername, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_socketpair, {Ptr(3), 0, VectorKind::None, 0, Fixed(3, FdPairSize)}}, ++ {x64::SYSCALL_x64_setsockopt, {Ptr(3), IntSized(3, 4)}}, ++ {x64::SYSCALL_x64_getsockopt, {Ptr(3) | Ptr(4), Through(3, 4), VectorKind::None, 0, Fixed(4, IntSize)}}, ++ {x64::SYSCALL_x64_execve, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_wait4, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(1, IntSize) | Fixed(3, RusageSize)}}, ++ {x64::SYSCALL_x64_uname, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, UtsnameSize)}}, ++ {x64::SYSCALL_x64_semop, {Ptr(1), UintSized(1, 2), VectorKind::None, Each(1, SemaphoreOpSize)}}, ++ {x64::SYSCALL_x64_semctl, {Ptr(3)}}, ++ {x64::SYSCALL_x64_msgsnd, {Ptr(1), Sized(1, 2), VectorKind::None, Each(1, MessageElements)}}, ++ {x64::SYSCALL_x64_msgrcv, {Ptr(1), Sized(1, 2), VectorKind::None, Each(1, MessageElements)}}, ++ {x64::SYSCALL_x64_msgctl, {Ptr(2)}}, ++ {x64::SYSCALL_x64_fcntl, {0, 0, VectorKind::FileControl}}, ++ {x64::SYSCALL_x64_truncate, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_getdents, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_getcwd, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_chdir, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_rename, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_mkdir, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_rmdir, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_creat, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_link, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_unlink, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_symlink, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_readlink, {Ptr(0) | Ptr(1), IntSized(1, 2), VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_chmod, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_chown, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_lchown, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_gettimeofday, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, TimeSize) | Fixed(1, TimezoneSize)}}, ++ {x64::SYSCALL_x64_getrlimit, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, RlimitSize)}}, ++ {x64::SYSCALL_x64_getrusage, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, RusageSize)}}, ++ {x64::SYSCALL_x64_sysinfo, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, SysinfoSize)}}, ++ {x64::SYSCALL_x64_times, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, TmsSize)}}, ++ {x64::SYSCALL_x64_syslog, {Ptr(1), IntSized(1, 2)}}, ++ {x64::SYSCALL_x64_getgroups, {Ptr(1), IntSized(1, 0), VectorKind::None, Each(1, GroupIdSize)}}, ++ {x64::SYSCALL_x64_setgroups, {Ptr(1), IntSized(1, 0), VectorKind::None, Each(1, GroupIdSize)}}, ++ {x64::SYSCALL_x64_getresuid, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(1, IntSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_getresgid, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(1, IntSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_capget, {Ptr(0), 0, VectorKind::Capabilities, 0, Fixed(0, CapHeaderSize)}}, ++ {x64::SYSCALL_x64_capset, {Ptr(0), 0, VectorKind::Capabilities, 0, Fixed(0, CapHeaderSize)}}, ++ {x64::SYSCALL_x64_rt_sigpending, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_rt_sigtimedwait, {Ptr(0) | Ptr(1) | Ptr(2), Sized(0, 3), VectorKind::None, 0, Fixed(1, SiginfoSize) | Fixed(2, TimeSize)}}, ++ {x64::SYSCALL_x64_rt_sigqueueinfo, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, SiginfoSize)}}, ++ {x64::SYSCALL_x64_rt_sigsuspend, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_sigaltstack, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, StackSize) | Fixed(1, StackSize)}}, ++ {x64::SYSCALL_x64_utime, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, UtimbufSize), Text(0)}}, ++ {x64::SYSCALL_x64_mknod, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_uselib, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_ustat, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, UstatSize)}}, ++ {x64::SYSCALL_x64_statfs, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatfsSize), Text(0)}}, ++ {x64::SYSCALL_x64_fstatfs, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatfsSize)}}, ++ {x64::SYSCALL_x64_sysfs, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_sched_setparam, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_sched_getparam, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_sched_setscheduler, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_sched_rr_get_interval, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_mlock, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_munlock, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_modify_ldt, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_pivot_root, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64__sysctl, {Ptr(0)}}, ++ {x64::SYSCALL_x64_adjtimex, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, TimexSize)}}, ++ {x64::SYSCALL_x64_setrlimit, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, RlimitSize)}}, ++ {x64::SYSCALL_x64_chroot, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_acct, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_settimeofday, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, TimeSize) | Fixed(1, TimezoneSize)}}, ++ {x64::SYSCALL_x64_mount, {Ptr(0) | Ptr(1) | Ptr(2) | Ptr(4), 0, VectorKind::None, 0, 0, Text(0) | Text(1) | Text(2)}}, ++ {x64::SYSCALL_x64_umount2, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_swapon, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_swapoff, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_reboot, {Ptr(3), 0, VectorKind::None, 0, 0, Text(3)}}, ++ {x64::SYSCALL_x64_sethostname, {Ptr(0), IntSized(0, 1)}}, ++ {x64::SYSCALL_x64_setdomainname, {Ptr(0), IntSized(0, 1)}}, ++ {x64::SYSCALL_x64_create_module, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_init_module, {Ptr(0) | Ptr(2), Sized(0, 1), VectorKind::None, 0, 0, Text(2)}}, ++ {x64::SYSCALL_x64_delete_module, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_get_kernel_syms, {Ptr(0)}}, ++ {x64::SYSCALL_x64_query_module, {Ptr(0) | Ptr(2) | Ptr(4), Sized(2, 3)}}, ++ {x64::SYSCALL_x64_quotactl, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_nfsservctl, {Ptr(1) | Ptr(2)}}, ++ {x64::SYSCALL_x64_setxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_lsetxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_fsetxattr, {Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_getxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_lgetxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_fgetxattr, {Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_listxattr, {Ptr(0) | Ptr(1), Sized(1, 2), VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_llistxattr, {Ptr(0) | Ptr(1), Sized(1, 2), VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_flistxattr, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_removexattr, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_lremovexattr, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_fremovexattr, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_time, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, LongSize)}}, ++ {x64::SYSCALL_x64_futex, {Ptr(0) | Ptr(3) | Ptr(4), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(3, TimeSize) | Fixed(4, IntSize)}}, ++ {x64::SYSCALL_x64_sched_setaffinity, {Ptr(2), UintSized(2, 1)}}, ++ {x64::SYSCALL_x64_sched_getaffinity, {Ptr(2), UintSized(2, 1)}}, ++ {x64::SYSCALL_x64_set_thread_area, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, UserDescSize)}}, ++ {x64::SYSCALL_x64_io_setup, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, LongSize)}}, ++ {x64::SYSCALL_x64_io_getevents, {Ptr(3) | Ptr(4), LongSized(3, 2), VectorKind::IoEvents, Each(3, IoEventSize), Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_io_submit, {Ptr(2), LongSized(2, 1), VectorKind::IoSubmit, Each(2, PointerSize)}}, ++ {x64::SYSCALL_x64_io_cancel, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, IoControlBlockSize) | Fixed(2, IoEventSize)}}, ++ {x64::SYSCALL_x64_get_thread_area, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, UserDescSize)}}, ++ {x64::SYSCALL_x64_lookup_dcookie, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_remap_file_pages, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_getdents64, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_semtimedop, {Ptr(1) | Ptr(3), UintSized(1, 2), VectorKind::None, Each(1, SemaphoreOpSize), Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_timer_create, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, SigeventSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_timer_settime, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, TimePairSize) | Fixed(3, TimePairSize)}}, ++ {x64::SYSCALL_x64_timer_gettime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize)}}, ++ {x64::SYSCALL_x64_clock_settime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_clock_gettime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_clock_getres, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_clock_nanosleep, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, TimeSize) | Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_epoll_wait, {Ptr(1), IntSized(1, 2), VectorKind::None, Each(1, EpollEventSize)}}, ++ {x64::SYSCALL_x64_epoll_ctl, {Ptr(3), 0, VectorKind::None, 0, Fixed(3, EpollEventSize)}}, ++ {x64::SYSCALL_x64_utimes, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize), Text(0)}}, ++ {x64::SYSCALL_x64_mbind, {Ptr(0) | Ptr(3), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_set_mempolicy, {Ptr(1)}}, ++ {x64::SYSCALL_x64_get_mempolicy, {Ptr(0) | Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(0, IntSize)}}, ++ {x64::SYSCALL_x64_mq_open, {Ptr(0) | Ptr(3), 0, VectorKind::None, 0, Fixed(3, MqAttrSize), Text(0)}}, ++ {x64::SYSCALL_x64_mq_unlink, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_mq_timedsend, {Ptr(1) | Ptr(4), Sized(1, 2), VectorKind::None, 0, Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_mq_timedreceive, {Ptr(1) | Ptr(3) | Ptr(4), Sized(1, 2), VectorKind::None, 0, Fixed(3, IntSize) | Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_mq_notify, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, SigeventSize)}}, ++ {x64::SYSCALL_x64_mq_getsetattr, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, MqAttrSize) | Fixed(2, MqAttrSize)}}, ++ {x64::SYSCALL_x64_kexec_load, {Ptr(2), Sized(2, 1), VectorKind::None, Each(2, KexecSegmentSize)}}, ++ {x64::SYSCALL_x64_waitid, {Ptr(2) | Ptr(4), 0, VectorKind::None, 0, Fixed(2, SiginfoSize) | Fixed(4, RusageSize)}}, ++ {x64::SYSCALL_x64_add_key, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_request_key, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, 0, Text(0) | Text(1) | Text(2)}}, ++ {x64::SYSCALL_x64_keyctl, {Ptr(1) | Ptr(2) | Ptr(3) | Ptr(4)}}, ++ {x64::SYSCALL_x64_inotify_add_watch, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_migrate_pages, {Ptr(2) | Ptr(3)}}, ++ {x64::SYSCALL_x64_openat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_mkdirat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_mknodat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_fchownat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_futimesat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(2, TimePairSize), Text(1)}}, ++ {x64::SYSCALL_x64_newfstatat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(2, StatSize), Text(1)}}, ++ {x64::SYSCALL_x64_unlinkat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_renameat, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_linkat, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_symlinkat, {Ptr(0) | Ptr(2), 0, VectorKind::None, 0, 0, Text(0) | Text(2)}}, ++ {x64::SYSCALL_x64_readlinkat, {Ptr(1) | Ptr(2), IntSized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_fchmodat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_faccessat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_pselect6, {Ptr(1) | Ptr(2) | Ptr(3) | Ptr(4) | Ptr(5), IntSized(1, 0) | IntSized(2, 0) | IntSized(3, 0), VectorKind::None, Each(1, BitmapElements) | Each(2, BitmapElements) | Each(3, BitmapElements), Fixed(4, TimeSize) | Fixed(5, SigsetArgumentSize)}}, ++ {x64::SYSCALL_x64_ppoll, {Ptr(0) | Ptr(2) | Ptr(3), UintSized(0, 1) | Sized(3, 4), VectorKind::None, Each(0, PollFdSize), Fixed(2, TimeSize)}}, ++ {x64::SYSCALL_x64_get_robust_list, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, PointerSize) | Fixed(2, PointerSize)}}, ++ {x64::SYSCALL_x64_splice, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(1, LongSize) | Fixed(3, LongSize)}}, ++ {x64::SYSCALL_x64_vmsplice, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_move_pages, {Ptr(2) | Ptr(3) | Ptr(4), Sized(2, 1) | Sized(3, 1) | Sized(4, 1), VectorKind::PageList, Each(2, PointerSize) | Each(3, IntSize) | Each(4, IntSize)}}, ++ {x64::SYSCALL_x64_utimensat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(2, TimePairSize), Text(1)}}, ++ {x64::SYSCALL_x64_epoll_pwait, {Ptr(1) | Ptr(4), IntSized(1, 2) | Sized(4, 5), VectorKind::None, Each(1, EpollEventSize)}}, ++ {x64::SYSCALL_x64_signalfd, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_timerfd_settime, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, TimePairSize) | Fixed(3, TimePairSize)}}, ++ {x64::SYSCALL_x64_timerfd_gettime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize)}}, ++ {x64::SYSCALL_x64_accept4, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_signalfd4, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_pipe2, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, FdPairSize)}}, ++ {x64::SYSCALL_x64_preadv, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_pwritev, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_rt_tgsigqueueinfo, {Ptr(3), 0, VectorKind::None, 0, Fixed(3, SiginfoSize)}}, ++ {x64::SYSCALL_x64_perf_event_open, {0, 0, VectorKind::PerfAttribute}}, ++ {x64::SYSCALL_x64_recvmmsg, {Ptr(4), 0, VectorKind::ReceivedMessageArray, 0, Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_fanotify_mark, {Ptr(4), 0, VectorKind::None, 0, 0, Text(4)}}, ++ {x64::SYSCALL_x64_prlimit_64, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, RlimitSize) | Fixed(3, RlimitSize)}}, ++ {x64::SYSCALL_x64_name_to_handle_at, {Ptr(1) | Ptr(3), 0, VectorKind::HandleAt, 0, Fixed(3, IntSize), Text(1)}}, ++ {x64::SYSCALL_x64_open_by_handle_at, {0, 0, VectorKind::OpenHandle}}, ++ {x64::SYSCALL_x64_clock_adjtime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimexSize)}}, ++ {x64::SYSCALL_x64_sendmmsg, {0, 0, VectorKind::SentMessageArray}}, ++ {x64::SYSCALL_x64_getcpu, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_kcmp, {Ptr(4), 0, VectorKind::None, 0, Fixed(4, KcmpSlotSize)}}, ++ {x64::SYSCALL_x64_finit_module, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_sched_setattr, {0, 0, VectorKind::SchedulerAttribute}}, ++ {x64::SYSCALL_x64_sched_getattr, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_renameat2, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_seccomp, {Ptr(2)}}, ++ {x64::SYSCALL_x64_getrandom, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_memfd_create, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_kexec_file_load, {Ptr(3), Sized(3, 2)}}, ++ {x64::SYSCALL_x64_bpf, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_execveat, {Ptr(1) | Ptr(2) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_mlock2, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_copy_file_range, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(1, LongSize) | Fixed(3, LongSize)}}, ++ {x64::SYSCALL_x64_preadv2, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_pwritev2, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_pkey_mprotect, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_statx, {Ptr(1) | Ptr(4), 0, VectorKind::None, 0, Fixed(4, StatxSize), Text(1)}}, ++ {x64::SYSCALL_x64_io_pgetevents, {Ptr(3) | Ptr(4) | Ptr(5), LongSized(3, 2), VectorKind::IoEvents, Each(3, IoEventSize), Fixed(4, TimeSize) | Fixed(5, SigsetArgumentSize)}}, ++ {x64::SYSCALL_x64_rseq, {Ptr(0), UintSized(0, 1)}}, ++ {x64::SYSCALL_x64_pidfd_send_signal, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, SiginfoSize)}}, ++ {x64::SYSCALL_x64_io_uring_setup, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, IoUringParamsSize)}}, ++ {x64::SYSCALL_x64_io_uring_enter, {Ptr(4), Sized(4, 5)}}, ++ {x64::SYSCALL_x64_io_uring_register, {Ptr(2)}}, ++ {x64::SYSCALL_x64_open_tree, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_move_mount, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_fsopen, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_fsconfig, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, 0, Text(2)}}, ++ {x64::SYSCALL_x64_fspick, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_openat2, {Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_faccessat2, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_process_madvise, {Ptr(1)}}, ++ {x64::SYSCALL_x64_epoll_pwait2, {Ptr(1) | Ptr(3) | Ptr(4), IntSized(1, 2) | Sized(4, 5), VectorKind::None, Each(1, EpollEventSize), Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_mount_setattr, {Ptr(1) | Ptr(3), Sized(3, 4), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_quotactl_fd, {Ptr(3)}}, ++ {x64::SYSCALL_x64_landlock_create_ruleset, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_landlock_add_rule, {0, 0, VectorKind::LandlockRule}}, ++ {x64::SYSCALL_x64_futex_waitv, {Ptr(0) | Ptr(3), UintSized(0, 1), VectorKind::FutexWaiters, Each(0, FutexWaitSize), Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_set_mempolicy_home_node, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_cachestat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, CachestatRangeSize) | Fixed(2, CachestatSize)}}, ++ {x64::SYSCALL_x64_fchmodat2, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_futex_wake, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, IntSize)}}, ++ {x64::SYSCALL_x64_futex_wait, {Ptr(0) | Ptr(4), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_futex_requeue, {Ptr(0), 0, VectorKind::FutexRequeue, 0, Fixed(0, 2 * FutexWaitSize)}}, ++ {x64::SYSCALL_x64_statmount, {Ptr(1), Sized(1, 2), VectorKind::MountRequest}}, ++ {x64::SYSCALL_x64_listmount, {Ptr(1), Sized(1, 2), VectorKind::MountRequest, Each(1, PointerSize)}}, ++ {x64::SYSCALL_x64_lsm_get_self_attr, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_lsm_set_self_attr, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_lsm_list_modules, {Ptr(0) | Ptr(1), Through(0, 1), VectorKind::None, 0, Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_mseal, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_setxattrat, {Ptr(1) | Ptr(3) | Ptr(4), Sized(4, 5), VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_getxattrat, {Ptr(1) | Ptr(3) | Ptr(4), Sized(4, 5), VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_listxattrat, {Ptr(1) | Ptr(3), Sized(3, 4), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_removexattrat, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ }; ++ ++ constexpr uint32_t LayoutCount() { ++ uint32_t Max = 0; ++ for (const auto& Entry : LayoutEntries) { ++ Max = std::max(Max, Entry.Syscall); ++ } ++ return Max + 1; ++ } ++ ++ constexpr std::array BuildLayouts() { ++ std::array Table {}; ++ for (const auto& Entry : LayoutEntries) { ++ Table[Entry.Syscall] = Entry.Arguments; ++ } ++ return Table; ++ } ++ ++ constexpr auto Layouts = BuildLayouts(); ++ ++ constexpr bool LayoutsAreConsistent() { ++ for (size_t i = 0; i < std::size(LayoutEntries); ++i) { ++ for (size_t j = i + 1; j < std::size(LayoutEntries); ++j) { ++ if (LayoutEntries[i].Syscall == LayoutEntries[j].Syscall) { ++ return false; ++ } ++ } ++ const auto& Arguments = LayoutEntries[i].Arguments; ++ if ((Arguments.Strings & ~Arguments.Pointers) != 0) { ++ return false; ++ } ++ for (uint32_t Arg = 0; Arg < 6; ++Arg) { ++ const bool Pointer = Arguments.Pointers & Ptr(Arg); ++ const auto Length = LengthArgument(Arguments, Arg); ++ const bool Indirect = LengthThroughPointer(Arguments, Arg); ++ const auto Bytes = FixedSize(Arguments, Arg); ++ const bool String = Arguments.Strings & Ptr(Arg); ++ const bool Elements = ElementSize(Arguments, Arg) != 0; ++ if (CountKind(Arguments, Arg) != 0 && (Length == 0 || Indirect)) { ++ return false; ++ } ++ if (!Pointer && (Length != 0 || Indirect || Bytes != 0 || Elements)) { ++ return false; ++ } ++ if (String && (Length != 0 || Indirect || Bytes != 0)) { ++ return false; ++ } ++ if (Elements && (Length == 0 || Indirect)) { ++ return false; ++ } ++ if (Length == 0) { ++ if (Indirect) { ++ return false; ++ } ++ continue; ++ } ++ if (Length > 6) { ++ return false; ++ } ++ const bool Target = Arguments.Pointers & Ptr(Length - 1); ++ if (Indirect ? !Target : (Target || Bytes != 0)) { ++ return false; ++ } ++ } ++ } ++ return true; ++ } ++ ++ constexpr bool LeavesUntranslated(std::initializer_list Syscalls) { ++ for (const auto Syscall : Syscalls) { ++ if (Syscall < Layouts.size() && (Layouts[Syscall].Pointers != 0 || Layouts[Syscall].Vector != VectorKind::None)) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ static_assert(LayoutsAreConsistent()); ++ static_assert(LeavesUntranslated({ ++ x64::SYSCALL_x64_mmap, ++ x64::SYSCALL_x64_mprotect, ++ x64::SYSCALL_x64_munmap, ++ x64::SYSCALL_x64_brk, ++ x64::SYSCALL_x64_rt_sigreturn, ++ x64::SYSCALL_x64_mremap, ++ x64::SYSCALL_x64_madvise, ++ x64::SYSCALL_x64_shmat, ++ x64::SYSCALL_x64_clone, ++ x64::SYSCALL_x64_shmdt, ++ x64::SYSCALL_x64_ptrace, ++ x64::SYSCALL_x64_prctl, ++ x64::SYSCALL_x64_arch_prctl, ++ x64::SYSCALL_x64_set_tid_address, ++ x64::SYSCALL_x64_set_robust_list, ++ x64::SYSCALL_x64_process_vm_readv, ++ x64::SYSCALL_x64_process_vm_writev, ++ x64::SYSCALL_x64_clone3, ++ x64::SYSCALL_x64_map_shadow_stack, ++ })); ++ ++ struct iovec* VectorCopy(ArgumentStorage* Storage, uint64_t Entries) { ++ if (Entries <= std::size(Storage->Inline)) { ++ return Storage->Inline; ++ } ++ Storage->Heap.resize(std::min(Entries, MaxIoVectors)); ++ return Storage->Heap.data(); ++ } ++ ++ uint64_t TranslateIoVector(uint64_t Vector, uint64_t Entries, struct iovec* Copy, uint64_t* Out, bool* Copied = nullptr) { ++ if (Entries == 0 || Entries > MaxIoVectors) { ++ return 0; ++ } ++ const auto Bytes = Entries * sizeof(struct iovec); ++ uint64_t HostVector {}; ++ if (!TranslateRange(Vector, Bytes, &HostVector)) { ++ return -EFAULT; ++ } ++ *Out = HostVector; ++ if (FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(HostVector), Bytes) != 0) { ++ return 0; ++ } ++ if (Copied) { ++ *Copied = true; ++ } ++ bool Changed = false; ++ for (uint64_t i = 0; i < Entries; ++i) { ++ const auto Base = reinterpret_cast(Copy[i].iov_base); ++ uint64_t Host {}; ++ if (!TranslateRange(Base, Copy[i].iov_len, &Host)) { ++ return -EFAULT; ++ } ++ if (Host != Base) { ++ Copy[i].iov_base = reinterpret_cast(Host); ++ Changed = true; ++ } ++ } ++ if (Changed) { ++ *Out = reinterpret_cast(Copy); ++ } ++ return 0; ++ } ++ ++ uint64_t TranslateMessageFields(struct msghdr* Message, struct iovec* Copy, bool* Changed, bool* Copied = nullptr) { ++ const auto Name = reinterpret_cast(Message->msg_name); ++ const auto Control = reinterpret_cast(Message->msg_control); ++ const auto Vector = reinterpret_cast(Message->msg_iov); ++ uint64_t HostName {}; ++ uint64_t HostControl {}; ++ uint64_t HostVector = Vector; ++ if (!TranslateRange(Name, Message->msg_namelen, &HostName) || !TranslateRange(Control, Message->msg_controllen, &HostControl)) { ++ return -EFAULT; ++ } ++ if (const auto Result = TranslateIoVector(Vector, Message->msg_iovlen, Copy, &HostVector, Copied); Result != 0) { ++ return Result; ++ } ++ *Changed = HostName != Name || HostControl != Control || HostVector != Vector; ++ Message->msg_name = reinterpret_cast(HostName); ++ Message->msg_control = reinterpret_cast(HostControl); ++ Message->msg_iov = reinterpret_cast(HostVector); ++ return 0; ++ } ++ ++ uint64_t TranslateMessage(uint64_t* Header, bool Received, ArgumentStorage* Storage) { ++ const auto GuestHeader = *Header; ++ uint64_t HostHeader {}; ++ if (!TranslateRange(GuestHeader, sizeof(struct msghdr), &HostHeader)) { ++ return -EFAULT; ++ } ++ *Header = HostHeader; ++ auto* Message = &Storage->Message; ++ if (FaultSafeUserMemAccess::CopyFromUser(Message, reinterpret_cast(HostHeader), sizeof(*Message)) != 0) { ++ return 0; ++ } ++ bool Changed = false; ++ if (const auto Result = TranslateMessageFields(Message, VectorCopy(Storage, Message->msg_iovlen), &Changed); Result != 0 || !Changed) { ++ return Result; ++ } ++ if (Received) { ++ Storage->ReceivedHeader = GuestHeader; ++ } ++ *Header = reinterpret_cast(Message); ++ return 0; ++ } ++ ++ template ++ bool WithStableMapping(uint64_t Address, Fn&& Body) { ++ auto* Thread = Contains(Address) ? FEX::HLE::ThreadManager::GetCurrentThreadObject() : nullptr; ++ if (Thread == nullptr || Thread->HighMemoryTrap.Mappings.Held) { ++ return Body(); ++ } ++ MappingHold Hold {Thread->HighMemoryTrap.Mappings, true}; ++ return Body(); ++ } ++ ++ bool CopyToGuest(uint64_t Address, const void* Value, uint64_t Size) { ++ return WithStableMapping(Address, [&] { ++ uint64_t Host {}; ++ return TranslateRange(Address, Size, &Host) && FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Host), Value, Size) == 0; ++ }); ++ } ++ ++ uint64_t TranslateMessages(uint64_t* Args, bool Received, ArgumentStorage* Storage) { ++ auto* Array = &Args[1]; ++ auto* Entries = &Args[2]; ++ const uint64_t Messages = std::min(static_cast(*Entries), MaxIoVectors); ++ if (Messages == 0) { ++ return 0; ++ } ++ constexpr uint64_t Size = sizeof(struct mmsghdr); ++ const auto GuestArray = *Array; ++ uint64_t HostArray {}; ++ if (!TranslateRange(GuestArray, Size, &HostArray)) { ++ return -EFAULT; ++ } ++ Storage->Messages.resize(Messages); ++ auto* Copy = Storage->Messages.data(); ++ uint64_t Ready = 0; ++ bool Contiguous = true; ++ uint64_t Whole {}; ++ if (TranslateRange(GuestArray, Messages * Size, &Whole) && ++ FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(Whole), Messages * Size) == 0) { ++ Ready = Messages; ++ } else { ++ for (; Ready < Messages; ++Ready) { ++ uint64_t Host {}; ++ if (!TranslateRange(GuestArray + Ready * Size, Size, &Host) || ++ FaultSafeUserMemAccess::CopyFromUser(&Copy[Ready], reinterpret_cast(Host), Size) != 0) { ++ break; ++ } ++ Contiguous = Contiguous && Host == HostArray + Ready * Size; ++ } ++ } ++ if (Ready == 0) { ++ *Array = HostArray; ++ return 0; ++ } ++ uint64_t Vectors = 0; ++ for (uint64_t i = 0; i < Ready; ++i) { ++ if (Copy[i].msg_hdr.msg_iovlen <= MaxIoVectors) { ++ Vectors += Copy[i].msg_hdr.msg_iovlen; ++ } ++ } ++ Storage->Heap.resize(Vectors); ++ Storage->MessageLengths.assign(Ready, 0); ++ bool Changed = !Contiguous; ++ uint64_t Offset = 0; ++ for (uint64_t i = 0; i < Ready; ++i) { ++ const auto Length = Copy[i].msg_hdr.msg_iovlen; ++ auto* Local = Storage->Heap.data() + Offset; ++ bool Translated = false; ++ bool Copied = false; ++ if (const auto Result = TranslateMessageFields(&Copy[i].msg_hdr, Local, &Translated, &Copied); Result != 0) { ++ if (i == 0) { ++ return Result; ++ } ++ Ready = i; ++ break; ++ } ++ if (!Received && Length != 0 && !Copied) { ++ if (i == 0) { ++ *Array = HostArray; ++ return 0; ++ } ++ Ready = i; ++ break; ++ } ++ if (Copied && !Received) { ++ Copy[i].msg_hdr.msg_iov = Local; ++ for (uint64_t j = 0; j < Length; ++j) { ++ Storage->MessageLengths[i] += Local[j].iov_len; ++ } ++ } ++ if (Length <= MaxIoVectors) { ++ Offset += Length; ++ } ++ Changed = Changed || Translated; ++ } ++ Storage->Messages.resize(Ready); ++ Storage->MessageLengths.resize(Ready); ++ if (!Changed) { ++ *Array = HostArray; ++ if (HostArray != GuestArray || Ready < static_cast(*Entries)) { ++ *Entries = Ready; ++ } ++ return 0; ++ } ++ *Array = reinterpret_cast(Copy); ++ *Entries = Received ? Ready : 1; ++ Storage->GuestMessages = GuestArray; ++ Storage->ReceivedMessages = Received; ++ Storage->SendFlags = static_cast(Args[3]); ++ if (!Received && Ready > 1) { ++ Storage->Socket = fcntl(static_cast(Args[0]), F_DUPFD_CLOEXEC, 0); ++ if (Storage->Socket >= 0) { ++ Args[0] = static_cast(Storage->Socket); ++ } ++ } ++ return 0; ++ } ++ ++ bool ReturnMessageFields(uint64_t Guest, const struct msghdr& Message) { ++ return (Message.msg_name == nullptr || ++ CopyToGuest(Guest + offsetof(struct msghdr, msg_namelen), &Message.msg_namelen, sizeof(Message.msg_namelen))) && ++ CopyToGuest(Guest + offsetof(struct msghdr, msg_flags), &Message.msg_flags, sizeof(Message.msg_flags)) && ++ CopyToGuest(Guest + offsetof(struct msghdr, msg_controllen), &Message.msg_controllen, sizeof(Message.msg_controllen)); ++ } ++ ++ uint64_t StringLength(uint64_t Address) { ++ uint64_t Length = 0; ++ while (Length < MaxString) { ++ const auto Here = Address + Length; ++ const auto Chunk = std::min({FEXCore::Utils::FEX_PAGE_SIZE - (Here & (FEXCore::Utils::FEX_PAGE_SIZE - 1)), MaxString - Length, StringChunk}); ++ char Chars[StringChunk]; ++ uint64_t Host {}; ++ if (!TranslateRange(Here, Chunk, &Host) || (Host == Here && Contains(Here)) || ++ FaultSafeUserMemAccess::CopyFromUser(Chars, reinterpret_cast(Host), Chunk) != 0) { ++ return Length + 1; ++ } ++ if (const auto* End = static_cast(memchr(Chars, 0, Chunk)); End != nullptr) { ++ return Length + (End - Chars) + 1; ++ } ++ Length += Chunk; ++ } ++ return MaxString; ++ } ++ ++ bool PointerLength(const Layout& Arguments, uint32_t Pointer, const uint64_t* Args, uint32_t NumArgs, uint64_t* Length) { ++ if (Arguments.Strings & Ptr(Pointer)) { ++ *Length = StringLength(Args[Pointer]); ++ return true; ++ } ++ const auto LengthArg = LengthArgument(Arguments, Pointer); ++ const auto Cap = FixedSize(Arguments, Pointer); ++ if (LengthArg == 0 || LengthArg > NumArgs) { ++ *Length = Cap; ++ return true; ++ } ++ const auto Source = Args[LengthArg - 1]; ++ if (!LengthThroughPointer(Arguments, Pointer)) { ++ return ByteLength(Arguments, Pointer, CountValue(Arguments, Pointer, Source), Length); ++ } ++ *Length = 0; ++ uint32_t Value {}; ++ uint64_t Host {}; ++ if (Source == 0 || !TranslateRange(Source, sizeof(Value), &Host) || ++ FaultSafeUserMemAccess::CopyFromUser(&Value, reinterpret_cast(Host), sizeof(Value)) != 0) { ++ return true; ++ } ++ *Length = Cap != 0 ? std::min(Value, Cap) : Value; ++ return true; ++ } ++ ++ uint64_t FileControlSize(uint64_t Command) { ++ switch (static_cast(Command)) { ++ case F_GETLK: ++ case F_SETLK: ++ case F_SETLKW: ++ case F_OFD_GETLK: ++ case F_OFD_SETLK: ++ case F_OFD_SETLKW: return FileLockSize; ++ case F_GETOWN_EX: ++ case F_SETOWN_EX: ++ case F_GET_RW_HINT: ++ case F_SET_RW_HINT: ++ case F_GET_FILE_RW_HINT: ++ case F_SET_FILE_RW_HINT: return LongSize; ++ default: return 0; ++ } ++ } ++ ++ struct IoControlBlock { ++ uint64_t Data; ++ uint32_t Key; ++ int32_t ReadWriteFlags; ++ uint16_t Opcode; ++ int16_t Priority; ++ uint32_t File; ++ uint64_t Buffer; ++ uint64_t Bytes; ++ int64_t Offset; ++ uint64_t Reserved; ++ uint32_t Flags; ++ uint32_t ResultFile; ++ }; ++ static_assert(sizeof(IoControlBlock) == IoControlBlockSize); ++ ++ constexpr uint16_t IoRead = 0; ++ constexpr uint16_t IoWrite = 1; ++ constexpr uint16_t IoReadVector = 7; ++ constexpr uint16_t IoWriteVector = 8; ++ ++ uint64_t TranslateIoBuffer(const IoControlBlock& Block, struct iovec* Copy, uint64_t* Out) { ++ *Out = Block.Buffer; ++ switch (Block.Opcode) { ++ case IoRead: ++ case IoWrite: return TranslateRange(Block.Buffer, Block.Bytes, Out) ? 0 : -EFAULT; ++ case IoReadVector: ++ case IoWriteVector: return TranslateIoVector(Block.Buffer, Block.Bytes, Copy, Out); ++ default: return 0; ++ } ++ } ++ ++ struct IoCopy { ++ IoControlBlock Block; ++ uint64_t Context; ++ uint64_t Guest; ++ uint64_t Generation; ++ bool Used; ++ }; ++ static_assert(offsetof(IoCopy, Block) == 0); ++ ++ constexpr size_t MaxIoCopies = 1024; ++ std::mutex IoCopyMutex; ++ std::array IoCopies {}; ++ size_t IoCopyNext {}; ++ std::atomic IoCopyCount {0}; ++ ++ struct AioContextState { ++ uint64_t Generation; ++ uint64_t Active; ++ bool Live; ++ fextl::list> Batches; ++ }; ++ ++ using AioContextTable = fextl::unordered_map; ++ ++ AioContextTable& AioContextsLocked() { ++ static auto* Table = fextl::make_unique().release(); ++ return *Table; ++ } ++ ++ uint64_t AioGeneration {}; ++ ++ uint64_t ContextGenerationLocked(uint64_t Context) { ++ const auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ return Found == Table.end() ? AioGeneration : Found->second.Generation; ++ } ++ ++ IoCopy* FindIoCopyLocked(uint64_t Address) { ++ const auto First = reinterpret_cast(IoCopies.data()); ++ if (Address < First || Address - First >= sizeof(IoCopies) || (Address - First) % sizeof(IoCopy) != 0) { ++ return nullptr; ++ } ++ auto* Copy = &IoCopies[(Address - First) / sizeof(IoCopy)]; ++ return Copy->Used ? Copy : nullptr; ++ } ++ ++ void ReleaseIoCopyLocked(IoCopy* Copy) { ++ Copy->Used = false; ++ IoCopyCount.fetch_sub(1, std::memory_order_release); ++ } ++ ++ uint64_t ClaimIoCopy(const IoControlBlock& Block, uint64_t Context, uint64_t Guest) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (size_t Tried = 0; Tried < MaxIoCopies; ++Tried) { ++ auto& Copy = IoCopies[IoCopyNext]; ++ IoCopyNext = (IoCopyNext + 1) % MaxIoCopies; ++ if (!Copy.Used) { ++ Copy = {Block, Context, Guest, ContextGenerationLocked(Context), true}; ++ IoCopyCount.fetch_add(1, std::memory_order_release); ++ return reinterpret_cast(&Copy); ++ } ++ } ++ return 0; ++ } ++ ++ void ReleaseIoCopies(const uint64_t* Copies, uint64_t Entries) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (uint64_t i = 0; i < Entries; ++i) { ++ if (auto* Copy = Copies[i] ? FindIoCopyLocked(Copies[i]) : nullptr) { ++ ReleaseIoCopyLocked(Copy); ++ } ++ } ++ } ++ ++ uint64_t ContextGeneration(uint64_t Context) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ return ContextGenerationLocked(Context); ++ } ++ ++ void ReleaseContext(uint64_t Context, uint64_t Generation) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (auto& Copy : IoCopies) { ++ if (Copy.Used && Copy.Context == Context && Copy.Generation <= Generation) { ++ ReleaseIoCopyLocked(&Copy); ++ } ++ } ++ auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ if (Found != Table.end() && Found->second.Generation <= Generation) { ++ Table.erase(Found); ++ } ++ } ++ ++ uint64_t BeginContext(uint64_t Context) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& Table = AioContextsLocked(); ++ Table.erase(Context); ++ Table[Context] = {++AioGeneration, 0, true, {}}; ++ return AioGeneration; ++ } ++ ++ uint64_t ReportedObject(uint64_t Object) { ++ if (IoCopyCount.load(std::memory_order_acquire) != 0) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ if (auto* Copy = FindIoCopyLocked(Object)) { ++ const auto Guest = Copy->Guest; ++ ReleaseIoCopyLocked(Copy); ++ return Guest; ++ } ++ } ++ return ToGuest(Object); ++ } ++ ++ uint64_t CancelTarget(uint64_t Context, uint64_t Guest, uint64_t Host) { ++ uint32_t Key {}; ++ if (IoCopyCount.load(std::memory_order_acquire) == 0 || ++ FaultSafeUserMemAccess::CopyFromUser(&Key, reinterpret_cast(Host + offsetof(IoControlBlock, Key)), sizeof(Key)) != 0 || ++ Key != 0) { ++ return Host; ++ } ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (auto& Copy : IoCopies) { ++ if (Copy.Used && Copy.Context == Context && Copy.Guest == Guest) { ++ return reinterpret_cast(&Copy); ++ } ++ } ++ return Host; ++ } ++ ++ constexpr uint64_t MaxIoEvents = 65536; ++ constexpr uint64_t IoEventWords = IoEventSize / sizeof(uint64_t); ++ constexpr uint64_t AioRingMagicOffset = 16; ++ constexpr uint32_t AioRingMagic = 0xa10a10a1; ++ ++ constexpr int64_t NanosPerSecond = 1'000'000'000; ++ constexpr int64_t ReapSlice = 20'000'000; ++ constexpr int64_t MaxWaitSeconds = 1LL << 32; ++ ++ struct StashTicket { ++ uint64_t Taken; ++ uint64_t Generation; ++ }; ++ ++ uint64_t TakeEventsLocked(AioContextState& State, uint64_t* Words, uint64_t Events) { ++ uint64_t Taken = 0; ++ while (Taken < Events && !State.Batches.empty()) { ++ auto& Batch = State.Batches.front(); ++ const auto Count = std::min(Batch.size() / IoEventWords, Events - Taken); ++ std::copy_n(Batch.begin(), Count * IoEventWords, Words + Taken * IoEventWords); ++ Taken += Count; ++ if (Count * IoEventWords == Batch.size()) { ++ State.Batches.pop_front(); ++ } else { ++ Batch.erase(Batch.begin(), Batch.begin() + Count * IoEventWords); ++ } ++ } ++ return Taken; ++ } ++ ++ StashTicket ReserveEvents(uint64_t Context, uint64_t* Words, uint64_t Events, bool Take) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& State = AioContextsLocked()[Context]; ++ if (State.Generation == 0) { ++ State.Generation = ++AioGeneration; ++ } ++ ++State.Active; ++ return {Take ? TakeEventsLocked(State, Words, Events) : 0, State.Generation}; ++ } ++ ++ uint64_t TopUpEvents(uint64_t Context, uint64_t Generation, uint64_t* Words, uint64_t Events) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ if (Found == Table.end() || Found->second.Generation != Generation) { ++ return 0; ++ } ++ return TakeEventsLocked(Found->second, Words, Events); ++ } ++ ++ void SettleEvents(uint64_t Context, uint64_t Generation, ArgumentStorage* Storage, uint64_t Kept, bool Forget) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ if (Found == Table.end() || Found->second.Generation != Generation) { ++ return; ++ } ++ auto& State = Found->second; ++ --State.Active; ++ if (Kept != 0) { ++ auto& Batch = Storage->Recovery.front(); ++ Batch.swap(Storage->EventBuffer); ++ Batch.resize(Kept * IoEventWords); ++ State.Batches.splice(State.Batches.begin(), Storage->Recovery); ++ } ++ if (Forget && !State.Live && State.Active == 0 && State.Batches.empty()) { ++ Table.erase(Found); ++ } ++ } ++ ++ uint64_t WritableEvents(uint64_t Host, uint64_t Events) { ++ Events = std::min(Events, (~0ULL - Host) / IoEventSize); ++ const auto End = Host + Events * IoEventSize; ++ auto Probe = Host; ++ while (Probe < End) { ++ uint8_t Byte {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Byte, reinterpret_cast(Probe), sizeof(Byte)) != 0 || ++ FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Probe), &Byte, sizeof(Byte)) != 0) { ++ break; ++ } ++ Probe = (Probe | (FEXCore::Utils::FEX_PAGE_SIZE - 1)) + 1; ++ } ++ return (std::min(Probe, End) - Host) / IoEventSize; ++ } ++ ++ int64_t MonotonicNanos() { ++ struct timespec Now {}; ++ clock_gettime(CLOCK_MONOTONIC, &Now); ++ return Now.tv_sec * NanosPerSecond + Now.tv_nsec; ++ } ++ ++ void SetWait(ArgumentStorage* Storage, int64_t Left) { ++ const auto Wait = std::clamp(Left, 0, ReapSlice); ++ Storage->Wait[0] = Wait / NanosPerSecond; ++ Storage->Wait[1] = Wait % NanosPerSecond; ++ } ++ ++ bool StartWait(uint64_t Timeout, ArgumentStorage* Storage) { ++ int64_t Given[2] {}; ++ if (Timeout != 0 && (FaultSafeUserMemAccess::CopyFromUser(Given, reinterpret_cast(Timeout), sizeof(Given)) != 0 || ++ Given[0] < 0 || Given[1] < 0 || Given[1] >= NanosPerSecond)) { ++ return false; ++ } ++ const auto Now = MonotonicNanos(); ++ Storage->Deadline = Timeout != 0 && Given[0] < MaxWaitSeconds ? Now + Given[0] * NanosPerSecond + Given[1] : -1; ++ SetWait(Storage, Storage->Deadline < 0 ? ReapSlice : Storage->Deadline - Now); ++ Storage->Blocking = true; ++ return true; ++ } ++ ++ bool ContinueWait(ArgumentStorage* Storage) { ++ if (Storage->Deadline < 0) { ++ SetWait(Storage, ReapSlice); ++ return true; ++ } ++ const auto Left = Storage->Deadline - MonotonicNanos(); ++ SetWait(Storage, Left); ++ return Left > 0; ++ } ++ ++ uint64_t WaitForEvents(ArgumentStorage* Storage, uint64_t* Words, uint64_t Events, uint64_t Reaped) { ++ if (!FEX::HLE::ThreadManager::GetCurrentThreadObject()->SignalInfo.DeferredSignalFrames.empty()) { ++ return -EINTR; ++ } ++ const auto Result = ::syscall(Storage->EventSyscall, Storage->EventContext, Storage->Least - Reaped, Events - Reaped, ++ Words + Reaped * IoEventWords, Storage->Wait, Storage->EventMask); ++ return Result == -1 ? -errno : Result; ++ } ++ ++ uint64_t StartContext(uint64_t ContextPointer, uint64_t Ring) { ++ const auto Generation = BeginContext(Ring); ++ uint32_t Magic {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Magic, reinterpret_cast(Ring + AioRingMagicOffset), sizeof(Magic)) == 0 && ++ Magic == AioRingMagic) { ++ Magic = 0; ++ static_cast(FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Ring + AioRingMagicOffset), &Magic, sizeof(Magic))); ++ } ++ if (CopyToGuest(ContextPointer, &Ring, sizeof(Ring))) { ++ return 0; ++ } ++ static_cast(::syscall(SYS_io_destroy, Ring)); ++ ReleaseContext(Ring, Generation); ++ return -EFAULT; ++ } ++ ++ uint64_t TrackIoCopies(uint64_t Syscall, const uint64_t* Guest, uint64_t* Args, ArgumentStorage* Storage) { ++ switch (Syscall) { ++ case x64::SYSCALL_x64_io_setup: ++ if (FaultSafeUserMemAccess::CopyFromUser(&Storage->SetupId, reinterpret_cast(Args[1]), sizeof(Storage->SetupId)) != 0) { ++ return -EFAULT; ++ } ++ Storage->SetupContext = Guest[1]; ++ Args[1] = reinterpret_cast(&Storage->SetupId); ++ break; ++ case x64::SYSCALL_x64_io_getevents: ++ case x64::SYSCALL_x64_io_pgetevents: { ++ const auto Wanted = static_cast(Args[2]); ++ if (Wanted <= 0 || Guest[3] == 0) { ++ break; ++ } ++ const auto Events = std::max(WritableEvents(Args[3], std::min(Wanted, MaxIoEvents)), 1); ++ if (static_cast(Wanted) > Events) { ++ if (static_cast(Args[1]) > static_cast(Events) && static_cast(Args[1]) <= Wanted) { ++ Args[1] = Events; ++ } ++ Args[2] = Events; ++ } ++ Storage->EventBuffer.resize(Events * IoEventWords); ++ Storage->Recovery.emplace_back(); ++ Storage->Events = Guest[3]; ++ Storage->EventContext = Args[0]; ++ const auto Least = static_cast(Args[1]); ++ const bool Valid = Least >= 0 && Least <= static_cast(Events); ++ const auto Ticket = ReserveEvents(Args[0], Storage->EventBuffer.data(), Events, Valid); ++ Storage->Stashed = Ticket.Taken; ++ Storage->StashGeneration = Ticket.Generation; ++ if (Valid) { ++ Storage->Least = Least; ++ Args[1] = Ticket.Taken >= Storage->Least ? 0 : Storage->Least - Ticket.Taken; ++ if (Args[1] != 0 && StartWait(Args[4], Storage)) { ++ Storage->EventSyscall = Syscall == x64::SYSCALL_x64_io_pgetevents ? SYS_io_pgetevents : SYS_io_getevents; ++ Storage->EventMask = Args[5]; ++ Args[4] = reinterpret_cast(Storage->Wait); ++ } ++ } ++ Args[2] = Events - Ticket.Taken; ++ Args[3] = reinterpret_cast(Storage->EventBuffer.data() + Ticket.Taken * IoEventWords); ++ break; ++ } ++ case x64::SYSCALL_x64_io_cancel: Args[1] = CancelTarget(Args[0], Guest[1], Args[1]); break; ++ case x64::SYSCALL_x64_io_destroy: ++ Storage->DestroyedContext = Args[0]; ++ Storage->DestroyedGeneration = ContextGeneration(Args[0]); ++ Storage->Destroying = true; ++ break; ++ default: break; ++ } ++ return 0; ++ } ++ ++ uint64_t TranslateIoSubmit(uint64_t Context, uint64_t* Entries, uint64_t* Array, ArgumentStorage* Storage) { ++ const auto Requested = static_cast(*Entries); ++ if (Requested <= 0) { ++ return 0; ++ } ++ const auto Blocks = std::min(Requested, MaxIoVectors); ++ Storage->Words.resize(Blocks); ++ auto* List = Storage->Words.data(); ++ if (FaultSafeUserMemAccess::CopyFromUser(List, reinterpret_cast(*Array), Blocks * PointerSize) != 0) { ++ return 0; ++ } ++ Storage->IoCopies.reserve(Blocks); ++ Storage->IoKeys.reserve(Blocks); ++ Storage->IoKeyValues.reserve(Blocks); ++ bool Refused = false; ++ bool Changed = false; ++ uint64_t Vectors = 0; ++ uint64_t Usable = 0; ++ for (; Usable < Blocks; ++Usable) { ++ IoControlBlock Block {}; ++ uint64_t Host {}; ++ if (!TranslateRange(List[Usable], sizeof(Block), &Host) || ++ FaultSafeUserMemAccess::CopyFromUser(&Block, reinterpret_cast(Host), sizeof(Block)) != 0) { ++ break; ++ } ++ const bool Vectored = (Block.Opcode == IoReadVector || Block.Opcode == IoWriteVector) && Block.Bytes <= MaxIoVectors; ++ if (Vectored) { ++ if (Block.Bytes > MaxIoVectors - Vectors) { ++ break; ++ } ++ Storage->Heap.resize(MaxIoVectors); ++ } ++ uint64_t Buffer {}; ++ if (TranslateIoBuffer(Block, Storage->Heap.data() + Vectors, &Buffer) != 0) { ++ break; ++ } ++ uint64_t Submitted = Host; ++ if (Buffer != Block.Buffer) { ++ if (FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Host + offsetof(IoControlBlock, Key)), &Block.Key, sizeof(Block.Key)) != 0) { ++ Storage->IoCopies.push_back(0); ++ Storage->IoKeys.push_back(0); ++ Storage->IoKeyValues.push_back(Block.Key); ++ Changed = Changed || Host != List[Usable]; ++ List[Usable++] = Host; ++ break; ++ } ++ Block.Buffer = Buffer; ++ Submitted = ClaimIoCopy(Block, Context, List[Usable]); ++ if (Submitted == 0) { ++ Refused = true; ++ break; ++ } ++ } ++ if (Vectored) { ++ Vectors += Block.Bytes; ++ } ++ Storage->IoCopies.push_back(Submitted != Host ? Submitted : 0); ++ Storage->IoKeys.push_back(Submitted != Host ? List[Usable] + offsetof(IoControlBlock, Key) : 0); ++ Storage->IoKeyValues.push_back(Block.Key); ++ Changed = Changed || Submitted != List[Usable]; ++ List[Usable] = Submitted; ++ } ++ if (Usable == 0) { ++ return Refused ? -EAGAIN : -EFAULT; ++ } ++ if (Changed) { ++ *Array = reinterpret_cast(List); ++ } ++ *Entries = Usable; ++ return 0; ++ } ++ ++ uint64_t TranslatePageList(uint64_t* Args, ArgumentStorage* Storage) { ++ const auto Process = static_cast(Args[0]); ++ const auto Pages = Args[1]; ++ if ((Process != 0 && Process != getpid()) || Pages == 0 || Pages > MaxPageList) { ++ return 0; ++ } ++ Storage->Words.resize(Pages); ++ auto* List = Storage->Words.data(); ++ if (FaultSafeUserMemAccess::CopyFromUser(List, reinterpret_cast(Args[2]), Pages * PointerSize) != 0) { ++ return 0; ++ } ++ bool Changed = false; ++ for (uint64_t i = 0; i < Pages; ++i) { ++ uint64_t Host {}; ++ if (!TranslateRange(List[i], 1, &Host)) { ++ return -EFAULT; ++ } ++ Changed = Changed || Host != List[i]; ++ List[i] = Host; ++ } ++ if (Changed) { ++ Args[2] = reinterpret_cast(List); ++ } ++ return 0; ++ } ++ ++ struct EmbeddedSize { ++ uint64_t Offset; ++ uint64_t Header; ++ uint64_t Default; ++ uint64_t Minimum; ++ uint64_t Maximum; ++ }; ++ ++ constexpr EmbeddedSize PerfAttributeSize {4, 0, 64, 64, FEXCore::Utils::FEX_PAGE_SIZE}; ++ constexpr EmbeddedSize SchedulerAttributeSize {0, 0, 48, 48, FEXCore::Utils::FEX_PAGE_SIZE}; ++ constexpr EmbeddedSize FileHandleSize {0, 8, 0, 0, 128}; ++ constexpr EmbeddedSize MountRequestSize {0, 0, 0, 24, FEXCore::Utils::FEX_PAGE_SIZE}; ++ ++ uint64_t TranslateEmbedded(uint64_t* Argument, const EmbeddedSize& Rule) { ++ if (!Contains(*Argument)) { ++ return 0; ++ } ++ const uint64_t Field = Rule.Offset + sizeof(uint32_t); ++ uint64_t Host {}; ++ if (!TranslateRange(*Argument, Field, &Host)) { ++ return -EFAULT; ++ } ++ uint64_t Span = std::max(Field, Rule.Header); ++ uint32_t Raw {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Raw, reinterpret_cast(Host + Rule.Offset), sizeof(Raw)) == 0) { ++ const uint64_t Value = Raw == 0 ? Rule.Default : Raw; ++ if (Value >= Rule.Minimum && Value <= Rule.Maximum) { ++ Span = std::max(Field, Rule.Header + Value); ++ } ++ } ++ return TranslateRange(*Argument, Span, Argument) ? 0 : -EFAULT; ++ } ++ ++ uint64_t TranslateCapabilities(uint64_t* Header, uint64_t GuestHeader, uint64_t* Data, ArgumentStorage* Storage) { ++ if (!Contains(*Data)) { ++ return 0; ++ } ++ uint64_t Bytes = 0; ++ auto* Copy = Storage->CapabilityHeader; ++ if (FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(*Header), sizeof(Storage->CapabilityHeader)) == 0) { ++ const auto Version = Copy[0]; ++ Bytes = Version == CapVersion1 ? CapDataSize : (Version == CapVersion2 || Version == CapVersion3) ? 2 * CapDataSize : 0; ++ Storage->CapabilityVersion = Version; ++ Storage->GuestCapabilityHeader = GuestHeader; ++ *Header = reinterpret_cast(Copy); ++ } ++ return TranslateRange(*Data, Bytes, Data) ? 0 : -EFAULT; ++ } ++ ++ uint64_t TranslateLandlockRule(uint64_t Type, uint64_t* Rule) { ++ const uint64_t Bytes = Type == 1 ? LandlockPathRuleSize : Type == 2 ? LandlockPortRuleSize : 0; ++ return TranslateRange(*Rule, Bytes, Rule) ? 0 : -EFAULT; ++ } ++ ++ uint64_t TranslateWaiters(uint64_t* Waiters, uint64_t Entries, ArgumentStorage* Storage) { ++ constexpr uint64_t Words = FutexWaitSize / sizeof(uint64_t); ++ if (Entries == 0 || Entries > MaxFutexWaiters) { ++ return 0; ++ } ++ Storage->Words.resize(Entries * Words); ++ auto* Copy = Storage->Words.data(); ++ if (FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(*Waiters), Entries * FutexWaitSize) != 0) { ++ return 0; ++ } ++ bool Changed = false; ++ for (uint64_t i = 0; i < Entries; ++i) { ++ auto& Address = Copy[i * Words + 1]; ++ uint64_t Host {}; ++ if (!TranslateRange(Address, 1ULL << (Copy[i * Words + 2] & 3), &Host)) { ++ return -EFAULT; ++ } ++ Changed = Changed || Host != Address; ++ Address = Host; ++ } ++ if (Changed) { ++ *Waiters = reinterpret_cast(Copy); ++ } ++ return 0; ++ } ++} // namespace ++ ++bool Contains(uint64_t Address) { ++ return Address >= HostLimit() && Address < TaskTop; ++} ++ ++bool ClaimsMapping(uint64_t Address, uint64_t Length, int Flags) { ++ if (!(Flags & MAP_FIXED) || (Flags & MAP_FIXED_NOREPLACE) || Length == 0) { ++ return false; ++ } ++ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) { ++ return false; ++ } ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ return Contains(Address) && Size <= TaskTop - Address; ++} ++ ++uint64_t Map(uint64_t Address, uint64_t Length, int Prot, int Flags, int FD, off_t Offset) { ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ const int HostFlags = Flags & ~MAP_FIXED; ++ void* Host = MAP_FAILED; ++ if (const auto Hint = NeighbourHint(Address, Size); Hint != 0) { ++ Host = ::mmap(reinterpret_cast(Hint), Size, Prot, HostFlags | MAP_FIXED_NOREPLACE, FD, Offset); ++ } ++ if (Host == MAP_FAILED) { ++ Host = ::mmap(nullptr, Size, Prot, HostFlags, FD, Offset); ++ } ++ if (Host == MAP_FAILED) { ++ return -errno; ++ } ++ ++ BeginWrite(); ++ int Result = 0; ++ if (!HasRoomLocked(Address, Size, 1)) { ++ Result = -ENOMEM; ++ } else { ++ Result = UnmapLocked(Address, Size); ++ } ++ if (Result == 0 && !AddEntry(Address, Size, reinterpret_cast(Host), false, TrackedProt(Prot))) { ++ Result = -ENOMEM; ++ } ++ if (Result == 0) { ++ CoalesceLocked(Address, Address + Size); ++ } ++ EndWrite(); ++ if (Result != 0) { ++ ::munmap(Host, Size); ++ return Result; ++ } ++ return Address; ++} ++ ++uint64_t Unmap(uint64_t Address, uint64_t Length) { ++ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) { ++ return -EINVAL; ++ } ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (Size == 0 || Size > TaskTop - Address) { ++ return -EINVAL; ++ } ++ BeginWrite(); ++ const int Result = UnmapLocked(Address, Size); ++ EndWrite(); ++ return Result; ++} ++ ++uint64_t Protect(uint64_t Address, uint64_t Length, int Prot) { ++ BeginWrite(); ++ uint64_t Result = ApplyToRegionsLocked(Address, Length, -ENOMEM, [](void*, uint64_t, uint32_t) { return 0; }); ++ if (Result == 0) { ++ Result = SplitLocked(Address, Length); ++ } ++ if (Result == 0) { ++ Result = ApplyToRegionsLocked(Address, Length, -ENOMEM, [Prot](void* Host, uint64_t Size, uint32_t i) { ++ const int Applied = ::mprotect(Host, Size, Prot); ++ if (Applied == 0) { ++ Regions[i].Prot.store(TrackedProt(Prot), std::memory_order_relaxed); ++ } ++ return Applied; ++ }); ++ CoalesceLocked(Address, Address + std::min(FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE), TaskTop - Address)); ++ } ++ EndWrite(); ++ return Result; ++} ++ ++uint64_t Advise(uint64_t Address, uint64_t Length, int Advice, bool* Applied) { ++ *Applied = false; ++ return ApplyToRegionsLocked(Address, Length, -EINVAL, [Advice, Applied](void* Host, uint64_t Size, uint32_t) { ++ const int Result = ::madvise(Host, Size, Advice); ++ if (Result == 0) { ++ *Applied = true; ++ } ++ return Result; ++ }); ++} ++ ++bool DiscardsContents(int Advice) { ++ switch (Advice) { ++ case MADV_DONTNEED: ++ case MADV_FREE: ++ case MADV_REMOVE: ++ case MADV_DONTNEED_LOCKED: return true; ++ default: return false; ++ } ++} ++ ++uint64_t ToGuest(uint64_t Address) { ++ if (Count.load(std::memory_order_relaxed) == 0) [[likely]] { ++ return Address; ++ } ++ return ReadConsistent([&] { ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ if (Address >= Host && Address - Host < Size) { ++ return Regions[i].Guest.load(std::memory_order_relaxed) + (Address - Host); ++ } ++ } ++ return Address; ++ }); ++} ++ ++bool TranslateRange(uint64_t Address, uint64_t Length, uint64_t* Host) { ++ if (Count.load(std::memory_order_relaxed) == 0 || !Contains(Address)) [[likely]] { ++ *Host = Address; ++ return true; ++ } ++ return ReadConsistent([&] { return SpanLocked(Address, Length, Host); }); ++} ++ ++void MarkCode(uint64_t Address, uint64_t Length) { ++ const auto End = Address + Length; ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed); ++ if (RegionEnd > Address && Guest < End) { ++ Regions[i].Code.store(true, std::memory_order_relaxed); ++ } ++ } ++} ++ ++uint64_t TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t NumArgs, ArgumentStorage* Storage) { ++ if (Count.load(std::memory_order_relaxed) == 0) [[likely]] { ++ return TrackIoCopies(Syscall, Args, Args, Storage); ++ } ++ if (Syscall >= Layouts.size()) { ++ return 0; ++ } ++ const auto& Arguments = Layouts[Syscall]; ++ const auto Used = std::min(NumArgs, 6); ++ uint64_t Guest[6] {}; ++ std::copy_n(Args, Used, Guest); ++ uint64_t Lengths[6] {}; ++ for (uint32_t i = 0; i < Used; ++i) { ++ if ((Arguments.Pointers & Ptr(i)) && Contains(Args[i]) && !PointerLength(Arguments, i, Args, Used, &Lengths[i])) { ++ return -EFAULT; ++ } ++ } ++ for (uint32_t i = 0; i < Used; ++i) { ++ if ((Arguments.Pointers & Ptr(i)) && !TranslateRange(Args[i], Lengths[i], &Args[i])) { ++ return -EFAULT; ++ } ++ } ++ if (const auto Failed = TrackIoCopies(Syscall, Guest, Args, Storage); Failed != 0) { ++ return Failed; ++ } ++ if (Used < 6) { ++ return 0; ++ } ++ switch (Arguments.Vector) { ++ case VectorKind::Io: return TranslateIoVector(Args[1], Args[2], VectorCopy(Storage, Args[2]), &Args[1]); ++ case VectorKind::SentMessage: return TranslateMessage(&Args[1], false, Storage); ++ case VectorKind::ReceivedMessage: return TranslateMessage(&Args[1], true, Storage); ++ case VectorKind::SentMessageArray: return TranslateMessages(Args, false, Storage); ++ case VectorKind::ReceivedMessageArray: return TranslateMessages(Args, true, Storage); ++ case VectorKind::IoSubmit: return TranslateIoSubmit(Args[0], &Args[1], &Args[2], Storage); ++ case VectorKind::IoEvents: return 0; ++ case VectorKind::PageList: return TranslatePageList(Args, Storage); ++ case VectorKind::FutexWaiters: return TranslateWaiters(&Args[0], static_cast(Args[1]), Storage); ++ case VectorKind::FutexRequeue: return TranslateWaiters(&Args[0], 2, Storage); ++ case VectorKind::FileControl: return TranslateRange(Args[2], FileControlSize(Args[1]), &Args[2]) ? 0 : -EFAULT; ++ case VectorKind::Capabilities: return TranslateCapabilities(&Args[0], Guest[0], &Args[1], Storage); ++ case VectorKind::PerfAttribute: return TranslateEmbedded(&Args[0], PerfAttributeSize); ++ case VectorKind::SchedulerAttribute: return TranslateEmbedded(&Args[1], SchedulerAttributeSize); ++ case VectorKind::HandleAt: return TranslateEmbedded(&Args[2], FileHandleSize); ++ case VectorKind::OpenHandle: return TranslateEmbedded(&Args[1], FileHandleSize); ++ case VectorKind::MountRequest: return TranslateEmbedded(&Args[0], MountRequestSize); ++ case VectorKind::LandlockRule: return TranslateLandlockRule(static_cast(Args[1]), &Args[2]); ++ case VectorKind::None: break; ++ } ++ return 0; ++} ++ ++bool HoldsMappings(FEXCore::Core::InternalThreadState* Thread) { ++ return FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->HighMemoryTrap.Mappings.Held; ++} ++ ++uint64_t FinishSyscallArguments(uint64_t Result, ArgumentStorage* Storage) { ++ struct PinnedSocket { ++ int FD; ++ ~PinnedSocket() { ++ if (FD >= 0) { ++ close(FD); ++ } ++ } ++ } Socket {std::exchange(Storage->Socket, -1)}; ++ if (!Storage->IoCopies.empty()) { ++ const auto Submitted = FEX::HLE::HasSyscallError(Result) ? 0 : std::min(Result, Storage->IoCopies.size()); ++ const auto Examined = std::min(Submitted + 1, Storage->IoCopies.size()); ++ for (uint64_t i = 0; i < Examined; ++i) { ++ if (Storage->IoKeys[i] == 0) { ++ continue; ++ } ++ const uint32_t Key = i < Submitted ? 0 : reinterpret_cast(Storage->IoCopies[i])->Key; ++ if (Key != Storage->IoKeyValues[i]) { ++ static_cast(CopyToGuest(Storage->IoKeys[i], &Key, sizeof(Key))); ++ } ++ } ++ ReleaseIoCopies(Storage->IoCopies.data() + Submitted, Storage->IoCopies.size() - Submitted); ++ } ++ if (Storage->SetupContext != 0 && Result == 0) { ++ Result = StartContext(Storage->SetupContext, Storage->SetupId); ++ } ++ if (Storage->Destroying && Result == 0) { ++ ReleaseContext(Storage->DestroyedContext, Storage->DestroyedGeneration); ++ } ++ if (Storage->GuestCapabilityHeader != 0 && Storage->CapabilityHeader[0] != Storage->CapabilityVersion && ++ !CopyToGuest(Storage->GuestCapabilityHeader, &Storage->CapabilityHeader[0], sizeof(Storage->CapabilityHeader[0]))) { ++ return -EFAULT; ++ } ++ if (Storage->Events != 0) { ++ const auto Taken = Storage->Stashed; ++ auto* Words = Storage->EventBuffer.data(); ++ if (FEX::HLE::HasSyscallError(Result) && (Result != static_cast(-EINTR) || Taken == 0)) { ++ SettleEvents(Storage->EventContext, Storage->StashGeneration, Storage, Taken, Result == static_cast(-EINVAL)); ++ return Result; ++ } ++ const auto Events = Storage->EventBuffer.size() / IoEventWords; ++ auto Reaped = Taken; ++ while (!FEX::HLE::HasSyscallError(Result)) { ++ const auto Fresh = std::min(Result, Events - Reaped); ++ for (uint64_t i = Reaped; i < Reaped + Fresh; ++i) { ++ auto& Object = Words[i * IoEventWords + IoEventObjectOffset / sizeof(uint64_t)]; ++ Object = ReportedObject(Object); ++ } ++ Reaped += Fresh; ++ if (!Storage->Blocking || Reaped >= Storage->Least) { ++ break; ++ } ++ Reaped += TopUpEvents(Storage->EventContext, Storage->StashGeneration, Words + Reaped * IoEventWords, Events - Reaped); ++ if (Reaped >= Storage->Least || !ContinueWait(Storage)) { ++ break; ++ } ++ Result = WaitForEvents(Storage, Words, Events, Reaped); ++ if (FEX::HLE::HasSyscallError(Result) && Reaped == 0) { ++ SettleEvents(Storage->EventContext, Storage->StashGeneration, Storage, 0, Result == static_cast(-EINVAL)); ++ return Result; ++ } ++ } ++ const bool Delivered = Reaped == 0 || CopyToGuest(Storage->Events, Words, Reaped * IoEventSize); ++ SettleEvents(Storage->EventContext, Storage->StashGeneration, Storage, Delivered ? 0 : Reaped, false); ++ if (!Delivered) { ++ return -EFAULT; ++ } ++ Result = Reaped; ++ } ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return Result; ++ } ++ if (Storage->GuestMessages != 0) { ++ const bool FollowUps = !Storage->ReceivedMessages && Socket.FD >= 0; ++ const auto Total = FollowUps ? Storage->Messages.size() : std::min(Result, Storage->Messages.size()); ++ uint64_t Done = 0; ++ for (; Done < Total; ++Done) { ++ auto& Message = Storage->Messages[Done]; ++ if (Done >= Result && ::sendmmsg(Socket.FD, &Message, 1, Storage->SendFlags) != 1) { ++ break; ++ } ++ const auto Guest = Storage->GuestMessages + Done * sizeof(struct mmsghdr); ++ if ((Storage->ReceivedMessages && !ReturnMessageFields(Guest + offsetof(struct mmsghdr, msg_hdr), Message.msg_hdr)) || ++ !CopyToGuest(Guest + offsetof(struct mmsghdr, msg_len), &Message.msg_len, sizeof(Message.msg_len))) { ++ return Done == 0 ? -EFAULT : Done; ++ } ++ if (FollowUps && Message.msg_len < Storage->MessageLengths[Done]) { ++ return Done + 1; ++ } ++ } ++ return Done; ++ } ++ if (Storage->ReceivedHeader != 0 && !ReturnMessageFields(Storage->ReceivedHeader, Storage->Message)) { ++ return -EFAULT; ++ } ++ return Result; ++} ++ ++bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ auto* SigInfo = static_cast(Info); ++ const auto FaultAddress = reinterpret_cast(SigInfo->si_addr); ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ auto& Trap = ThreadObject->HighMemoryTrap; ++ const auto PC = ArchHelpers::Context::GetPc(UContext); ++ ++ if (DeferWhileHeld(Trap.Mappings, Signal, SigInfo)) { ++ return true; ++ } ++ if (Trap.Active && PC == reinterpret_cast(Trap.Code)) { ++ RedeliverFromTrap(Trap, SigInfo, UContext); ++ return false; ++ } ++ ++ if (SigInfo->si_code <= SI_USER || !Contains(FaultAddress) || Trap.Active || Trap.Mappings.Held) { ++ return false; ++ } ++ ++ const auto Insn = *reinterpret_cast(PC); ++ if (!IsLoadStore(Insn) || IsLiteralLoad(Insn) || RnField(Insn) == 31) { ++ return false; ++ } ++ ++ uint64_t Address {}; ++ uint32_t Size {}; ++ bool Plain {}; ++ if (!DecodeAccess(Insn, UContext, &Address, &Size, &Plain)) { ++ return false; ++ } ++ ++ MappingHold Hold {Trap.Mappings}; ++ AccessPiece Pieces[MaxAccessPieces] {}; ++ const auto Parts = ReadConsistent([&] { return PlanAccessLocked(Address, Size, Pieces); }); ++ if (Parts == 0) { ++ return false; ++ } ++ ++ const bool Write = IsWrite(Insn); ++ if (Write && std::any_of(Pieces, Pieces + Parts, [](const AccessPiece& Piece) { return Piece.Code; })) { ++ auto& VMATracking = FEX::HLE::_SyscallHandler->VMATracking; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ if (!Pieces[i].Code) { ++ continue; ++ } ++ const auto Last = Pieces[i].Guest + Pieces[i].Size - 1; ++ for (auto FaultBase = FEXCore::AlignDown(Pieces[i].Guest, FEXCore::Utils::FEX_PAGE_SIZE); FaultBase <= Last; ++ FaultBase += FEXCore::Utils::FEX_PAGE_SIZE) { ++ const auto Entry = VMATracking.FindVMAEntry(FaultBase); ++ if (Entry != VMATracking.VMAs.end()) { ++ FEX::HLE::SyscallHandler::InvalidateWrittenCodePage(Thread, FaultBase, Entry->first, Entry->second); ++ } else { ++ FEX::HLE::_SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE); ++ } ++ } ++ } ++ ++ constexpr uint64_t MaxStoreSize = 64; ++ const uint64_t StoreWindowStart = FaultAddress - MaxStoreSize; ++ auto CTX = Thread->CTX; ++ if (CTX->IsAddressInCodeBuffer(Thread, PC) && !CTX->IsCurrentBlockSingleInst(Thread) && ++ CTX->IsAddressInCurrentBlock(Thread, StoreWindowStart, 2 * MaxStoreSize)) { ++ ThreadObject->SignalInfo.Delegator->SpillSRA(Thread, UContext, Thread->CurrentFrame->InSyscallInfo & 0xFFFF); ++ const auto& Config = ThreadObject->SignalInfo.Delegator->GetConfig(); ++ ArchHelpers::Context::SetPc(UContext, Config.AbsoluteLoopTopAddressFillSRA); ++ ArchHelpers::Context::SetArmReg(UContext, 1, 1); ++ return true; ++ } ++ } ++ ++ if (IsExclusive(Insn)) { ++ if (Parts != 1 || !ExclusiveReachable(Insn, Pieces[0].Prot) || ++ !EmulateExclusive(Trap.Monitor, Insn, Pieces[0].Host, UContext)) { ++ return false; ++ } ++ ArchHelpers::Context::SetPc(UContext, PC + 4); ++ return true; ++ } ++ ++ const bool Bounced = !HostContiguous(Pieces, Parts); ++ if (Bounced && (!PiecesReachable(Pieces, Parts, Write) || (!Plain && !IsOrderedAccess(Insn)))) { ++ return false; ++ } ++ ++ const int Scratch = PickScratch(Insn); ++ if (Scratch < 0 || !EnsureTrapCode(Trap)) { ++ return false; ++ } ++ ++ Trap.Scratch = Scratch; ++ Trap.Base = RnField(Insn); ++ Trap.SavedScratch = ArchHelpers::Context::GetArmReg(UContext, Scratch); ++ Trap.BaseBefore = ArchHelpers::Context::GetArmReg(UContext, Trap.Base); ++ Trap.ResumePC = PC + 4; ++ Trap.Parts = 0; ++ Trap.Delta = Pieces[0].Host - Address; ++ ++ uint32_t Failed = Parts; ++ if (Bounced && !Plain) { ++ Failed = EmulateOrdered(Insn, Pieces, Parts, UContext); ++ if (Failed == Parts) { ++ ArchHelpers::Context::SetPc(UContext, PC + 4); ++ return true; ++ } ++ } else if (Bounced) { ++ Trap.BounceOffset = Address & 15; ++ Trap.Store = Write; ++ Trap.Parts = Parts; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ Trap.Pieces[i].Guest = Pieces[i].Guest; ++ Trap.Pieces[i].Host = Pieces[i].Host; ++ Trap.Pieces[i].Size = Pieces[i].Size; ++ } ++ auto* Window = Trap.Bounce + Trap.BounceOffset; ++ Failed = CopyPieces(Window, Trap.Pieces, Parts, true); ++ Trap.Delta = reinterpret_cast(Window) - Address; ++ } ++ ++ auto* Mask = &ArchHelpers::Context::GetUContext(UContext)->uc_sigmask; ++ memcpy(&Trap.SavedMask, Mask, sizeof(Trap.SavedMask)); ++ const uint64_t Blocked = ~HeldSignalMask(); ++ memcpy(Mask, &Blocked, sizeof(Blocked)); ++ if (Failed != Parts) { ++ ArmProbe(Trap, UContext, Pieces[Failed].Guest, Pieces[Failed].Host); ++ } else { ++ ArmTrap(Trap, UContext, (Insn & ~(0x1fU << 5)) | (static_cast(Scratch) << 5), Trap.BaseBefore + Trap.Delta, false); ++ } ++ Hold.Keep(); ++ return true; ++} ++ ++bool HandleBusFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ auto* SigInfo = static_cast(Info); ++ auto& Trap = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->HighMemoryTrap; ++ const auto PC = ArchHelpers::Context::GetPc(UContext); ++ if (DeferWhileHeld(Trap.Mappings, Signal, SigInfo)) { ++ return true; ++ } ++ if (Trap.Active && PC == reinterpret_cast(Trap.Code)) { ++ RedeliverFromTrap(Trap, SigInfo, UContext); ++ return false; ++ } ++ if (SigInfo->si_code <= SI_USER || !FaultSafeUserMemAccess::IsFaultLocation(PC)) { ++ return false; ++ } ++ ArchHelpers::Context::SetArmReg(UContext, 0, EFAULT); ++ ArchHelpers::Context::SetPc(UContext, ArchHelpers::Context::GetArmReg(UContext, 30)); ++ return true; ++} ++ ++bool HandleTrap(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ auto& Trap = ThreadObject->HighMemoryTrap; ++ auto* SigInfo = static_cast(Info); ++ if (DeferWhileHeld(Trap.Mappings, Signal, SigInfo)) { ++ return true; ++ } ++ if (!Trap.Active || SigInfo->si_code != TRAP_BRKPT || ArchHelpers::Context::GetPc(UContext) != reinterpret_cast(Trap.Code) + 4) { ++ return false; ++ } ++ ++ if (Trap.Probe) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch); ++ LeaveTrap(Trap, UContext, Trap.ResumePC - 4); ++ return true; ++ } ++ ++ const auto ScratchAfter = ArchHelpers::Context::GetArmReg(UContext, Trap.Scratch); ++ if (ScratchAfter != Trap.BaseBefore + Trap.Delta) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, ScratchAfter - Trap.Delta); ++ } ++ if (Trap.Parts != 0 && Trap.Store) { ++ const auto Failed = CopyPieces(Trap.Bounce + Trap.BounceOffset, Trap.Pieces, Trap.Parts, false); ++ if (Failed != Trap.Parts) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, Trap.BaseBefore); ++ ArmProbe(Trap, UContext, Trap.Pieces[Failed].Guest, Trap.Pieces[Failed].Host); ++ return true; ++ } ++ } ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch); ++ LeaveTrap(Trap, UContext, Trap.ResumePC); ++ return true; ++} ++ ++void ReleaseThread(FEX::HLE::ThreadStateObject* Thread) { ++ if (Thread->HighMemoryTrap.Code) { ++ FEXCore::Allocator::munmap(Thread->HighMemoryTrap.Code, FEXCore::Utils::FEX_PAGE_SIZE); ++ Thread->HighMemoryTrap.Code = nullptr; ++ } ++} ++} // namespace FEX::HLE::GuestHighMemory +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h +new file mode 100644 +index 0000000..661b200 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h +@@ -0,0 +1,74 @@ ++#pragma once ++ ++#include ++#include ++ ++#include ++#include ++#include ++#include ++ ++namespace FEXCore::Core { ++struct InternalThreadState; ++} ++ ++namespace FEX::HLE { ++struct ThreadStateObject; ++} ++ ++namespace FEX::HLE::GuestHighMemory { ++struct ArgumentStorage { ++ struct iovec Inline[8]; ++ fextl::vector Heap; ++ struct msghdr Message; ++ uint64_t ReceivedHeader {}; ++ fextl::vector Messages; ++ fextl::vector MessageLengths; ++ uint64_t GuestMessages {}; ++ bool ReceivedMessages {}; ++ int Socket {-1}; ++ int SendFlags {}; ++ uint32_t CapabilityHeader[2] {}; ++ uint32_t CapabilityVersion {}; ++ uint64_t GuestCapabilityHeader {}; ++ fextl::vector Words; ++ fextl::vector IoCopies; ++ fextl::vector IoKeys; ++ fextl::vector IoKeyValues; ++ fextl::vector EventBuffer; ++ fextl::list> Recovery; ++ uint64_t Events {}; ++ uint64_t EventContext {}; ++ uint64_t Stashed {}; ++ uint64_t StashGeneration {}; ++ uint64_t Least {}; ++ int64_t Deadline {}; ++ int64_t Wait[2] {}; ++ long EventSyscall {}; ++ uint64_t EventMask {}; ++ bool Blocking {}; ++ uint64_t SetupContext {}; ++ uint64_t SetupId {}; ++ uint64_t DestroyedContext {}; ++ uint64_t DestroyedGeneration {}; ++ bool Destroying {}; ++}; ++ ++bool Contains(uint64_t Address); ++bool ClaimsMapping(uint64_t Address, uint64_t Length, int Flags); ++uint64_t Map(uint64_t Address, uint64_t Length, int Prot, int Flags, int FD, off_t Offset); ++uint64_t Unmap(uint64_t Address, uint64_t Length); ++uint64_t Protect(uint64_t Address, uint64_t Length, int Prot); ++uint64_t Advise(uint64_t Address, uint64_t Length, int Advice, bool* Applied); ++bool DiscardsContents(int Advice); ++uint64_t ToGuest(uint64_t Address); ++bool TranslateRange(uint64_t Address, uint64_t Length, uint64_t* Host); ++void MarkCode(uint64_t Address, uint64_t Length); ++uint64_t TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t Count, ArgumentStorage* Storage); ++uint64_t FinishSyscallArguments(uint64_t Result, ArgumentStorage* Storage); ++bool HoldsMappings(FEXCore::Core::InternalThreadState* Thread); ++bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext); ++bool HandleBusFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext); ++bool HandleTrap(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext); ++void ReleaseThread(FEX::HLE::ThreadStateObject* Thread); ++} // namespace FEX::HLE::GuestHighMemory +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index 87b890e..ababed9 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -7,6 +7,7 @@ $end_info$ + */ + + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/SignalTrace.h" +@@ -765,6 +766,10 @@ uint64_t SignalDelegator::GetNewSigMask(int Signal) const { + } + + bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ if (FEX::HLE::GuestHighMemory::HandleFault(Thread, Signal, Info, UContext)) { ++ return true; ++ } ++ + auto SigInfo = *static_cast(Info); + + if (FaultSafeUserMemAccess::TryHandleSafeFault(Signal, SigInfo, UContext)) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +index 607ab0b..5e684c4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +@@ -16,6 +16,7 @@ $end_info$ + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/SignalDelegator.h" + #include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + #include + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" +@@ -820,6 +821,8 @@ SyscallHandler::SyscallHandler(FEXCore::Context::Context* _CTX, FEX::HLE::Signal + + SignalDelegation->RegisterHostSignalHandler(SIGSEGV, HandleSegfault, true); + ++ SignalDelegation->RegisterHostSignalHandler(SIGTRAP, FEX::HLE::GuestHighMemory::HandleTrap, true); ++ SignalDelegation->RegisterHostSignalHandler(SIGBUS, FEX::HLE::GuestHighMemory::HandleBusFault, true); + SignalDelegation->RegisterHostSignalHandler( + SIGTRAP, [](FEXCore::Core::InternalThreadState*, int, void*, void*) { return false; }, true); + +@@ -894,30 +897,34 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + } + + auto& Def = Definitions[SyscallNum]; ++ uint64_t A[7] {}; ++ for (unsigned i = 1; i < 7; ++i) { ++ A[i] = GetArg(Is64Bit, Frame, i); ++ } ++ FEX::HLE::GuestHighMemory::ArgumentStorage HighMemoryArguments; + uint64_t Result {}; +- switch (Def.NumArgs) { +- case 0: Result = std::invoke(Def.Ptr0, Frame); break; +- case 1: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 1)); break; +- case 2: Result = std::invoke(Def.Ptr2, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2)); break; +- case 3: Result = std::invoke(Def.Ptr3, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3)); break; +- case 4: +- Result = +- std::invoke(Def.Ptr4, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), GetArg(Is64Bit, Frame, 4)); +- break; +- case 5: +- Result = std::invoke(Def.Ptr5, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), +- GetArg(Is64Bit, Frame, 4), GetArg(Is64Bit, Frame, 5)); +- break; +- case 6: +- Result = std::invoke(Def.Ptr6, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), +- GetArg(Is64Bit, Frame, 4), GetArg(Is64Bit, Frame, 5), GetArg(Is64Bit, Frame, 6)); +- break; +- // for missing syscalls +- case 255: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 0)); break; +- default: +- LOGMAN_MSG_A_FMT("Unhandled syscall: {}", GetArg(Is64Bit, Frame, 0)); +- Result = -ENOSYS; +- break; ++ if constexpr (Is64Bit) { ++ Result = FEX::HLE::GuestHighMemory::TranslateSyscallArguments(SyscallNum, &A[1], 6, &HighMemoryArguments); ++ } ++ if (!FEX::HLE::HasSyscallError(Result)) { ++ switch (Def.NumArgs) { ++ case 0: Result = std::invoke(Def.Ptr0, Frame); break; ++ case 1: Result = std::invoke(Def.Ptr1, Frame, A[1]); break; ++ case 2: Result = std::invoke(Def.Ptr2, Frame, A[1], A[2]); break; ++ case 3: Result = std::invoke(Def.Ptr3, Frame, A[1], A[2], A[3]); break; ++ case 4: Result = std::invoke(Def.Ptr4, Frame, A[1], A[2], A[3], A[4]); break; ++ case 5: Result = std::invoke(Def.Ptr5, Frame, A[1], A[2], A[3], A[4], A[5]); break; ++ case 6: Result = std::invoke(Def.Ptr6, Frame, A[1], A[2], A[3], A[4], A[5], A[6]); break; ++ // for missing syscalls ++ case 255: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 0)); break; ++ default: ++ LOGMAN_MSG_A_FMT("Unhandled syscall: {}", GetArg(Is64Bit, Frame, 0)); ++ Result = -ENOSYS; ++ break; ++ } ++ } ++ if constexpr (Is64Bit) { ++ Result = FEX::HLE::GuestHighMemory::FinishSyscallArguments(Result, &HighMemoryArguments); + } + #ifdef DEBUG_STRACE + Strace(Frame, Result); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp +index 9397c9e..6095bf3 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp +@@ -5,12 +5,19 @@ tags: LinuxSyscalls|syscalls-shared + $end_info$ + */ + ++#include "LinuxSyscalls/GuestHighMemory.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" + + #include ++#include ++#include ++#include ++#include + ++#include ++#include + #include + #include + #include +@@ -25,6 +32,29 @@ void RegisterMemory(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(madvise, [](FEXCore::Core::CpuStateFrame* Frame, void* addr, size_t length, int32_t advice) -> uint64_t { ++ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(addr))) { ++ uint64_t Result {}; ++ bool Applied {}; ++ { ++ auto lk = FEXCore::GuardSignalDeferringSection(FEX::HLE::_SyscallHandler->VMATracking.Mutex, Frame->Thread); ++ Result = FEX::HLE::GuestHighMemory::Advise(reinterpret_cast(addr), length, advice, &Applied); ++ } ++ if (Applied && FEX::HLE::GuestHighMemory::DiscardsContents(advice)) { ++ const auto Base = reinterpret_cast(addr); ++ const auto Size = std::min(FEXCore::AlignUp(length, FEXCore::Utils::FEX_PAGE_SIZE), UINT64_MAX - Base); ++ FEX::HLE::_SyscallHandler->TM.InvalidateGuestCodeRange(Frame->Thread, Base, Size, [](uintptr_t Start, uintptr_t Length) { ++ if (FEX::HLE::GuestHighMemory::Contains(Start)) { ++ return; ++ } ++ auto rv = mprotect(reinterpret_cast(Start), Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }); ++ } ++ if (!FEX::HLE::HasSyscallError(Result)) { ++ FEX::HLE::_SyscallHandler->TrackMadvise(Frame->Thread, (uintptr_t)addr, length, advice); ++ } ++ return Result; ++ } + uint64_t Result = ::madvise(addr, length, advice); + + if (Result != -1) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +index f9e85a2..2dff836 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +@@ -21,6 +21,7 @@ $end_info$ + + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + + #include + #include +@@ -45,6 +46,9 @@ static void HandleSegfaultForCodeCacheFinalization(FEXCore::Core::InternalThread + void SyscallHandler::InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, + const FEX::HLE::VMATracking::VMAEntry& Mapping) { + auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { ++ if (FEX::HLE::GuestHighMemory::Contains(Start)) { ++ return; ++ } + auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); + }; +@@ -93,6 +97,10 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + } + ++ if (FEX::HLE::GuestHighMemory::Contains(FaultAddress) || FEX::HLE::GuestHighMemory::HoldsMappings(Thread)) { ++ return false; ++ } ++ + { + // Can't use the deferred signal lock in the SIGSEGV handler. + auto lk = FEXCore::MaskSignalsAndLockMutex(_SyscallHandler->VMATracking.Mutex); +@@ -150,6 +158,7 @@ void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThr + return; + } + ++ Buf = reinterpret_cast(FEX::HLE::GuestHighMemory::ToGuest(reinterpret_cast(Buf))); + const uint64_t Start = FEXCore::AlignDown(reinterpret_cast(Buf), FEXCore::Utils::FEX_PAGE_SIZE); + const uint64_t Last = reinterpret_cast(Buf) + Length - 1 < reinterpret_cast(Buf) ? + UINT64_MAX : +@@ -176,6 +185,9 @@ void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThr + } + } else { + TM.InvalidateGuestCodeRange(Thread, From, To - From, [](uintptr_t Start, uintptr_t Length) { ++ if (FEX::HLE::GuestHighMemory::Contains(Start)) { ++ return; ++ } + auto rv = mprotect(reinterpret_cast(Start), Length, PROT_READ | PROT_WRITE); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); + }); +@@ -227,6 +239,10 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + const auto ProtectBase = std::max(MapBase, Base); + const auto ProtectSize = std::min(MapTop, Top) - ProtectBase; + ++ const bool HighRange = FEX::HLE::GuestHighMemory::Contains(ProtectBase); ++ if (HighRange) { ++ FEX::HLE::GuestHighMemory::MarkCode(ProtectBase, ProtectSize); ++ } + if (Mapping->second.Flags.Shared) { + LOGMAN_THROW_A_FMT(Mapping->second.Resource, "VMA tracking error"); + +@@ -245,13 +261,17 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + + const auto MirroredBase = std::max(VMAOffsetBase, OffsetBase); + const auto MirroredSize = std::min(OffsetTop, VMAOffsetTop) - MirroredBase; ++ if (FEX::HLE::GuestHighMemory::Contains(MirroredBase - VMAOffsetBase + VMABase)) { ++ FEX::HLE::GuestHighMemory::MarkCode(MirroredBase - VMAOffsetBase + VMABase, MirroredSize); ++ continue; ++ } + + auto rv = mprotect((void*)(MirroredBase - VMAOffsetBase + VMABase), MirroredSize, PROT_READ); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", MirroredBase, MirroredSize); + } + } while ((VMA = VMA->ResourceNextVMA)); + +- } else if (Mapping->second.Prot.Writable) { ++ } else if (!HighRange && Mapping->second.Prot.Writable) { + int rv = mprotect((void*)ProtectBase, ProtectSize, PROT_READ); + + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", ProtectBase, ProtectSize); +@@ -293,6 +313,10 @@ void SyscallHandler::ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length) + + const auto OverlapBase = std::max(VMA->Offset, OffsetBase); + const auto OverlapTop = std::min(VMA->Offset + VMA->Length, OffsetTop); ++ if (FEX::HLE::GuestHighMemory::Contains(MapBase + (OverlapBase - OffsetBase))) { ++ FEX::HLE::GuestHighMemory::MarkCode(MapBase + (OverlapBase - OffsetBase), OverlapTop - OverlapBase); ++ continue; ++ } + auto rv = mprotect((void*)(MapBase + (OverlapBase - OffsetBase)), OverlapTop - OverlapBase, PROT_READ); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", OverlapBase, OverlapTop - OverlapBase); + } +@@ -429,6 +453,11 @@ void* SyscallHandler::GuestMmap(bool Is64Bit, FEXCore::Core::InternalThreadState + return reinterpret_cast(Result); + } + LOGMAN_THROW_A_FMT(Is64Bit || (Result >> 32) == 0 || (Result >> 32) == 0xFFFFFFFF, "values must fit to 32 bits"); ++ } else if (FEX::HLE::GuestHighMemory::ClaimsMapping(reinterpret_cast(addr), length, flags)) { ++ Result = FEX::HLE::GuestHighMemory::Map(reinterpret_cast(addr), length, prot, flags, fd, offset); ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return reinterpret_cast(Result); ++ } + } else { + Result = reinterpret_cast(::mmap(reinterpret_cast(addr), length, prot, flags, fd, offset)); + if (Result == ~0ULL) { +@@ -483,9 +512,16 @@ uint64_t SyscallHandler::GuestMunmap(bool Is64Bit, FEXCore::Core::InternalThread + if (Addr > X86_64TaskSizeMax || Size > X86_64TaskSizeMax - Addr || (length != 0 && Size == 0)) { + return -EINVAL; + } +- Result = ::munmap(addr, length); +- if (Result == -1) { +- return -errno; ++ if (FEX::HLE::GuestHighMemory::Contains(Addr)) { ++ Result = FEX::HLE::GuestHighMemory::Unmap(Addr, length); ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return Result; ++ } ++ } else { ++ Result = ::munmap(addr, length); ++ if (Result == -1) { ++ return -errno; ++ } + } + if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { + Get32BitAllocator()->TrackUnmapped(addr, length); +@@ -511,6 +547,10 @@ uint64_t SyscallHandler::GuestMremap(bool Is64Bit, FEXCore::Core::InternalThread + { + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); + if (Is64Bit) { ++ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(old_address)) || ++ ((flags & MREMAP_FIXED) && FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(new_address)))) { ++ return -EINVAL; ++ } + Result = reinterpret_cast(::mremap(old_address, old_size, new_size, flags, new_address)); + if (Result == -1) { + return -errno; +@@ -602,9 +642,16 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + } + } + +- Result = ::mprotect(addr, len, prot); +- if (Result == -1) { +- return -errno; ++ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(addr))) { ++ Result = FEX::HLE::GuestHighMemory::Protect(reinterpret_cast(addr), len, prot); ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return Result; ++ } ++ } else { ++ Result = ::mprotect(addr, len, prot); ++ if (Result == -1) { ++ return -errno; ++ } + } + + TrackMprotect(Thread, addr, len, prot); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +index 2e59f2f..ee28680 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +@@ -1,6 +1,7 @@ + // SPDX-License-Identifier: MIT + + #include "LinuxSyscalls/ThreadManager.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + #include "LinuxSyscalls/SamplingProfiler.h" + + #include "LinuxSyscalls/Syscalls.h" +@@ -330,6 +331,7 @@ void ThreadManager::HandleThreadDeletion(FEX::HLE::ThreadStateObject* Thread, bo + FEXCore::Allocator::munmap(Thread->ldt_entries, Thread->ldt_entry_count * FEX::HLE::SyscallHandler::LDT_ENTRY_SIZE); + } + ++ FEX::HLE::GuestHighMemory::ReleaseThread(Thread); + CTX->DestroyThread(Thread->Thread); + FEX::HLE::_SyscallHandler->SeccompEmulator.FreeSeccompFilters(Thread); + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index 9c5f9f1..e43dfc7 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -104,6 +104,40 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + bool Enabled; + } SyscallUserDispatch {}; + ++ struct { ++ uint8_t* Code; ++ uint64_t ResumePC; ++ uint64_t SavedScratch; ++ uint64_t BaseBefore; ++ uint64_t Delta; ++ uint64_t SavedMask; ++ uint32_t Scratch; ++ uint32_t Base; ++ bool Active; ++ bool Store; ++ bool Probe; ++ struct { ++ bool Held; ++ uint32_t Deferred; ++ siginfo_t DeferredInfo[3]; ++ } Mappings; ++ uint32_t Parts; ++ uint32_t BounceOffset; ++ struct { ++ uint64_t Guest; ++ uint64_t Host; ++ uint64_t Size; ++ } Pieces[2]; ++ alignas(16) uint8_t Bounce[96]; ++ struct { ++ uint64_t Host; ++ uint64_t Low; ++ uint64_t High; ++ uint32_t Size; ++ bool Valid; ++ } Monitor; ++ } HighMemoryTrap {}; ++ + uint64_t JITStackSP {}; + + struct TrapSignalFrame { +-- +2.43.0 + diff --git a/tools/fex/patches/0028-guest-cmdline-without-checkpoint-restore.patch b/tools/fex/patches/0028-guest-cmdline-without-checkpoint-restore.patch new file mode 100644 index 0000000000..899b071568 --- /dev/null +++ b/tools/fex/patches/0028-guest-cmdline-without-checkpoint-restore.patch @@ -0,0 +1,58 @@ +From 0510284085165d39ef0eabb83e7604fe1bb74c76 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Thu, 3 Dec 2026 03:26:13 -0500 +Subject: [PATCH] Show the guest command line when the argument area cannot be + remapped + +Kernels built without checkpoint/restore support refuse PR_SET_MM_MAP, +so /proc/pid/cmdline kept showing the FEX invocation instead of the +guest program and the argv rewrites it makes. For 64-bit guests whose +arguments fit, the guest argument strings now live in the original +argument area and argv points there, which needs no privilege. +--- + Source/Tools/FEXInterpreter/ELFCodeLoader.h | 23 ++++++++++++++++++++- + 1 file changed, 22 insertions(+), 1 deletion(-) + +diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +index b1a72d227..6d2157365 100644 +--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h ++++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +@@ -874,13 +874,34 @@ public: + + int r = prctl(PR_SET_MM, PR_SET_MM_MAP, &map, sizeof(map), 0L); + if (r != 0) { +- LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, errno); ++ int Error = errno; ++ if (Is64BitMode() && MoveArgumentDataToHostArea(NewArgStart, ArgSize)) { ++ return; ++ } ++ LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, Error); + } + } else { + LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (GetCurrentMap failed)"); + } + } + ++ bool MoveArgumentDataToHostArea(uintptr_t GuestArgStart, uint64_t ArgSize) { ++ struct prctl_mm_map map {}; ++ if (!GetCurrentMap(map) || map.arg_end <= map.arg_start || ArgSize > map.arg_end - map.arg_start) { ++ return false; ++ } ++ ++ auto HostArgs = reinterpret_cast(map.arg_start); ++ memmove(HostArgs, reinterpret_cast(GuestArgStart), ArgSize); ++ memset(HostArgs + ArgSize, 0, map.arg_end - map.arg_start - ArgSize); ++ ++ auto ArgumentPointers = reinterpret_cast(StackPointer + sizeof(uint64_t)); ++ for (size_t i = 0; i < ApplicationArgs.size(); ++i) { ++ ArgumentPointers[i] = ArgumentPointers[i] - GuestArgStart + map.arg_start; ++ } ++ return true; ++ } ++ + // Setups the stack initial data (argv, envp, auxv) + void SetupStack() { + StackPointer += StackSize(); +-- +2.43.0 + diff --git a/tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch b/tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch new file mode 100644 index 0000000000..61cf5004df --- /dev/null +++ b/tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch @@ -0,0 +1,310 @@ +From fc926d0e9c63a3d5290a5d816029513349de78f6 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Thu, 3 Dec 2026 08:03:20 -0500 +Subject: [PATCH] Describe the container's procfs in emulated mount tables + +Android mounts /proc with hidepid=invisible,gid=3009 so an app cannot see the +processes of other users. Every process of the container runs as the app's +user, so the container sees all of its own processes, as it would through a +procfs of its own in a PID namespace. The emulated /proc//mounts and +mountinfo now list the proc mount without the host instance's access options +(hidepid, gid, subset). Every other mount is passed through unchanged. +--- + .../EmulatedFiles/EmulatedFiles.cpp | 230 +++++++++++++----- + .../EmulatedFiles/EmulatedFiles.h | 1 + + 2 files changed, 170 insertions(+), 61 deletions(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index 19bfc814f..85f1b3e15 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -37,6 +37,7 @@ $end_info$ + #include + #include + #include ++#include + #include + #include + #include +@@ -649,6 +650,149 @@ static bool IsHostArchModule(const char* Path, fextl::unordered_map 0) { ++ Out.append(Buf, Len); ++ } else if (Len == 0) { ++ break; ++ } else if (errno != EINTR) { ++ LogMan::Msg::EFmt("Emulated /proc file: reading {} failed: {}", Path, errno); ++ ::close(HostFD); ++ return false; ++ } ++ } ++ ::close(HostFD); ++ return true; ++} ++ ++static int32_t SealedFileOf(const char* pathname, int32_t flags, const fextl::string& Data) { ++ int NewFD = GenTmpFD(pathname, flags); ++ if (NewFD < 0) { ++ LogMan::Msg::EFmt("Emulated /proc file: memfd_create failed: {}", errno); ++ return -1; ++ } ++ for (size_t Done = 0; Done < Data.size();) { ++ const ssize_t Wrote = ::write(NewFD, Data.data() + Done, Data.size() - Done); ++ if (Wrote > 0) { ++ Done += Wrote; ++ } else if (Wrote < 0 && errno == EINTR) { ++ continue; ++ } else { ++ LogMan::Msg::EFmt("Emulated /proc file: writing the synthesized file failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ } ++ if (::lseek(NewFD, 0, SEEK_SET) != 0) { ++ LogMan::Msg::EFmt("Emulated /proc file: lseek failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ SealTmpFD(NewFD); ++ return NewFD; ++} ++ ++static const char* ProcFileOfPid(const char* Path) { ++ if (strncmp(Path, "/proc/", 6) != 0) { ++ return nullptr; ++ } ++ const char* P = Path + 6; ++ if (strncmp(P, "self/", 5) == 0) { ++ return P + 5; ++ } ++ if (strncmp(P, "thread-self/", 12) == 0) { ++ return P + 12; ++ } ++ if (!isdigit(*P)) { ++ return P; ++ } ++ while (isdigit(*P)) { ++ ++P; ++ } ++ if (*P++ != '/') { ++ return nullptr; ++ } ++ if (strncmp(P, "task/", 5) == 0) { ++ P += 5; ++ if (!isdigit(*P)) { ++ return nullptr; ++ } ++ while (isdigit(*P)) { ++ ++P; ++ } ++ if (*P++ != '/') { ++ return nullptr; ++ } ++ } ++ return P; ++} ++ ++static bool IsProcMountTablePath(const char* Path) { ++ const char* File = ProcFileOfPid(Path); ++ return File && (strcmp(File, "mounts") == 0 || strcmp(File, "mountinfo") == 0); ++} ++ ++static fextl::string ContainerProcOptions(std::string_view Options) { ++ fextl::string Out; ++ size_t Pos = 0; ++ while (Pos <= Options.size()) { ++ size_t Comma = Options.find(',', Pos); ++ if (Comma == std::string_view::npos) { ++ Comma = Options.size(); ++ } ++ const std::string_view Option = Options.substr(Pos, Comma - Pos); ++ if (!Option.empty() && !Option.starts_with("hidepid=") && !Option.starts_with("gid=") && !Option.starts_with("subset=")) { ++ if (!Out.empty()) { ++ Out += ','; ++ } ++ Out.append(Option); ++ } ++ Pos = Comma + 1; ++ } ++ return Out; ++} ++ ++static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) { ++ fextl::vector Fields; ++ size_t Pos = 0; ++ while (Pos < Line.size()) { ++ size_t Space = Line.find(' ', Pos); ++ if (Space == std::string_view::npos) { ++ Space = Line.size(); ++ } ++ Fields.push_back(Line.substr(Pos, Space - Pos)); ++ Pos = Space + 1; ++ } ++ size_t Type = 2; ++ if (MountInfo) { ++ auto Dash = std::find(Fields.begin(), Fields.end(), std::string_view("-")); ++ Type = static_cast(Dash - Fields.begin()) + 1; ++ } ++ const size_t Options = MountInfo ? Type + 2 : Type + 1; ++ if (Options >= Fields.size() || Fields[Type] != "proc") { ++ return fextl::string(Line); ++ } ++ fextl::string Out; ++ for (size_t i = 0; i < Fields.size(); ++i) { ++ if (i) { ++ Out += ' '; ++ } ++ if (i == Options) { ++ Out += ContainerProcOptions(Fields[i]); ++ } else { ++ Out.append(Fields[i]); ++ } ++ } ++ return Out; ++} ++ + static bool IsProcMapsPath(const char* Path) { + if (strncmp(Path, "/proc/", 6) != 0) { + return false; +@@ -673,6 +817,9 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) + if (pathname && IsProcMapsPath(pathname)) { + return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode); + } ++ if (pathname && IsProcMountTablePath(pathname)) { ++ return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode); ++ } + return -1; + } + +@@ -680,25 +827,10 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) + } + + int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { +- int HostFD = ::open(pathname, O_RDONLY | O_CLOEXEC); +- if (HostFD < 0) { +- return -1; +- } + fextl::string In; +- char Buf[65536]; +- for (;;) { +- const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf)); +- if (Len > 0) { +- In.append(Buf, Len); +- } else if (Len == 0) { +- break; +- } else if (errno != EINTR) { +- LogMan::Msg::EFmt("ProcMaps: reading {} failed: {}", pathname, errno); +- ::close(HostFD); +- return -1; +- } ++ if (!ReadHostFile(pathname, In)) { ++ return -1; + } +- ::close(HostFD); + + constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096; + const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47; +@@ -756,30 +888,29 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, + Pos = End; + } + +- int NewFD = GenTmpFD(pathname, flags); +- if (NewFD < 0) { +- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); ++ return SealedFileOf(pathname, flags, Out); ++} ++ ++int32_t EmulatedFDManager::ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { ++ fextl::string In; ++ if (!ReadHostFile(pathname, In)) { + return -1; + } +- for (size_t Done = 0; Done < Out.size();) { +- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done); +- if (Wrote > 0) { +- Done += Wrote; +- } else if (Wrote < 0 && errno == EINTR) { +- continue; +- } else { +- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno); +- ::close(NewFD); +- return -1; ++ const char* File = ProcFileOfPid(pathname); ++ const bool MountInfo = File && strcmp(File, "mountinfo") == 0; ++ fextl::string Out; ++ Out.reserve(In.size()); ++ size_t Pos = 0; ++ while (Pos < In.size()) { ++ size_t Eol = In.find('\n', Pos); ++ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol; ++ Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo); ++ if (Eol != fextl::string::npos) { ++ Out += '\n'; + } ++ Pos = LineEnd + 1; + } +- if (::lseek(NewFD, 0, SEEK_SET) != 0) { +- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); +- ::close(NewFD); +- return -1; +- } +- SealTmpFD(NewFD); +- return NewFD; ++ return SealedFileOf(pathname, flags, Out); + } + + int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { +@@ -832,30 +963,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd + Cursor = Eol + 1; + } + +- int NewFD = GenTmpFD(pathname, flags); +- if (NewFD < 0) { +- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); +- return -1; +- } +- for (size_t Done = 0; Done < Out.size();) { +- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done); +- if (Wrote > 0) { +- Done += Wrote; +- } else if (Wrote < 0 && errno == EINTR) { +- continue; +- } else { +- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno); +- ::close(NewFD); +- return -1; +- } +- } +- if (::lseek(NewFD, 0, SEEK_SET) != 0) { +- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); +- ::close(NewFD); +- return -1; +- } +- SealTmpFD(NewFD); +- return NewFD; ++ return SealedFileOf(pathname, flags, Out); + } + + int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +index b98ef4bda..b1ec241a7 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +@@ -35,6 +35,7 @@ private: + + static int32_t ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); + static int32_t ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); ++ static int32_t ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); + static int32_t ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); + const uint32_t ThreadsConfig; + }; diff --git a/tools/fex/probes/guest-high-memory.c b/tools/fex/probes/guest-high-memory.c new file mode 100644 index 0000000000..fa4450183a --- /dev/null +++ b/tools/fex/probes/guest-high-memory.c @@ -0,0 +1,92 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include + +#define HIGH ((uintptr_t)0x7e0000000000ULL) +#define ALIAS ((uintptr_t)0x7e0000100000ULL) +#define THREADS 4 +#define ITERS 200000 + +static volatile uint64_t *counter; +static volatile uint64_t *cas; +static int fails; + +static void check(const char *name, int ok) { + printf("%s %s\n", ok ? "PASS" : "FAIL", name); + if (!ok) fails++; +} + +static void *worker(void *arg) { + (void)arg; + for (int i = 0; i < ITERS; i++) { + __atomic_fetch_add(counter, 1, __ATOMIC_SEQ_CST); + uint64_t old = __atomic_load_n(cas, __ATOMIC_RELAXED); + while (!__atomic_compare_exchange_n(cas, &old, old + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) { + } + } + return NULL; +} + +int main(void) { + alarm(60); + uint8_t *high = mmap((void *)HIGH, 65536, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + if (high == MAP_FAILED) { + printf("NOTCLAIMED errno=%d\n", errno); + return 0; + } + check("fixed-high-map", high == (uint8_t *)HIGH); + memset(high, 0x5a, 65536); + check("load-store", high[100] == 0x5a && high[65535] == 0x5a); + + counter = (uint64_t *)(high + 64); + cas = (uint64_t *)(high + 128); + *counter = 0; + *cas = 0; + pthread_t t[THREADS]; + for (int i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, worker, NULL); + for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL); + check("atomic-add", *counter == (uint64_t)THREADS * ITERS); + check("atomic-cmpxchg", *cas == (uint64_t)THREADS * ITERS); + + int p[2]; + check("pipe", pipe(p) == 0); + memcpy(high + 4096, "hello ", 6); + memcpy(high + 8192, "world", 5); + struct iovec out[2] = {{high + 4096, 6}, {high + 8192, 5}}; + ssize_t w = writev(p[1], out, 2); + memset(high + 12288, 0, 64); + struct iovec in[2] = {{high + 12288, 3}, {high + 12291, 8}}; + ssize_t r = w == 11 ? readv(p[0], in, 2) : -1; + check("writev-readv", w == 11 && r == 11 && memcmp(high + 12288, "hello world", 11) == 0); + + int wrote = write(p[1], "abcdef", 6) == 6; + check("write", wrote); + check("read", wrote && read(p[0], high + 20000, 6) == 6 && memcmp(high + 20000, "abcdef", 6) == 0); + + high[30000] = 7; + check("madvise-dontneed", madvise(high + 28672, 4096, MADV_DONTNEED) == 0 && high[30000] == 0); + + int fd = memfd_create("code", 0); + check("memfd", fd >= 0 && ftruncate(fd, 4096) == 0); + static const uint8_t code[] = {0xb8, 0x01, 0x00, 0x00, 0x00, 0xc3}; + check("pwrite", pwrite(fd, code, sizeof code, 0) == (ssize_t)sizeof code); + uint8_t *low = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); + uint8_t *alias = mmap((void *)ALIAS, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0); + check("alias-map", low != MAP_FAILED && alias == (uint8_t *)ALIAS); + int (*fn)(void) = (int (*)(void))low; + int before = fn(); + alias[1] = 2; + __atomic_thread_fence(__ATOMIC_SEQ_CST); + int after = fn(); + printf("alias before=%d after=%d\n", before, after); + check("smc-through-high-alias", before == 1 && after == 2); + + printf("%s\n", fails ? "RESULT FAIL" : "RESULT PASS"); + return fails != 0; +} 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 01840825af..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 @@ -233,7 +241,12 @@ 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)" 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-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index 0b432bb5d3..1f5cc42743 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -664,7 +664,7 @@ def data_dir(env): return DATA_DIR -def guest_environment(fex, env): +def guest_environment(fex, env, keep_compat=False): result = dict(env) data = data_dir(env) for directory in (CONFIG_DIR, data, CACHE_DIR): @@ -672,7 +672,7 @@ def guest_environment(fex, env): result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/" result["FEX_APP_DATA_LOCATION"] = data + "/" result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/" - if result.get("STEAM_COMPAT_DATA_PATH"): + if result.get("STEAM_COMPAT_DATA_PATH") and not keep_compat: short = data if data != DATA_DIR else "/tmp/fex" os.makedirs(short, exist_ok=True) result["STEAM_COMPAT_DATA_PATH"] = short @@ -750,9 +750,12 @@ def vulkan_thunk_loads(fex, folder): def required_runtime(program): - text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or "" - match = re.search(r'"require_tool_appid"\s+"(\d+)"', text) - return match.group(1) if match and match.group(1) in RUNTIMES else SNIPER_APPID + folder = os.path.dirname(program) + for name in ("toolmanifest.vdf.droiddeck-orig", "toolmanifest.vdf"): + match = re.search(r'"require_tool_appid"\s+"(\d+)"', read_text(os.path.join(folder, name)) or "") + if match and match.group(1) in RUNTIMES: + return match.group(1) + return SNIPER_APPID def resolve(program, env): @@ -761,7 +764,7 @@ def resolve(program, env): return shutil.which(program, path=env.get("PATH")) or program -def launch(command, env, mode, decide=None): +def launch(command, env, mode, decide=None, keep_compat=False): program = resolve(command[0], env) use = mode == "on" or (mode == "auto" and needs_fex(decide or program)) if not use: @@ -769,7 +772,7 @@ def launch(command, env, mode, decide=None): fex = prepare(required_runtime(program)) if fex is None: return 126 - guest = guest_environment(fex, env) + guest = guest_environment(fex, env, keep_compat) x86_64 = elf_arch(program) != "i386" thunks = "on" if "FEX_THUNKCONFIG" in guest else "off" folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program) @@ -781,7 +784,7 @@ def launch(command, env, mode, decide=None): return os.execve(fex["bin"], [fex["bin"], program] + command[1:], guest) -def game_environment(env, command): +def game_environment(env, command, proton=None): try: game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env")) env = game_env["game_gpu"](env) @@ -800,7 +803,14 @@ def game_environment(env, command): config = json.load(source) except FileNotFoundError: config = {"version": 1} - return game_env["apply_config"](env, config, str(app), fixes) + env = game_env["apply_config"](env, config, str(app), fixes) + if proton and len(proton) > 2 and proton[1] == "waitforexitandrun": + logged = game_env["apply_game_debug_logs"](env, config) + if logged is not env: + say("game debug logs enabled for this launch") + env = game_env["game_logs"](proton, logged, str(app)) + game_env["GAME_DEBUG"]["cap_proton_log"](env) + return env except FileNotFoundError: return env except Exception as error: @@ -963,7 +973,7 @@ def parse_run(args): def main(argv): if not argv: - say("usage: droiddeck-fex steam VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status") + say("usage: droiddeck-fex steam VERB CMD... | proton PROTON VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | update | status") return 2 action, args = argv[0], list(argv[1:]) if action == "steam": @@ -975,6 +985,10 @@ def main(argv): if not command: return 2 return launch(command, game_environment(dict(os.environ), command), os.environ.get("DROIDDECK_FEX", "auto")) + if action == "proton": + if len(args) < 2: + return 2 + return launch(args, game_environment(dict(os.environ), args[2:] or args, args), "on", keep_compat=True) if action == "run": try: mode, decide, command = parse_run(args) @@ -996,6 +1010,10 @@ def main(argv): return extract(args[0]) if action == "prepare": return 0 if prepare() else 1 + if action == "update": + with locked(): + update_own_fex() + return 0 if action == "status": with locked(): status = describe(fex_install(), runtime_platform(), graphics_platform()) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update index 25f445adee..f25d2a3394 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update @@ -29,10 +29,14 @@ fex_install() { return 1 fi (cd "$tmp/root" && find . ! -type d) > "$tmp/files" - for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do - [ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue - (cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done - done > "$tmp/stale" + { + for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do + [ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue + (cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done + done + f=usr/local/share/fex-emu/.droiddeck-patches + if [ -e "$dst$f" ] && ! grep -qxF "./$f" "$tmp/files"; then echo "$f"; fi + } > "$tmp/stale" mkdir "$tmp/old" while IFS= read -r f; do f=${f#./} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-debug b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-debug index 24147636b7..6be7771a39 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-debug +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-debug @@ -69,7 +69,8 @@ def apply_game_debug_logs(env, config=None, debug_dir=None): "PROTON_CRASH_REPORT_DIR": debug_dir, "DXVK_LOG_PATH": debug_dir, "DXVK_LOG_LEVEL": "debug", - "VKD3D_DEBUG": "info", + "VKD3D_DEBUG": "warn", + "VKD3D_SHADER_DEBUG": "warn", "WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")), }) return result diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index 1e02ad4be2..bc4c7c73c8 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,30 @@ 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", +) +PSPC_SDK_FILES = {"install_pspc_sdk_runtime.bat", "pspcsdkruntimeinstaller.msi", "pspcsdkruntimemanager.msi"} # 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 +174,40 @@ def game_files(exe): return names +def unreal_binary_files(exe): + project = os.path.splitext(os.path.basename(exe))[0] + try: + with os.scandir(os.path.join(os.path.dirname(exe), project, "Binaries", "Win64")) as folder: + return {entry.name.lower() for entry in folder} + except OSError: + return set() + + +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 +217,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 +237,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: @@ -249,6 +315,12 @@ def arkham_city_x87(game): return {"FEX_X87REDUCEDPRECISION": "0"}, [], "Batman: Arkham City: FEX with full x87 precision" +@fix +def playstation_pc_sdk_x87(game): + if PSPC_SDK_FILES & (game.files | unreal_binary_files(game.exe)): + return {"FEX_X87REDUCEDPRECISION": "0"}, [], "PlayStation PC SDK: FEX with full x87 precision" + + @fix def split_second_x87_fip(game): if game.app_id == "297860" or game.stem == "splitsecond": 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-open-url b/tools/linuxfs/overlay/usr/local/bin/droiddeck-open-url index 48154cc849..83c84f885d 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-open-url +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-open-url @@ -3,6 +3,7 @@ import json import os LAUNCH_DIR_FILE = "/tmp/droiddeck-browser/launch-dir" +STEAM = "/usr/local/bin/droiddeck-steam-shim" import sys import time from pathlib import Path @@ -17,6 +18,13 @@ def hand_over(url, launch_dir): os.rename(tmp, req / (rid + ".json")) +def same_file(a, b): + try: + return os.path.samefile(a, b) + except OSError: + return os.path.realpath(a) == os.path.realpath(b) + + def where(url): from urllib.parse import urlsplit try: @@ -40,10 +48,11 @@ def main(argv): if url.startswith(("https://", "http://")) and launch_dir: hand_over(url, launch_dir) return 0 - here = os.path.dirname(os.path.realpath(sys.argv[0])) + if url.startswith("steam://") and os.access(STEAM, os.X_OK): + os.execv(STEAM, [STEAM, url]) for d in os.environ.get("PATH", "").split(os.pathsep): candidate = os.path.join(d, "xdg-open") - if os.access(candidate, os.X_OK) and os.path.realpath(candidate) != os.path.realpath(__file__) and os.path.abspath(d) != here: + if os.access(candidate, os.X_OK) and not same_file(candidate, __file__): os.execv(candidate, [candidate] + argv) return 1 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 c30c3098ec..d82fb99350 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 @@ -1226,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 @@ -1305,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'; } @@ -1393,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 @@ -1402,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 @@ -1427,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 @@ -1465,13 +1553,14 @@ 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 decky_exits=0 # The guest has no "deck" user, which Decky otherwise requires at startup. export UNPRIVILEGED_USER=root + export LIVE_RELOAD=0 while :; do if [ "$decky_arch" = x86_64 ]; then /usr/local/bin/droiddeck-fex run --mode on -- "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 & else "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 & @@ -1489,7 +1578,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 @@ -1690,7 +1780,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= @@ -1868,7 +1958,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: /' @@ -1901,6 +1992,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 @@ -2016,12 +2147,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" @@ -2031,6 +2169,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 4eb7ba26f7..0f1a29f3ac 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -318,12 +318,80 @@ dd_vacdiag() { } """ +DD_ANTICHEAT_SETUP = """ +dd_anticheat_runtime() { + local current=$1 name=$2 bridge=$3 library + if [ -n "$current" ] && [ -n "$(find -L "$current" -iname "$bridge" -print -quit 2>/dev/null)" ]; then + printf '%s' "$current"; return 0 + fi + while IFS= read -r library; do + [ -n "$(find "$library/steamapps/common/$name" -iname "$bridge" -print -quit 2>/dev/null)" ] || continue + printf '%s' "$library/steamapps/common/$name"; return 0 + done < <(printf '%s\\n' "$DD_AC_ROOT" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$DD_AC_ROOT/steamapps/libraryfolders.vdf" 2>/dev/null) + return 1 +} + +dd_x86_64_proton() { + [ -d "$1/files/lib/wine/x86_64-unix" ] && [ ! -d "$1/files/bin-arm64" ] +} + +dd_anticheat() { + case ${verb:-} in waitforexitandrun | run) ;; *) return 0 ;; esac + case ${DROIDDECK_ANTICHEAT:-auto} in off | 0 | false) return 0 ;; esac + local game=${STEAM_COMPAT_INSTALL_PATH:-} found markers eac battleye tool runtime= + [ -d "$game" ] || return 0 + markers=$(find "$game" -maxdepth 5 \\( -ipath '*/easyanticheat/settings.json' -o -iname 'easyanticheat_x64.so' \\ + -o -iname 'beclient_x64.so' -o -iname 'beservice_x64.exe' \\) -print 2>/dev/null) + eac=$(printf '%s\\n' "$markers" | grep -i easyanticheat | head -n 1) + battleye=$(printf '%s\\n' "$markers" | grep -iv easyanticheat | grep . | head -n 1) + found=${eac:-$battleye} + [ -n "$found" ] || return 0 + case ${DD_AC_TOOL:-DroidDeck-Proton} in + DroidDeck-Proton*) ;; + *) + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; ${DD_AC_TOOL} was chosen for this game, so it runs as chosen" >&2 + return 0 + ;; + esac + /usr/local/bin/droiddeck-fex update || true + if ! grep -qx fixed-guest-memory-above-host-address-limit /usr/local/share/fex-emu/.droiddeck-patches 2>/dev/null; then + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; the installed FEX build cannot run anti-cheat, so this launch stays on ARM64" >&2 + return 0 + fi + DD_AC_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam} + tool=$(cd "$DD_AC_ROOT/compatibilitytools.d" 2>/dev/null && for d in DroidDeck-Proton*; do + [ -x "$d/proton" ] && dd_x86_64_proton "$d" && printf '%s/%s\\n' "$PWD" "$d" + done | sort -V | tail -n 1) + if [ -z "$tool" ]; then + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; no x86-64 DroidDeck-Proton is installed, so this launch stays on ARM64" >&2 + return 0 + fi + if [ -n "$eac" ] && runtime=$(dd_anticheat_runtime "${PROTON_EAC_RUNTIME:-}" "Proton EasyAntiCheat Runtime" easyanticheat_x64.so); then + export PROTON_EAC_RUNTIME="$runtime" + found=$eac + elif [ -n "$battleye" ] && runtime=$(dd_anticheat_runtime "${PROTON_BATTLEYE_RUNTIME:-}" "Proton BattlEye Runtime" beclient_x64.so); then + export PROTON_BATTLEYE_RUNTIME="$runtime" + found=$battleye + else + runtime= + fi + if [ -z "$runtime" ]; then + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; its Proton runtime is not installed, so this launch stays on ARM64" >&2 + return 0 + fi + dd_game_cpus + declare -F dd_components >/dev/null && dd_components "$tool" + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; running ${tool##*/} under FEX" >&2 + exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$tool/proton" "$verb" "$@" +} +""" + # DroidDeck-Bionic runs only without proot. With proot on, a launch Steam sends to a DroidDeck-Bionic tool goes to the # newest DroidDeck-Proton's wrapper before anything else runs, as if that Proton had been picked; the picks stay as set. DD_BIONIC_PROOT_FALLBACK = """ if [ -f "$here/bionic/launch.sh" ] && [ -z "${DDNATV_ROOT:-}" ]; then dd_fallback=$(cd "$here/.." 2>/dev/null && for d in DroidDeck-Proton*; do - [ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] || continue + [ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] && ! dd_x86_64_proton "$d" || continue v=${d#DroidDeck-Proton}; printf '%s\\t%s/%s\\n' "${v#[ -]}" "$PWD" "$d" done | sort -V | tail -n 1 | cut -f 2-) if [ -n "$dd_fallback" ]; then @@ -461,6 +529,7 @@ for name in %s; do [ -n "$depot" ] && break done if [ -n "$depot" ]; then + dd_anticheat "$@" dd_components "$depot" dd_directaudio "$depot" "$@" dd_game_cpus @@ -481,7 +550,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH def launcher_sh(sources=SOURCES): return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace( "verb=$1; shift", "verb=$1; shift\n" + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP - + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1) + + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP + DD_ANTICHEAT_SETUP, 1) LAUNCHER_SH = launcher_sh() @@ -516,6 +585,11 @@ if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then *) LD_AUDIT="$audit${LD_AUDIT:+:$LD_AUDIT}"; export LD_AUDIT ;; esac fi +if dd_x86_64_proton "$here"; then + dd_game_cpus + exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$here/%s" "$verb" "$@" +fi +DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@" dd_components "$here" dd_directaudio "$here" "$@" dd_game_cpus @@ -530,9 +604,9 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve def extra_wrapper_sh(entry_point): - return (EXTRA_WRAPPER_SH % entry_point).replace( + return (EXTRA_WRAPPER_SH % (entry_point, entry_point)).replace( 'here=$(dirname "$0")', - 'here=$(dirname "$0")\n' + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + 'here=$(dirname "$0")\n' + DD_ANTICHEAT_SETUP + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1) @@ -1332,10 +1406,18 @@ def tool_catalog(steam_root, extras=None): continue extras[first_key(os.path.join(tool_dir, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or entry] = entry for name, entry in sorted(extras.items()): - catalog.append(tool_entry(name, display_name(entry), os.path.join(tools, entry), False)) + tool = tool_entry(name, display_name(entry), os.path.join(tools, entry), False) + if x86_64_layout(os.path.join(tools, entry)): + tool["x86_64"] = True + catalog.append(tool) return catalog +def x86_64_layout(path): + return (os.path.isdir(os.path.join(path, "files", "lib", "wine", "x86_64-unix")) and + not os.path.isdir(os.path.join(path, "files", "bin-arm64"))) + + def built_from(name, catalog, runnable=None): depot = VALVE_DEPOTS.get(name) tools = [t["name"] for t in catalog if depot and t["valve"] and t["dir"] == depot and @@ -1474,7 +1556,7 @@ ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64") def own_builds(tools): return [t for t in tools if isinstance(t, dict) and not t.get("valve") and - isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")] + isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name") and not t.get("x86_64")] def build_key(name): @@ -1512,7 +1594,8 @@ def choose_default(steam_default, state, request, catalog, adopt_steam=True, app wanted = requested_tool(request, catalog) state["applied"] = seq if wanted: - if wanted != state.get("default"): + if wanted != state.get("default") or (state.get("source") not in ("app", "steam") and any( + t["name"] == wanted and t.get("x86_64") for t in catalog)): state.update(default=wanted, seq=now or now_ms(), source="app") else: print("steam-compatibility: the app asked for %s, which is not installed; kept %s" % ( @@ -1709,7 +1792,11 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non read_json(state_path("request.json", directory)), catalog) else: default = state.get("default") if state.get("default") in names else TOOL - if settle and newest and default == TOOL and state.get("source") not in ("app", "steam"): + automatic = state.get("source") not in ("app", "steam") + if settle and automatic and default in {t["name"] for t in catalog if t.get("x86_64")}: + default = newest or TOOL + state.update(default=default, seq=now_ms(), source="update") + elif settle and newest and default == TOOL and automatic: default = newest state.update(default=newest, seq=now_ms(), source="update") state.pop("own_proton", None) 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/linuxfs/preload/vdec.c b/tools/linuxfs/preload/vdec.c index 3bd38f3bc9..89e62129cf 100644 --- a/tools/linuxfs/preload/vdec.c +++ b/tools/linuxfs/preload/vdec.c @@ -957,8 +957,9 @@ __attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) { __attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(struct pollfd *, nfds_t, int), int *ret) { - if (n != 1 || vd_find(fds[0].fd) == NULL) return 0; + if (n != 1 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return 0; struct vdec *v = vd_find(fds[0].fd); + if (v == NULL) return 0; pthread_mutex_lock(&vd_lock); short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0); pthread_mutex_unlock(&vd_lock); diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index 7fc21d0cab..446996a06e 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -18,6 +19,9 @@ #include +#ifndef PR_SET_SYSCALL_USER_DISPATCH +#define PR_SET_SYSCALL_USER_DISPATCH 59 +#endif #ifndef MADV_PAGEOUT #define MADV_PAGEOUT 21 #endif @@ -538,13 +542,40 @@ static int zr_start(void) { return 0; } +static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec"))); + +int prctl(int option, ...) { + va_list ap; + va_start(ap, option); + unsigned long arg2 = va_arg(ap, unsigned long); + unsigned long arg3 = va_arg(ap, unsigned long); + unsigned long arg4 = va_arg(ap, unsigned long); + unsigned long arg5 = va_arg(ap, unsigned long); + va_end(ap); + volatile unsigned char *dispatch = zr_dispatch; + unsigned char selector = dispatch != NULL ? *dispatch : 0; + if (selector) *dispatch = 0; + long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5); + if (selector) *dispatch = selector; + if ((unsigned long)result > -4096UL) { + errno = (int)-result; + return -1; + } + if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL; + return (int)result; +} + static void zr_handler(int sig, siginfo_t *info, void *context) { (void)sig; (void)context; if (info == NULL || info->si_code != SI_USER) return; + volatile unsigned char *dispatch = zr_dispatch; + unsigned char selector = dispatch != NULL ? *dispatch : 0; + if (selector) *dispatch = 0; int saved = errno; if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0); errno = saved; + if (selector) *dispatch = selector; } static void zr_child(void) { 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 546531c6dd..ede8c4354d 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -374,6 +374,8 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ENOSYS; return -1; } + if (is_proc_self_exe(filename) && g_real_exe[0] != '\0') filename = g_real_exe; + 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. @@ -538,11 +540,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; @@ -660,7 +660,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); @@ -1067,6 +1079,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, @@ -1076,7 +1297,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/fileops.c b/tools/nativeguest/hook/fileops.c index 840812fe69..81a10b89e5 100644 --- a/tools/nativeguest/hook/fileops.c +++ b/tools/nativeguest/hook/fileops.c @@ -422,6 +422,7 @@ static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, s if (ret <= 0 || out == buf) return ret; size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz; memcpy(buf, out, n); + if (n < bufsiz) buf[n] = '\0'; return (ssize_t)n; } @@ -454,6 +455,7 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { static ssize_t (*orig_readlinkat)(int, const char *, char *, size_t) = NULL; if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat"); + const char *given = pathname; DDNATV_AT_REMAP(dirfd, pathname); // after the remap: "proc/self/exe" relative to a descriptor for "/" is /proc/self/exe as well { @@ -478,7 +480,7 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { const char *retry = usrmerge_retry_path(target, alt, sizeof(alt)); if (retry) ret = orig_readlinkat(dirfd, retry, out, outsiz); } - return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz)); + return copy_readlink_result(buf, bufsiz, out, postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, out, ret, outsiz)); } // Fortified readlink variants used by dpkg / update-alternatives @@ -739,10 +741,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; } @@ -778,7 +778,7 @@ char *realpath(const char *path, char *resolved_path) { char pbuf[PATH_MAX]; const char *target = rewrite_path(path, pbuf, sizeof(pbuf)); char *res = orig_realpath ? orig_realpath(target, resolved_path) : NULL; - if (res && g_ddnatv_root[0] != '\0') { + if (res && g_ddnatv_root[0] != '\0' && !is_rootfs_real_path(path)) { size_t rlen = g_ddnatv_root_len; if (strncmp(res, g_ddnatv_root, rlen) == 0 && (res[rlen] == '/' || res[rlen] == '\0')) { size_t rem_len = strlen(res + rlen); @@ -790,7 +790,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..7ea658d006 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]; @@ -197,6 +197,116 @@ static int open_proc_status_at(int dirfd, const char *name, int flags) { return open_proc_status(dir, flags); } +static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5, unsigned long a6); + +#ifndef F_SEAL_EXEC +#define F_SEAL_EXEC 0x0020 +#endif +#ifndef MFD_EXEC +#define MFD_EXEC 0x0010U +#endif + +static int own_fd_of_path(const char *path) { + if (!path) return -1; + const char *p; + if (strncmp(path, "/dev/fd/", 8) == 0) { + p = path + 8; + } else { + if (!is_proc_fd_link(path)) return -1; + const char *who = path + 6; + if (*who >= '0' && *who <= '9') { + long pid = 0; + while (*who >= '0' && *who <= '9') pid = pid * 10 + (*who++ - '0'); + if (pid != (long)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0)) { + char task[48]; + snprintf(task, sizeof(task), "/proc/self/task/%ld", pid); + if (call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)task, F_OK, 0, 0, 0) != 0) return -1; + } + } + p = strstr(path + 6, "/fd/") + 4; + } + if (*p < '0' || *p > '9') return -1; + long fd = 0; + while (*p >= '0' && *p <= '9') { + fd = fd * 10 + (*p++ - '0'); + if (fd > INT_MAX) return -1; + } + return *p == '\0' ? (int)fd : -1; +} + +static int copy_memfd_contents(int from, int to, off_t size) { + char chunk[32768]; + off_t at = 0; + while (at < size) { + size_t want = (size_t)(size - at) < sizeof(chunk) ? (size_t)(size - at) : sizeof(chunk); + long got = call_orig_syscall(SYS_pread64, (unsigned long)from, (unsigned long)chunk, want, (unsigned long)at, 0, 0); + if (got < 0 && errno == EINTR) continue; + if (got <= 0) return -1; + long done = 0; + while (done < got) { + long put = call_orig_syscall(SYS_write, (unsigned long)to, (unsigned long)(chunk + done), (unsigned long)(got - done), 0, 0, 0); + if (put < 0 && errno == EINTR) continue; + if (put <= 0) return -1; + done += put; + } + at += got; + } + return 0; +} + +static int copy_of_memfd(int src, int flags) { + char link[48], target[PATH_MAX]; + snprintf(link, sizeof(link), "/proc/thread-self/fd/%d", src); + long n = call_orig_syscall(SYS_readlinkat, (unsigned long)AT_FDCWD, (unsigned long)link, (unsigned long)target, sizeof(target) - 1, 0, 0); + if (n <= 7 || strncmp(target, "/memfd:", 7) != 0) return -1; + target[n] = '\0'; + char *name = target + 7; + size_t name_len = (size_t)n - 7; + if (name_len >= 10 && strcmp(name + name_len - 10, " (deleted)") == 0) name[name_len -= 10] = '\0'; + if (name_len > 249) name[249] = '\0'; + struct stat st; + if (call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISREG(st.st_mode)) return -1; + long seals = call_orig_syscall(SYS_fcntl, (unsigned long)src, F_GET_SEALS, 0, 0, 0, 0); + if (seals < 0) return -1; + unsigned long mfd_flags = MFD_ALLOW_SEALING | ((flags & O_CLOEXEC) ? MFD_CLOEXEC : 0); + long copy = -1; + if (st.st_mode & 0111) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags | MFD_EXEC, 0, 0, 0, 0); + if (copy < 0) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags, 0, 0, 0, 0); + if (copy < 0) return -1; + int ok = copy_memfd_contents(src, (int)copy, st.st_size) == 0 && + call_orig_syscall(SYS_lseek, (unsigned long)copy, 0, SEEK_SET, 0, 0, 0) == 0 && + call_orig_syscall(SYS_fchmod, (unsigned long)copy, st.st_mode & 07777, 0, 0, 0, 0) == 0 && + call_orig_syscall(SYS_fcntl, (unsigned long)copy, F_ADD_SEALS, (unsigned long)(seals | F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK), 0, 0, 0) == 0; + if (!ok) { + call_orig_syscall(SYS_close, (unsigned long)copy, 0, 0, 0, 0, 0); + return -1; + } + return (int)copy; +} + +static int reopen_denied_memfd(const char *path, int flags) { + if ((flags & O_ACCMODE) != O_RDONLY || (flags & (O_CREAT | O_TRUNC | O_DIRECTORY | O_PATH))) return -1; + int named = own_fd_of_path(path); + if (named < 0) return -1; + long src = call_orig_syscall(SYS_fcntl, (unsigned long)named, F_DUPFD_CLOEXEC, 0, 0, 0, 0); + if (src < 0) return -1; + struct stat by_path, by_fd; + int same = call_orig_syscall(SYS_newfstatat, (unsigned long)AT_FDCWD, (unsigned long)path, (unsigned long)&by_path, 0, 0, 0) == 0 && + call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&by_fd, 0, 0, 0, 0) == 0 && + by_path.st_dev == by_fd.st_dev && by_path.st_ino == by_fd.st_ino; + int copy = same ? copy_of_memfd((int)src, flags) : -1; + call_orig_syscall(SYS_close, (unsigned long)src, 0, 0, 0, 0, 0); + return copy; +} + +static int open_or_reopen_memfd(int fd, const char *path, int flags) { + if (fd >= 0 || errno != EACCES) return fd; + int copy = reopen_denied_memfd(path, flags); + if (copy >= 0) return copy; + errno = EACCES; + return -1; +} + // Hook open int open(const char *pathname, int flags, ...) { static int (*orig_open)(const char *, int, ...) = NULL; @@ -225,7 +335,7 @@ int open(const char *pathname, int flags, ...) { forget_proc_root_fd(fd); return fd; } - int fd = orig_open(target, flags); + int fd = open_or_reopen_memfd(orig_open(target, flags), pathname, flags); remember_proc_root_fd(fd, pathname); return fd; } @@ -259,7 +369,7 @@ int openat(int dirfd, const char *pathname, int flags, ...) { forget_proc_root_fd(fd); return fd; } - int fd = orig_openat(dirfd, target, flags); + int fd = open_or_reopen_memfd(orig_openat(dirfd, target, flags), (pathname && pathname[0] == '/') ? pathname : NULL, flags); remember_proc_root_fd(fd, pathname); return fd; } @@ -304,6 +414,11 @@ static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, u return orig_syscall ? orig_syscall(number, a1, a2, a3, a4, a5, a6) : syscall(number, a1, a2, a3, a4, a5, a6); } +static int openat2_or_reopen_memfd(int fd, const char *pathname, const struct ddnatv_open_how *how) { + if (fd >= 0 || errno != EACCES || pathname[0] != '/' || !how || how->resolve) return fd; + return open_or_reopen_memfd(fd, pathname, (int)how->flags); +} + // Hook openat2 (used by GNU tar 1.35+/gnulib for RESOLVE_BENEATH traversal). // Rewrites absolute paths like openat, then delegates; on ENOSYS (kernels // without openat2, e.g. Android < 5.6) emulates with plain openat instead of @@ -334,12 +449,12 @@ int openat2(int dirfd, const char *pathname, struct ddnatv_open_how *how, size_t const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname; if (orig_openat2) { int ret = orig_openat2(dirfd, target, how, usize); - if (ret >= 0 || errno != ENOSYS) return ret; + if (ret >= 0 || errno != ENOSYS) return openat2_or_reopen_memfd(ret, pathname, how); } #ifdef __NR_openat2 long sret = call_orig_syscall(__NR_openat2, (unsigned long)dirfd, (unsigned long)target, (unsigned long)how, (unsigned long)usize, 0, 0); if (sret >= 0 || errno != ENOSYS) { - return (int)sret; + return openat2_or_reopen_memfd((int)sret, pathname, how); } #endif if (!how || usize < 16) { @@ -646,6 +761,7 @@ int lstat(const char *pathname, struct stat *statbuf) { int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) { static int (*orig_fstatat)(int, const char *, struct stat *, int) = NULL; if (!orig_fstatat) orig_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat"); + const char *given = pathname; DDNATV_AT_REMAP(dirfd, pathname); char buf[PATH_MAX]; const char *target = (pathname && pathname[0] == '/') ? ((flags & AT_SYMLINK_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf)) : pathname; @@ -665,7 +781,7 @@ int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) { if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat"); ssize_t llen = orig_readlinkat ? orig_readlinkat(dirfd, target, link_buf, sizeof(link_buf) - 1) : -1; if (llen > 0) { - ssize_t post_len = postprocess_readlink(pathname, link_buf, llen, sizeof(link_buf)); + ssize_t post_len = postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, link_buf, llen, sizeof(link_buf)); if (post_len > 0) { statbuf->st_size = post_len; } 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 89605e1ebb..e8f9060b45 100644 --- a/tools/nativeguest/hook/paths.c +++ b/tools/nativeguest/hook/paths.c @@ -952,6 +952,30 @@ static int is_proc_fd_link(const char *path) { return *p == '\0'; } +static int is_proc_cwd_link(const char *path) { + if (!path || strncmp(path, "/proc/", 6) != 0) return 0; + const char *p = path + 6; + if (strncmp(p, "self/", 5) == 0) { + p += 5; + } else if (strncmp(p, "thread-self/", 12) == 0) { + p += 12; + } else { + if (*p < '0' || *p > '9') return 0; + while (*p >= '0' && *p <= '9') p++; + if (*p != '/') return 0; + p++; + } + return strcmp(p, "cwd") == 0; +} + +static int is_rootfs_real_path(const char *path) { + return path && g_ddnatv_root_len > 0 && is_path_prefix(path, g_ddnatv_root, g_ddnatv_root_len); +} + +static int link_answers_in_kernel_form(const char *linkpath, const char *named) { + return is_proc_fd_link(linkpath) || is_proc_cwd_link(linkpath) || is_rootfs_real_path(named); +} + // The guest path of a folder that a session mount puts outside the rootfs, for what the kernel // reports as its real place (getcwd(), /proc/self/cwd and fd links). Wine found no DOS drive for // Sekiro's folder on the SD card library ("starting in the Windows directory"), and the game quit. @@ -975,7 +999,21 @@ static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int return best->dst_len + rest; } -static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) { +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_named_readlink(const char *linkpath, const char *named, char *buf, ssize_t ret, size_t bufsiz) { if (ret <= 0) return ret; if ((size_t)ret < bufsiz) { buf[ret] = '\0'; @@ -984,7 +1022,7 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret ret = (ssize_t)guest_path_of_mount_source(buf, (size_t)ret, bufsiz, NULL); // 1. Strip g_ddnatv_root if target starts with it - if (g_ddnatv_root_len > 0 && !is_proc_fd_link(linkpath)) { + if (g_ddnatv_root_len > 0 && !link_answers_in_kernel_form(linkpath, named)) { size_t rlen = g_ddnatv_root_len; if ((size_t)ret >= rlen && memcmp(buf, g_ddnatv_root, rlen) == 0 && ((size_t)ret == rlen || buf[rlen] == '/')) { @@ -1039,6 +1077,10 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret return ret; } +static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) { + return postprocess_named_readlink(linkpath, linkpath, buf, ret, bufsiz); +} + // Android's SELinux label, which the xattr hooks keep away from Ubuntu programs. static const char k_selinux_xattr[] = "security.selinux"; diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 7abb578071..9fd5a8077f 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 @@ -270,8 +235,16 @@ static int sandbox_only_limit(int resource, const struct rlimit *rlim) { return 0; } +// The kernel checks RLIMIT_RTTIME on a thread that is realtime or has a CPU-time timer armed, and a +// limit of 0 is reached at once: SIGXCPU at the soft limit, SIGKILL at the hard one. SDL sets the +// RTTimeUSecMax it reads from org.freedesktop.portal.Realtime before it asks for a realtime thread, +// and xdg-desktop-portal reports 0 when it reaches no RealtimeKit, as in a session with no system bus. +static int fatal_limit(int resource, const struct rlimit *rlim) { + return rlim && resource == RLIMIT_RTTIME && rlim->rlim_cur == 0; +} + int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) { - if (sandbox_only_limit((int)resource, rlim)) return 0; + if (sandbox_only_limit((int)resource, rlim) || fatal_limit((int)resource, rlim)) return 0; static int (*orig_setrlimit)(__rlimit_resource_t, const struct rlimit *) = NULL; #if defined(__USE_FILE_OFFSET64) && !defined(__LP64__) // With 64-bit file offsets on a 32-bit system this function is setrlimit64 @@ -374,6 +347,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 +418,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 +556,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 +654,33 @@ 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_execve + if (number == __NR_execve) { + return (long)execve((const char *)arg1, (char *const *)arg2, (char *const *)arg3); + } +#endif + +#ifdef __NR_execveat + if (number == __NR_execveat && arg2 && ((const char *)arg2)[0] != '\0' && + (((const char *)arg2)[0] == '/' || (int)arg1 == AT_FDCWD) && (arg5 & ~(unsigned long)AT_EMPTY_PATH) == 0) { + return (long)execve((const char *)arg2, (char *const *)arg3, (char *const *)arg4); + } +#endif + #ifdef __NR_clone3 if (number == __NR_clone3) { errno = ENOSYS; @@ -821,82 +875,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..d94956af5a 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)) @@ -305,6 +307,7 @@ static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) { size_t len = strlen(out_path); size_t copy_len = (len < bufsiz) ? len : bufsiz; memcpy(buf, out_path, copy_len); + if (copy_len < bufsiz) buf[copy_len] = '\0'; return (ssize_t)copy_len; } diff --git a/tools/nativeguest/hook/signals.c b/tools/nativeguest/hook/signals.c index 0b5765070d..3d370bae28 100644 --- a/tools/nativeguest/hook/signals.c +++ b/tools/nativeguest/hook/signals.c @@ -10,6 +10,12 @@ #define SYS_SECCOMP 1 #endif +#if defined(__aarch64__) +#define DDNATV_HOST_AUDIT_ARCH 0xC00000B7U +#else +#define DDNATV_HOST_AUDIT_ARCH 0x40000028U +#endif + static int (*get_real_sigaction(void))(int, const struct sigaction *, struct sigaction *); // A program's own SIGSYS handler, for the traps of a seccomp filter it installed itself (Firefox's @@ -33,10 +39,37 @@ 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; - if (info->si_code != SYS_SECCOMP) { + int host_trap = info->si_code == SYS_SECCOMP && info->si_errno == 0 && info->si_arch == DDNATV_HOST_AUDIT_ARCH; + if (!host_trap && g_app_sigsys_set) { + if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx); + else g_app_sigsys.sa_handler(sig); + return; + } + if (!host_trap) { int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction(); if (real_sig) { struct sigaction sa_dfl; @@ -48,15 +81,13 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) { raise(sig); return; } - if (info->si_errno != 0 && g_app_sigsys_set) { - if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx); - else g_app_sigsys.sa_handler(sig); - return; - } ucontext_t *uctx = (ucontext_t *)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 +181,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 +272,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 +291,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..11cfd85080 100644 --- a/tools/tests/effects_source_cache_harness.c +++ b/tools/tests/effects_source_cache_harness.c @@ -51,6 +51,110 @@ 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 unsigned area_copies, search_copies, weight_passes; +static void VKAPI_CALL bind_pipeline(VkCommandBuffer c, VkPipelineBindPoint b, VkPipeline p) { + if (p != g_pipe[P_SMAA_WEIGHTS]) return; + weight_passes++; + assert(area_copies == weight_passes && search_copies == weight_passes); +} +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 VKAPI_CALL copy_table(VkCommandBuffer c, VkBuffer b, VkImage i, VkImageLayout l, + uint32_t n, const VkBufferImageCopy *r) { + assert(i == g_smaa_area.img || i == g_smaa_search.img); + if (i == g_smaa_area.img) area_copies++; + else search_copies++; +} + +static void record_into_stubs(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_vk.CmdCopyBufferToImage = copy_table; +} + +static void check_smaa_tables(void) { + record_into_stubs(); + g_rp = g_smaa_edge_rp = g_smaa_weights_rp = (VkRenderPass)(uintptr_t)5; + for (int k = P_FXAA; k <= P_SMAA_BLEND; k++) g_pipe[k] = (VkPipeline)(uintptr_t)(60 + k); + g_smaa_buf = (VkBuffer)(uintptr_t)7; + g_smaa_area.img = (VkImage)(uintptr_t)40; + g_smaa_search.img = (VkImage)(uintptr_t)41; + g_ready = 1; + struct fx_target *targets[] = {&g_t[0], &g_smaa_edges, &g_smaa_weights}; + for (int k = 0; k < 3; k++) { + targets[k]->img = (VkImage)(uintptr_t)(30 + k); targets[k]->w = 1280; targets[k]->h = 720; + } + vkp_effects_set_screen(0, 0, 1, 100, 2, 0, 0, 0); + for (unsigned frame = 1; frame <= 2; frame++) { + int w, h; + assert(vkp_effects_run(VK_NULL_HANDLE, (VkImage)(uintptr_t)10, 1280, 720, 1280, 720, &w, &h) == g_t[0].img); + assert(weight_passes == frame && area_copies == frame && search_copies == frame); + } +} + +static void check_generated_settings_and_layout(void) { + record_into_stubs(); + 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(1280, 720, 1920, 1080)); + 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 +188,22 @@ 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], "smaa-tables")) { + check_smaa_tables(); + } 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_anticheat_routing.py b/tools/tests/test_anticheat_routing.py new file mode 100644 index 0000000000..6f3666a464 --- /dev/null +++ b/tools/tests/test_anticheat_routing.py @@ -0,0 +1,245 @@ +import json +import os +from pathlib import Path +import runpy +import subprocess +import tempfile +import unittest + + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +COMPAT = runpy.run_path(str(BIN / "steam-compatibility"), run_name="steam_compatibility") +SETUP = COMPAT["DD_ANTICHEAT_SETUP"] + + +class AntiCheatRoutingTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.steam = self.root / "Steam" + self.common = self.steam / "steamapps" / "common" + self.tools = self.steam / "compatibilitytools.d" + self.game = self.common / "Some Game" + self.game.mkdir(parents=True) + self.tools.mkdir(parents=True) + self.record = self.root / "record.json" + self.fex = self.root / "droiddeck-fex" + self.fex.write_text("#!/bin/bash\nif [ \"$1\" = update ]; then echo \"$1\" >> \"$DD_RECORD.update\"; " + "[ -n \"${DD_UPDATED_PATCHES:-}\" ] && printf '%s\\n' \"$DD_UPDATED_PATCHES\" > \"$DD_PATCHES\"; exit 0; fi\n" + "python3 -c 'import json,os,sys; json.dump({\"argv\": sys.argv[2:], " + "\"eac\": os.environ.get(\"PROTON_EAC_RUNTIME\"), \"be\": os.environ.get(\"PROTON_BATTLEYE_RUNTIME\")}, " + "open(sys.argv[1], \"w\"))' \"$DD_RECORD\" \"$@\"\n") + self.fex.chmod(0o755) + self.patches = self.root / "fex-patches" + self.patches.write_text("openat2-enosys-fallback\nfixed-guest-memory-above-host-address-limit\n") + + def tool(self, name, x86_64=True): + tool = self.tools / name + (tool / "files" / "lib" / "wine" / ("x86_64-unix" if x86_64 else "aarch64-unix")).mkdir(parents=True) + if not x86_64: + (tool / "files" / "bin-arm64").mkdir() + (tool / "proton").write_text("#!/bin/sh\n") + (tool / "proton").chmod(0o755) + return tool + + def runtime(self, name, library): + folder = self.common / name / "v2" / "lib64" + folder.mkdir(parents=True) + (folder / library).write_text("") + return self.common / name + + def file(self, relative): + path = self.game / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("{}") + + def launch(self, verb="waitforexitandrun", extra=None): + script = SETUP.replace("/usr/local/bin/droiddeck-fex", str(self.fex)).replace( + "/usr/local/share/fex-emu/.droiddeck-patches", str(self.patches)) + ( + "dd_game_cpus() { :; }\n" + "verb=$1; shift\n" + "dd_anticheat \"$@\"\n" + "echo stayed\n") + env = {"PATH": os.environ["PATH"], "HOME": str(self.root), "DD_RECORD": str(self.record), "DD_PATCHES": str(self.patches), + "STEAM_COMPAT_INSTALL_PATH": str(self.game), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.steam)} + env.update(extra or {}) + result = subprocess.run(["bash", "-c", script, "launcher", verb, str(self.game / "game.exe")], + env=env, capture_output=True, text=True, timeout=30) + routed = json.loads(self.record.read_text()) if self.record.exists() else None + return result, routed + + def test_eos_easy_anti_cheat_runs_the_newest_x86_64_build_under_fex(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + newest = self.tool("DroidDeck-Proton-11.0-10-x86_64") + self.tool("DroidDeck-Proton-11.0-20", x86_64=False) + runtime = self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch() + self.assertNotIn("stayed", result.stdout) + self.assertEqual(routed["argv"], ["proton", str(newest / "proton"), "waitforexitandrun", str(self.game / "game.exe")]) + self.assertEqual(routed["eac"], str(runtime)) + self.assertIn("running DroidDeck-Proton-11.0-10-x86_64 under FEX", result.stderr) + + def test_battleye_sets_its_own_runtime(self): + self.file("BattlEye/BEClient_x64.so") + tool = self.tool("DroidDeck-Proton-11.0-1-x86_64") + runtime = self.runtime("Proton BattlEye Runtime", "beclient_x64.so") + _, routed = self.launch() + self.assertEqual((routed["argv"][1], routed["be"], routed["eac"]), (str(tool / "proton"), str(runtime), None)) + + def test_anti_cheat_in_an_unreal_binaries_folder_is_found(self): + for found in ("Project/Binaries/Win64/BattlEye/BEService_x64.exe", "Project/Binaries/Win64/EasyAntiCheat/Settings.json"): + with self.subTest(found=found): + self.setUp() + self.file(found) + tool = self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton BattlEye Runtime", "beclient_x64.so") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + _, routed = self.launch() + self.assertEqual(routed["argv"][1], str(tool / "proton")) + + def test_a_game_with_both_kinds_uses_whichever_runtime_is_installed(self): + for installed, key in (("Proton BattlEye Runtime", "be"), ("Proton EasyAntiCheat Runtime", "eac")): + with self.subTest(installed=installed): + self.setUp() + self.file("BattlEye/BEService_x64.exe") + self.file("Project/Binaries/Win64/EasyAntiCheat/Settings.json") + tool = self.tool("DroidDeck-Proton-11.0-1-x86_64") + runtime = self.runtime(installed, "beclient_x64.so" if key == "be" else "easyanticheat_x64.so") + _, routed = self.launch() + self.assertEqual((routed["argv"][1], routed[key]), (str(tool / "proton"), str(runtime))) + + def test_a_runtime_already_set_with_files_is_kept(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + own = self.root / "own-eac" + (own / "v2").mkdir(parents=True) + (own / "v2" / "easyanticheat_x64.so").write_text("") + _, routed = self.launch(extra={"PROTON_EAC_RUNTIME": str(own)}) + self.assertEqual(routed["eac"], str(own)) + + def test_games_without_anti_cheat_files_stay_on_arm64(self): + self.file("Data/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertEqual(result.stderr, "") + + def test_without_an_x86_64_build_the_launch_stays_on_arm64(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-20", x86_64=False) + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertIn("no x86-64 DroidDeck-Proton is installed", result.stderr) + + def test_without_the_runtime_files_the_launch_stays_on_arm64(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + (self.common / "Proton EasyAntiCheat Runtime").mkdir(parents=True) + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("its Proton runtime is not installed", result.stderr) + + def test_the_user_can_turn_routing_off(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"}) + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + + def test_a_tool_the_user_chose_is_kept(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + for chosen in ("GE-Proton11-15-aarch64", "DroidDeck-Bionic-14.1-r85", "proton_experimental"): + result, routed = self.launch(extra={"DD_AC_TOOL": chosen}) + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertIn("%s was chosen for this game, so it runs as chosen" % chosen, result.stderr) + + def test_droiddeck_proton_builds_still_route(self): + self.file("EasyAntiCheat/Settings.json") + newest = self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + for own in ("DroidDeck-Proton 11-14.1", "DroidDeck-Proton-11-14.2"): + self.record.unlink(missing_ok=True) + result, routed = self.launch(extra={"DD_AC_TOOL": own}) + self.assertEqual(routed["argv"][1], str(newest / "proton")) + + def test_a_fex_build_without_high_guest_memory_stays_on_arm64(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + for patches in ("openat2-enosys-fallback\n", None): + if patches is None: + self.patches.unlink() + else: + self.patches.write_text(patches) + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertIn("the installed FEX build cannot run anti-cheat", result.stderr) + + def test_an_older_fex_build_is_updated_before_routing(self): + self.file("EasyAntiCheat/Settings.json") + tool = self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + self.patches.unlink() + result, routed = self.launch(extra={"DD_UPDATED_PATCHES": "fixed-guest-memory-above-host-address-limit"}) + self.assertEqual(routed["argv"][1], str(tool / "proton")) + self.assertNotIn("cannot run anti-cheat", result.stderr) + self.assertTrue((self.root / "record.json.update").exists()) + + def test_games_without_anti_cheat_files_do_not_update_fex(self): + self.file("Data/Settings.json") + self.launch() + self.assertFalse((self.root / "record.json.update").exists()) + + def test_choices_are_kept_the_same_with_an_older_fex_build(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + self.patches.unlink() + result, routed = self.launch(extra={"DD_AC_TOOL": "GE-Proton11-15-aarch64"}) + self.assertIsNone(routed) + self.assertIn("GE-Proton11-15-aarch64 was chosen for this game, so it runs as chosen", result.stderr) + result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"}) + self.assertIsNone(routed) + self.assertEqual(result.stderr, "") + + def test_the_fex_build_lists_its_patches(self): + build = (BIN.parents[4] / "fex" / "build-in-arch.sh").read_text() + self.assertIn("> out/usr/local/share/fex-emu/.droiddeck-patches", build) + names = {p.stem.split("-", 1)[1] for p in (BIN.parents[4] / "fex" / "patches").glob("*.patch")} + self.assertIn("fixed-guest-memory-above-host-address-limit", names) + + def test_adopted_tools_pass_their_own_folder_name(self): + wrapper = COMPAT["extra_wrapper_sh"]("proton") + self.assertIn('DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"', wrapper) + self.assertNotIn("DD_AC_TOOL=", COMPAT["LAUNCHER_SH"]) + + def test_other_verbs_are_left_alone(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch(verb="getcompatpath") + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + + def test_launchers_check_before_arm64_setup_and_x86_64_tools_run_under_fex(self): + launcher = COMPAT["LAUNCHER_SH"] + self.assertLess(launcher.index('dd_anticheat "$@"'), launcher.index('dd_components "$depot"')) + wrapper = COMPAT["extra_wrapper_sh"]("proton") + self.assertLess(wrapper.index("dd_x86_64_proton() {"), wrapper.index("dd_fallback=")) + self.assertLess(wrapper.index('droiddeck-fex proton "$here/proton"'), wrapper.index('dd_components "$here"')) + self.assertIn('! dd_x86_64_proton "$d"', wrapper) + + +if __name__ == "__main__": + unittest.main() 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_bottom_mirror_composition.py b/tools/tests/test_bottom_mirror_composition.py new file mode 100644 index 0000000000..6ddee5a720 --- /dev/null +++ b/tools/tests/test_bottom_mirror_composition.py @@ -0,0 +1,38 @@ +from pathlib import Path +import unittest + +ROOT = Path(__file__).resolve().parents[2] +NATIVE = ROOT / "app/src/main/cpp/waylandcomp/src" +APP = ROOT / "app/src/main/java/com/droiddeck/launcher" + + +class BottomMirrorCompositionTest(unittest.TestCase): + def test_mirror_requests_composition_until_its_last_consumer_leaves(self): + panel = (APP / "ui/BottomMirrorPage.kt").read_text() + self.assertIn("actions.holdComposed(true)", panel) + self.assertIn("onDispose { actions.holdComposed(false) }", panel) + activity = (APP / "SessionActivity.kt").read_text() + hold = activity.split("private fun holdComposedOutput(", 1)[1].split("private fun zeroCopyActive", 1)[0] + self.assertIn("if (held == wasHeld) return", hold) + self.assertIn("nativeSetMirrorCapture(held)", hold) + self.assertIn("if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy", hold) + self.assertIn("CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy", activity) + self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode) && composedOutputFree())", activity) + self.assertIn("nativeSetZeroCopy(composedOutputFree())", hold) + self.assertNotIn("SessionPrefs.set", hold) + + def test_compositor_selects_readable_surface_without_dropping_unimportable_hdr(self): + jni = (NATIVE / "waylandcomp_jni.c").read_text() + self.assertIn("droiddeck_host_mirror_capture(on ? 1 : 0);", jni) + host = (NATIVE / "droiddeck_ext.c").read_text() + self.assertIn("case HOST_MIRROR_CAPTURE:\n droiddeck_set_mirror_capture(m->a);", host) + compositor = (NATIVE / "compositor.c").read_text() + self.assertIn("if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {\n hdr_route = 2;", compositor) + self.assertIn("g_zero_copy && !g_mirror_capture && (!framegen || fg_layer)", compositor) + self.assertIn("if (un && g_zero_copy)", compositor) + self.assertIn("if (g_zero_copy && droiddeck_color_hdr_open()) note_hdr_unimported", compositor) + self.assertNotIn("if (g_mirror_capture) ls = NULL", compositor) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_ci_checks.py b/tools/tests/test_ci_checks.py index a5982366ac..1e7995a3d2 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'): @@ -33,14 +33,25 @@ class CiChecksTest(unittest.TestCase): robolectric = [cache['path'] for cache in caches if cache['key'].startswith('robolectric-')] self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2) + def test_only_main_saves_the_robolectric_cache(self): + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] + saves = [step for step in steps if step.get('uses', '').startswith('actions/cache/save') + and step['with']['key'].startswith('robolectric-')] + self.assertEqual(len(saves), 1) + self.assertIn("github.event_name != 'pull_request'", saves[0]['if']) + 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 +70,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 index 39b37e93a9..2f31b9aff8 100644 --- a/tools/tests/test_commit_waits_for_client_writes.py +++ b/tools/tests/test_commit_waits_for_client_writes.py @@ -74,6 +74,11 @@ static int poll(struct pollfd *p, unsigned n, int timeout) { } 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; @@ -121,6 +126,7 @@ 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]; @@ -146,6 +152,7 @@ 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; 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_decky_loader_env.py b/tools/tests/test_decky_loader_env.py new file mode 100644 index 0000000000..dbd6c4ec24 --- /dev/null +++ b/tools/tests/test_decky_loader_env.py @@ -0,0 +1,58 @@ +import os +import re +import shlex +import subprocess +import tempfile +import unittest +from pathlib import Path + +SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session" + + +def decky_job(): + match = re.search(r"^ *_dd_job_decky\(\) \{\n.*?^ {8}\}\n", SESSION.read_text(), re.M | re.S) + return match.group(0) if match else None + + +class DeckyLoaderEnvironmentTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + (self.root / "homebrew/services").mkdir(parents=True) + + def loader_environment(self, inherited=None): + job = decky_job() + self.assertIsNotNone(job, "droiddeck-session has no _dd_job_decky()") + seen = self.root / "seen.env" + loader = self.root / "PluginLoader" + loader.write_text("#!/bin/sh\nenv > %s\nexit 1\n" % shlex.quote(str(seen))) + loader.chmod(0o755) + script = "sleep() { :; }\n" + job + script += "decky_arch=arm64\ndecky_loader=%s\n_dd_job_decky\n" % shlex.quote(str(loader)) + env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(self.root)} + env.update(inherited or {}) + out = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30, env=env, check=True).stdout + self.assertIn("stopped after 5 loader exits", out) + return dict(line.split("=", 1) for line in seen.read_text().splitlines() if "=" in line) + + def test_the_loader_runs_without_its_file_watcher(self): + self.assertEqual("0", self.loader_environment().get("LIVE_RELOAD")) + + def test_a_live_reload_from_the_session_environment_does_not_reach_the_loader(self): + self.assertEqual("0", self.loader_environment({"LIVE_RELOAD": "1"}).get("LIVE_RELOAD")) + + def test_the_loader_still_runs_as_root_and_keeps_its_plugin_permission_fixes(self): + env = self.loader_environment() + self.assertEqual("root", env.get("UNPRIVILEGED_USER")) + self.assertNotIn("CHOWN_PLUGIN_PATH", env) + + def test_only_the_decky_job_sets_live_reload(self): + text = SESSION.read_text() + job = decky_job() + self.assertEqual(1, text.count("LIVE_RELOAD")) + self.assertIn("export LIVE_RELOAD=0", job) + + +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_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 79f7043cbb..5bd2596b88 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -1235,6 +1235,29 @@ class LaunchTest(FexTestCase): self.assertEqual(emulated.call_args[0][2]["FEX_ROOTFS"], str(platform / "files")) self.assertEqual(FEX["required_runtime"](str(self.proton("1391110"))), "1628350") + def test_an_adopted_proton_keeps_the_runtime_of_its_original_manifest(self): + proton = self.proton("4183110") + folder = proton.parent + os.rename(folder / "toolmanifest.vdf", folder / "toolmanifest.vdf.droiddeck-orig") + self.write(folder / "toolmanifest.vdf", '"manifest"\n{\n "commandline" "/droiddeck-proton-wrap %verb%"\n}\n') + self.assertEqual(FEX["required_runtime"](str(proton)), "4183110") + os.unlink(folder / "toolmanifest.vdf.droiddeck-orig") + self.assertEqual(FEX["required_runtime"](str(proton)), "1628350") + + def test_proton_action_keeps_the_prefix_and_runs_under_fex(self): + self.fex_tool() + self.runtime() + proton = self.proton("1628350") + prefix = str(self.tmp / "compatdata" / "730") + env = {"STEAM_COMPAT_DATA_PATH": prefix} + with mock.patch.dict(os.environ, env, clear=False), mock.patch("os.execve") as emulated: + self.quiet(FEX["main"], ["proton", str(proton), "waitforexitandrun", "game.exe"]) + command, guest = emulated.call_args[0][1], emulated.call_args[0][2] + self.assertEqual(command[1:], [str(proton), "waitforexitandrun", "game.exe"]) + self.assertEqual(guest["STEAM_COMPAT_DATA_PATH"], prefix) + self.assertNotEqual(FEX["guest_environment"]({"portable": True}, env)["STEAM_COMPAT_DATA_PATH"], prefix) + self.assertEqual(FEX["main"](["proton", str(proton)]), 2) + def test_native_programs_run_directly(self): program = self.write(self.tmp / "native", elf(183), 0o755) with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated: @@ -1351,6 +1374,48 @@ class LaunchTest(FexTestCase): self.assertEqual(started(unity, "10")[:2], ("1", None)) self.assertEqual(started(other, "10")[:2], (None, None)) + def test_x86_64_proton_launches_keep_the_game_debug_and_graphics_logs(self): + config = self.home / ".config/droiddeck/game-environment.json" + session = self.tmp / "session" + session.mkdir() + proton = str(self.tmp / "Proton x86-64/proton") + + def started(verb, debug, extra=None): + self.write(config, json.dumps({"version": 1, "gameDebugLogs": debug, + "games": {"976730": {"DXVK_HUD": "fps"}}})) + env = {"SteamAppId": "976730", "SteamGameId": "976730", "DD_DEBUG_DIR": str(session), **(extra or {})} + with mock.patch.dict(G, {"launch": mock.Mock(return_value=0), "GAME_ENVIRONMENT": str(config)}), \ + mock.patch.dict(os.environ, env, clear=True), mock.patch("subprocess.Popen") as capped: + _, said = self.quiet(FEX["main"], ["proton", proton, verb, "C:/game/game.exe"]) + command, guest, mode = G["launch"].call_args[0] + self.assertEqual((command, mode), ([proton, verb, "C:/game/game.exe"], "on")) + return guest, said, capped + + guest, said, capped = started("waitforexitandrun", True) + self.assertEqual((guest["PROTON_LOG"], guest["PROTON_LOG_DIR"]), ("1", str(session))) + self.assertIn("+seh", guest["WINEDEBUG"]) + self.assertEqual(guest["DXVK_HUD"], "fps") + self.assertIn("game debug logs enabled for this launch", said) + self.assertIn(str(session / "steam-976730.log"), capped.call_args[0][0]) + + guest, said, _ = started("waitforexitandrun", False, {"DD_GAME_LOGS": "1"}) + folder = Path(guest["PROTON_LOG_DIR"]) + self.assertEqual((guest["PROTON_LOG"], folder.parent), ("1", session / "games")) + self.assertTrue(folder.name.endswith("-976730")) + self.assertNotIn("game debug logs enabled", said) + + guest, _, capped = started("waitforexitandrun", False) + self.assertNotIn("PROTON_LOG", guest) + self.assertEqual(guest["DXVK_HUD"], "fps") + capped.assert_not_called() + + guest, _, capped = started("run", True) + self.assertNotIn("PROTON_LOG", guest) + capped.assert_not_called() + + guest, _, _ = started("waitforexitandrun", True, {"PROTON_LOG": "1", "PROTON_LOG_DIR": "/mine"}) + self.assertEqual(guest["PROTON_LOG_DIR"], str(session)) + class AppInfoTest(unittest.TestCase): COMPAT = runpy.run_path(str(BIN / "steam-compatibility")) diff --git a/tools/tests/test_droiddeck_proton_default.py b/tools/tests/test_droiddeck_proton_default.py index 2173a223a1..194bf022c9 100644 --- a/tools/tests/test_droiddeck_proton_default.py +++ b/tools/tests/test_droiddeck_proton_default.py @@ -15,6 +15,8 @@ VALVE_11 = {"name": COMPAT["TOOL_11"], "display": "Proton 11.0 ARM64", "dir": CO GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False} GE10 = {"name": "GE-Proton10-3", "display": "GE-Proton10-3", "dir": "GE-Proton10-3", "valve": False} NEWER = {"name": "DroidDeck-Proton-11-12.1", "display": "DroidDeck-Proton 11-12.1", "dir": "DroidDeck-Proton 11-12.1", "valve": False} +X86 = {"name": "DroidDeck-Proton-11-14.2-x86_64", "display": "DroidDeck-Proton 11-14.2 x86-64", "dir": "DroidDeck-Proton 11-14.2 x86-64", + "valve": False, "x86_64": True} def config_text(entries): @@ -204,6 +206,50 @@ class DroidDeckProtonDefaultTest(unittest.TestCase): self.assertEqual(newest, "b") self.assertEqual(gone, {OLD["name"]}) + def test_an_x86_64_build_never_becomes_the_automatic_default(self): + default, mapping, state = self.run_default( + {"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL)], [VALVE, NEW, X86], ["42"]) + self.assertEqual((default, mapping["0"]), (NEW["name"], NEW["name"])) + default, mapping, _ = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, X86]) + self.assertEqual((default, mapping), (TOOL, {"0": TOOL})) + + def test_an_automatic_x86_64_default_moves_back_to_arm64(self): + default, mapping, state = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, NEW, X86]) + self.assertEqual((default, mapping, state["source"]), (NEW["name"], {"0": NEW["name"]}, "update")) + default, mapping, _ = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, X86]) + self.assertEqual((default, mapping), (TOOL, {"0": TOOL})) + + def test_an_x86_64_default_the_user_picked_is_kept(self): + for source in ("app", "steam"): + default, mapping, _ = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": source}, [("0", X86["name"])], [VALVE, NEW, X86]) + self.assertEqual((default, mapping), (X86["name"], {"0": X86["name"]})) + + def test_a_request_for_the_automatic_x86_64_default_keeps_it(self): + default, mapping, state = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": "update", "applied": 1}, [("0", X86["name"])], + [VALVE, NEW, X86], request={"seq": 2, "name": X86["name"]}) + self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app")) + default, mapping, state = self.run_default(state, [("0", X86["name"])], [VALVE, NEW, X86], + request={"seq": 2, "name": X86["name"]}) + self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app")) + + def test_x86_64_layouts_are_marked_in_the_catalog(self): + with tempfile.TemporaryDirectory() as tmp: + tools = Path(tmp) / "compatibilitytools.d" + for entry, arm in (("DroidDeck-Proton 11-14.2 x86-64", False), ("DroidDeck-Proton 11-14.2", True)): + (tools / entry / "files" / "lib" / "wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True) + if arm: + (tools / entry / "files" / "bin-arm64").mkdir() + (tools / entry / COMPAT["EXTRA_WRAPPER"]).write_text("") + catalog = {t["dir"]: t for t in COMPAT["tool_catalog"](tmp) if not t["valve"]} + self.assertTrue(catalog["DroidDeck-Proton 11-14.2 x86-64"].get("x86_64")) + self.assertNotIn("x86_64", catalog["DroidDeck-Proton 11-14.2"]) + newest, _ = COMPAT["own_proton_moves"]({}, list(catalog.values())) + self.assertEqual(newest, catalog["DroidDeck-Proton 11-14.2"]["name"]) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_droiddeckctl.py b/tools/tests/test_droiddeckctl.py index 59f187a7f5..4873d13ce5 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(): @@ -519,7 +522,9 @@ class DroiddeckctlTest(FakeAdbTest): answer = ctl.provider_call("adb", "fake-1", "state", arg="a b", request={"x": 1}) self.assertEqual({"ok": True, "command": "state"}, answer) broadcast = next(c for c in calls if c[:2] == ("shell", "am")) - self.assertEqual(("shell", "am", "broadcast", "-a", ctl.PACKAGE + ".AGENT_CALL", "-p", ctl.PACKAGE), broadcast[:7]) + receiver = ctl.PACKAGE + "/com.droiddeck.launcher.agent.AgentCallReceiver" + self.assertEqual(("shell", "am", "broadcast", "-n", receiver), broadcast[:5]) + self.assertNotIn("-a", broadcast) self.assertIn("'a b'", broadcast) self.assertEqual(ctl.encode_request({"x": 1}), broadcast[broadcast.index("request") + 1]) call_id = broadcast[broadcast.index("id") + 1] 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..ba80771818 100644 --- a/tools/tests/test_effects_source_cache.py +++ b/tools/tests/test_effects_source_cache.py @@ -57,6 +57,15 @@ 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') + + def test_every_recorded_frame_fills_the_smaa_tables(self): + self.check_cache('smaa-tables') + 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..09c9e16f2d 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,48 @@ 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(int in_w, int in_h, int out_w, int out_h) { + (void)in_w; (void)in_h; (void)out_w; (void)out_h; + 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 +351,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 +625,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 +732,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_fex_guest_high_memory.py b/tools/tests/test_fex_guest_high_memory.py new file mode 100644 index 0000000000..ff21c4adad --- /dev/null +++ b/tools/tests/test_fex_guest_high_memory.py @@ -0,0 +1,3392 @@ +import platform +import re +import shutil +import signal +import subprocess +import tempfile +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch" +PROBE = REPO / "tools/fex/probes/guest-high-memory.c" + +SOURCE = "Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp" +HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h" + +KERNEL_NAMES = {"pread_64": "pread64", "pwrite_64": "pwrite64", "prlimit_64": "prlimit64"} +NEWER_SYSCALLS = { + "futex_wake": 454, "futex_wait": 455, "futex_requeue": 456, "statmount": 457, "listmount": 458, + "lsm_get_self_attr": 459, "lsm_set_self_attr": 460, "lsm_list_modules": 461, + "mseal": 462, "setxattrat": 463, "getxattrat": 464, "listxattrat": 465, "removexattrat": 466, +} +OLDEST_HEADERS_LAST_SYSCALL = 453 +HARNESS_SECONDS = 120 + +PRELUDE = r""" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace fextl { +template using vector = std::vector; +template using list = std::list; +template using unordered_map = std::unordered_map; +using std::make_unique; +} +namespace FEXCore { +namespace Utils { constexpr uint64_t FEX_PAGE_SIZE = 4096; } +constexpr uint64_t AlignUp(uint64_t V, uint64_t A) { return (V + A - 1) & ~(A - 1); } +namespace Allocator { inline uint64_t GetHostVABits() { return 39; } } +} +""" + +STUBS = r""" +static int MunmapFailures; +static int TestMunmap(void* Address, size_t Size) { + if (MunmapFailures > 0) { + --MunmapFailures; + errno = ENOMEM; + return -1; + } + return munmap(Address, Size); +} +#define munmap TestMunmap +static int SendCalls; +static int SendFailures; +static size_t SendLimit = ~size_t {}; +static int SentSocket = -1; +static size_t SentLengths[8]; +static struct iovec* GrowAfterSend; +static void* UnmapAfterSend; +static bool PassSend; +static int DupFailures; +static int TestSendmmsg(int Socket, struct mmsghdr* Messages, unsigned int Count, int Flags) { + if (PassSend) { + return sendmmsg(Socket, Messages, Count, Flags); + } + SentSocket = Socket; + if (Count != 1 || SendFailures > 0) { + SendFailures -= SendFailures > 0; + errno = EAGAIN; + return -1; + } + size_t Length = 0; + for (size_t i = 0; i < Messages[0].msg_hdr.msg_iovlen; ++i) { + Length += Messages[0].msg_hdr.msg_iov[i].iov_len; + } + Length = std::min(Length, SendLimit); + SentLengths[SendCalls++ & 7] = Length; + Messages[0].msg_len = Length; + if (GrowAfterSend) { + GrowAfterSend->iov_len = 64; + } + if (UnmapAfterSend) { + munmap(UnmapAfterSend, 4096); + UnmapAfterSend = nullptr; + } + return 1; +} +#define sendmmsg TestSendmmsg +static int TestFcntl(int FD, int Command, int Argument = 0) { + if (Command == F_DUPFD_CLOEXEC && DupFailures > 0) { + --DupFailures; + errno = EMFILE; + return -1; + } + return fcntl(FD, Command, Argument); +} +#define fcntl TestFcntl +static int ProtectCalls; +static int TestMprotect(void* Address, size_t Size, int Prot) { + ++ProtectCalls; + return mprotect(Address, Size, Prot); +} +#define mprotect TestMprotect +static uint64_t AioDestroyed; +static std::function AioDestroyHook; +static int AioReaps; +static uint64_t AioReapArgs[7]; +static std::function AioReapHook; +template static uint64_t SyscallWord(T Value) { + if constexpr (std::is_null_pointer_v) { + return 0; + } else if constexpr (std::is_pointer_v) { + return reinterpret_cast(Value); + } else { + return static_cast(Value); + } +} +template static long TestSyscall(long Number, T... Args) { + const uint64_t Words[] = {0, SyscallWord(Args)...}; + if (Number == SYS_io_getevents || Number == SYS_io_pgetevents) { + ++AioReaps; + std::copy_n(Words, std::min(std::size(Words), 7), AioReapArgs); + AioReapArgs[0] = Number; + if (AioReapHook) { + return AioReapHook(Words); + } + errno = EINTR; + return -1; + } + if (Number == SYS_io_destroy) { + AioDestroyed = Words[1]; + if (AioDestroyHook) { + AioDestroyHook(Words[1]); + } + errno = EINVAL; + return -1; + } + return syscall(Number, Args...); +} +#define syscall TestSyscall +namespace FEXCore { +template class LockType = std::unique_lock, typename MutexType> +inline auto MaskSignalsAndLockMutex(MutexType& Mutex, uint64_t = ~0ULL) { return LockType {Mutex}; } +} +namespace ArchHelpers::Context { +inline uint64_t GetArmReg(void* UContext, uint32_t Reg) { return static_cast(UContext)[Reg]; } +inline void SetArmReg(void* UContext, uint32_t Reg, uint64_t Value) { static_cast(UContext)[Reg] = Value; } +} +namespace FEX::HLE { +struct TestVMATracking { std::shared_mutex Mutex; }; +struct TestSyscallHandler { TestVMATracking VMATracking; }; +inline TestSyscallHandler TestHandler; +inline TestSyscallHandler* _SyscallHandler = &TestHandler; +struct TestThreadObject { + struct { + struct { + bool Held; + uint32_t Deferred; + siginfo_t DeferredInfo[3]; + } Mappings; + } HighMemoryTrap; + struct { + std::vector DeferredSignalFrames; + } SignalInfo; +}; +inline TestThreadObject TestThread {}; +struct ThreadManager { + static TestThreadObject* GetCurrentThreadObject() { return &TestThread; } +}; +inline bool HasSyscallError(uint64_t Result) { return Result >= 0xFFFF'FFFF'FFFF'0001ULL; } +namespace FaultSafeUserMemAccess { +inline size_t CopyFromUser(void* Dest, const void* Src, size_t Size) { + struct iovec Local {Dest, Size}; + struct iovec Remote {const_cast(Src), Size}; + return Size == 0 || process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0) == static_cast(Size) ? 0 : Size; +} +inline void (*BeforeUserWrite)() = nullptr; +inline size_t CopyToUser(void* Dest, const void* Src, size_t Size) { + if (auto* Hook = std::exchange(BeforeUserWrite, nullptr)) { + Hook(); + } + struct iovec Local {const_cast(Src), Size}; + struct iovec Remote {Dest, Size}; + return Size == 0 || process_vm_writev(getpid(), &Local, 1, &Remote, 1, 0) == static_cast(Size) ? 0 : Size; +} +} +namespace x64 { +ENUM +} +} +""" + +MAIN = r""" +using namespace FEX::HLE::GuestHighMemory; +namespace Sys = FEX::HLE::x64; +static void Show(const char* Name, uint64_t Value) { std::printf("%s %llx\n", Name, static_cast(Value)); } +struct TestHold { + bool Held; + uint32_t Deferred; + siginfo_t DeferredInfo[3]; +}; +static std::atomic TrapsSeen; +static std::atomic TrapCode; +static std::atomic TrapValue; +static bool ExclusiveFromAnotherThread() { + std::thread Writer([] { std::unique_lock Exclusive {FEX::HLE::_SyscallHandler->VMATracking.Mutex}; }); + Writer.join(); + return true; +} +static void CountTrap(int, siginfo_t* Info, void*) { + ++TrapsSeen; + TrapCode = Info->si_code; + TrapValue = Info->si_value.sival_int; +} +static uint64_t Call(uint32_t Syscall, uint64_t* Args, ArgumentStorage* Storage) { return TranslateSyscallArguments(Syscall, Args, 6, Storage); } +template +static uint64_t FinishResult(uint64_t Result, Arguments* Storage) { + if constexpr (std::is_void_v) { + FinishSyscallArguments(Result, Storage); + return Result; + } else { + return FinishSyscallArguments(Result, Storage); + } +} +int main() { + alarm(HARNESS_SECONDS); + const uint64_t Page = 4096; + static bool FirstHighStoreHeld; + FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] { FirstHighStoreHeld = FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held; }; + const uint32_t FirstHighValue = 1; + Show("high_store_unmapped_result", CopyToGuest(0x720000000000ULL, &FirstHighValue, sizeof(FirstHighValue))); + Show("high_store_unmapped_held", FirstHighStoreHeld); + Show("high_store_unmapped_released", FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held); + const uint64_t High = TaskTop - Page; + const uint64_t Low = 0x140000000ULL; + Show("contains_last_page", Contains(High)); + Show("contains_task_top", Contains(TaskTop)); + Show("contains_host_limit", Contains(1ULL << 39)); + Show("contains_below_limit", Contains((1ULL << 39) - Page)); + Show("claims_fixed", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED)); + Show("claims_noreplace", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE)); + Show("claims_low", ClaimsMapping(Low, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED)); + Show("claims_hint", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS)); + Show("claims_task_top", ClaimsMapping(TaskTop, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED)); + + auto* Backing = static_cast(mmap(nullptr, 8 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Base = reinterpret_cast(Backing); + const uint64_t Single = 0x7f0000000000ULL; + const uint64_t Split = 0x7e0000000000ULL; + const uint64_t Joined = 0x7d0000000000ULL; + AddEntry(Single, Page, Base, false, PROT_READ | PROT_WRITE); + AddEntry(Split, Page, Base + 2 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Split + Page, Page, Base + 4 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Joined, Page, Base + 5 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Joined + Page, Page, Base + 6 * Page, false, PROT_READ | PROT_WRITE); + ArgumentStorage Storage; + const int Peer = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0); + + uint64_t Read[6] = {3, Single + 16, 32, 0, 0, 0}; + Show("read_result", Call(Sys::SYSCALL_x64_read, Read, &Storage)); + Show("read_buffer", Read[1] - Base); + + uint64_t Truncate[6] = {3, Single + 16, 0, 0, 0, 0}; + Show("ftruncate_result", Call(Sys::SYSCALL_x64_ftruncate, Truncate, &Storage)); + Show("ftruncate_length", Truncate[1] - Single); + + uint64_t Mapping[6] = {Single, Page, 0, 0, 0, 0}; + Show("mmap_result", Call(Sys::SYSCALL_x64_mmap, Mapping, &Storage)); + Show("mmap_address", Mapping[0] - Single); + + uint64_t Unknown[6] = {Single, Single, Single, Single, Single, Single}; + Show("unknown_result", Call(1000, Unknown, &Storage)); + Show("unknown_args", Unknown[0] - Single + Unknown[5] - Single); + + uint64_t Overrun[6] = {3, Single + Page - 8, 64, 0, 0, 0}; + Show("overrun_result", Call(Sys::SYSCALL_x64_read, Overrun, &Storage)); + + uint64_t Apart[6] = {3, Split + Page - 96, 200, 0, 0, 0}; + Show("split_result", Call(Sys::SYSCALL_x64_read, Apart, &Storage)); + + uint64_t Together[6] = {3, Joined + Page - 96, 200, 0, 0, 0}; + Show("joined_result", Call(Sys::SYSCALL_x64_read, Together, &Storage)); + Show("joined_buffer", Together[1] - Base); + + uint64_t Write[6] = {3, Split + Page - 96, 96, 0, 0, 0}; + Show("fits_result", Call(Sys::SYSCALL_x64_write, Write, &Storage)); + + uint64_t PollApart[6] = {Split + Page - 96, 25, 0, 0, 0, 0}; + Show("poll_split_result", Call(Sys::SYSCALL_x64_poll, PollApart, &Storage)); + uint64_t PollFits[6] = {Split + Page - 96, 12, 0, 0, 0, 0}; + Show("poll_fits_result", Call(Sys::SYSCALL_x64_poll, PollFits, &Storage)); + uint64_t PollJoined[6] = {Joined + Page - 96, 25, 0, 0, 0, 0}; + Show("poll_joined_result", Call(Sys::SYSCALL_x64_poll, PollJoined, &Storage)); + uint64_t PollHuge[6] = {Single, 1ULL << 61, 0, 0, 0, 0}; + Show("poll_huge_result", Call(Sys::SYSCALL_x64_poll, PollHuge, &Storage)); + uint64_t EpollApart[6] = {3, Split + Page - 96, 9, 0, 0, 0}; + Show("epoll_split_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollApart, &Storage)); + uint64_t EpollFits[6] = {3, Split + Page - 96, 8, 0, 0, 0}; + Show("epoll_fits_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollFits, &Storage)); + uint64_t SelectApart[6] = {1024, Split + Page - 64, 0, 0, 0, 0}; + Show("select_split_result", Call(Sys::SYSCALL_x64_select, SelectApart, &Storage)); + uint64_t SelectFits[6] = {512, Split + Page - 64, 0, 0, 0, 0}; + Show("select_fits_result", Call(Sys::SYSCALL_x64_select, SelectFits, &Storage)); + uint64_t SelectWide[6] = {(1ULL << 32) + 1, Single, 0, 0, 0, 0}; + Show("select_wide_result", Call(Sys::SYSCALL_x64_select, SelectWide, &Storage)); + Show("fits_buffer", Write[1] - Base); + + char LowBuffer[16]; + struct iovec Guest[2] = {{reinterpret_cast(Single + 64), 32}, {LowBuffer, sizeof(LowBuffer)}}; + uint64_t Vector[6] = {3, reinterpret_cast(Guest), 2, 0, 0, 0}; + Show("readv_result", Call(Sys::SYSCALL_x64_readv, Vector, &Storage)); + const auto* HostVector = reinterpret_cast(Vector[1]); + Show("readv_copied", HostVector != Guest); + Show("readv_high_base", reinterpret_cast(HostVector[0].iov_base) - Base); + Show("readv_low_base", HostVector[1].iov_base == LowBuffer); + Show("readv_guest_untouched", reinterpret_cast(Guest[0].iov_base) - Single); + + struct iovec LowOnly[1] = {{LowBuffer, sizeof(LowBuffer)}}; + uint64_t Plain[6] = {3, reinterpret_cast(LowOnly), 1, 0, 0, 0}; + Show("writev_result", Call(Sys::SYSCALL_x64_writev, Plain, &Storage)); + Show("writev_untouched", Plain[1] == reinterpret_cast(LowOnly)); + + struct iovec Straddle[1] = {{reinterpret_cast(Split + Page - 8), 16}}; + uint64_t Crossing[6] = {3, reinterpret_cast(Straddle), 1, 0, 0, 0}; + Show("writev_split_result", Call(Sys::SYSCALL_x64_writev, Crossing, &Storage)); + + ArgumentStorage Receive; + struct iovec Incoming[1] = {{reinterpret_cast(Single + 128), 64}}; + struct msghdr Header {}; + Header.msg_iov = Incoming; + Header.msg_iovlen = 1; + uint64_t Message[6] = {3, reinterpret_cast(&Header), 0, 0, 0, 0}; + Show("recvmsg_result", Call(Sys::SYSCALL_x64_recvmsg, Message, &Receive)); + const auto* HostHeader = reinterpret_cast(Message[1]); + Show("recvmsg_copied", HostHeader != &Header); + Show("recvmsg_base", reinterpret_cast(HostHeader->msg_iov[0].iov_base) - Base); + Receive.Message.msg_flags = MSG_TRUNC; + FinishSyscallArguments(64, &Receive); + Show("recvmsg_flags", Header.msg_flags); + Show("recvmsg_guest_iov", Header.msg_iov == Incoming); + + Show("to_guest", ToGuest(Base + 6 * Page + 8) - Joined); + Show("to_guest_low", ToGuest(Low) == Low); + + const uint32_t ExclusiveOps[] = {0xc85f7c20, 0x885ffc20, 0x085ffc20, 0x485f7c20, 0xc8027c20, 0xc802fc20, + 0x0802fc20, 0xc87f0820, 0x887f8820, 0xc8230820, 0xc8238820}; + const uint32_t OtherOps[] = {0xc8dffc20, 0xc89ffc20, 0xc8e0fc41, 0x4860fc82, 0x08207c82, 0xf8e00041, + 0xf8e08041, 0xf9400020, 0xf9000420, 0xa9000440, 0xf8bfc020}; + uint64_t Refused = 0; + for (auto Op : ExclusiveOps) { + Refused += IsExclusive(Op); + } + uint64_t Allowed = 0; + for (auto Op : OtherOps) { + Allowed += !IsExclusive(Op); + } + Show("exclusive_refused", Refused); + Show("others_allowed", Allowed); + + std::vector> Applied; + auto Record = [&](void* Host, uint64_t Size, uint32_t) { + Applied.emplace_back(reinterpret_cast(Host), Size); + return 0; + }; + Show("split_apply_result", ApplyToRegionsLocked(Split, 2 * Page, -EINVAL, Record)); + Show("split_apply_count", Applied.size()); + Show("split_apply_first", Applied[0].first - Base); + Show("split_apply_second", Applied[1].first - Base); + Show("split_apply_sizes", Applied[0].second + Applied[1].second); + Applied.clear(); + Show("gap_apply_result", ApplyToRegionsLocked(Single, 2 * Page, -EINVAL, Record)); + Show("gap_apply_count", Applied.size()); + bool Advised = false; + Show("advise_split", Advise(Split, 2 * Page, MADV_DONTNEED, &Advised)); + Show("advise_split_applied", Advised); + Show("advise_gap", Advise(Single, 2 * Page, MADV_DONTNEED, &Advised)); + Show("advise_gap_applied", Advised); + Show("advise_unaligned", Advise(Single + 8, Page, MADV_DONTNEED, &Advised)); + Show("advise_unaligned_applied", Advised); + Show("advise_zero", Advise(Single, 0, MADV_DONTNEED, &Advised)); + Show("advise_wrap", Advise(Single, UINT64_MAX - 16, MADV_DONTNEED, &Advised)); + Show("advise_wrap_applied", Advised); + Show("protect_split", Protect(Split, 2 * Page, PROT_READ | PROT_WRITE)); + Show("protect_zero", Protect(Single, 0, PROT_READ | PROT_WRITE)); + Show("protect_wrap", Protect(Single, UINT64_MAX - 16, PROT_READ | PROT_WRITE)); + + auto* Guarded = static_cast(mmap(nullptr, 3 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Guard = 0x7b0000000000ULL; + RegionView Part {}; + AddEntry(Guard, 3 * Page, reinterpret_cast(Guarded), false, PROT_READ | PROT_WRITE); + Show("guard_protect", Protect(Guard + Page, Page, PROT_READ)); + FindLocked(Guard, &Part); + Show("guard_low_size", Part.Size); + Show("guard_low_prot", Part.Prot); + FindLocked(Guard + Page, &Part); + Show("guard_mid_size", Part.Size); + Show("guard_mid_host", Part.Host - reinterpret_cast(Guarded)); + Show("guard_mid_prot", Part.Prot); + FindLocked(Guard + 2 * Page, &Part); + Show("guard_high_size", Part.Size); + Show("guard_high_prot", Part.Prot); + Show("guard_store_readonly", ExclusiveReachable(0xc8027c20, PROT_READ)); + Show("guard_load_readonly", ExclusiveReachable(0xc85f7c20, PROT_READ)); + Show("guard_store_writable", ExclusiveReachable(0xc8027c20, PROT_READ | PROT_WRITE)); + Show("guard_load_none", ExclusiveReachable(0xc85f7c20, PROT_NONE)); + Show("guard_pair_store_readonly", ExclusiveReachable(0xc8220c20, PROT_READ)); + Show("discards", DiscardsContents(MADV_DONTNEED) + DiscardsContents(MADV_FREE) + DiscardsContents(MADV_REMOVE) + + DiscardsContents(MADV_DONTNEED_LOCKED)); + Show("keeps", DiscardsContents(MADV_WILLNEED) + DiscardsContents(MADV_NORMAL) + DiscardsContents(MADV_HUGEPAGE)); + + auto* Spare = static_cast(mmap(nullptr, 2 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Retire = 0x7c0000000000ULL; + unsigned char Resident = 0; + RegionView View {}; + AddEntry(Retire, 2 * Page, reinterpret_cast(Spare), false, PROT_READ | PROT_WRITE); + MunmapFailures = 1; + Show("retire_unmap", UnmapLocked(Retire, Page)); + Show("retire_pending", RetiredCount); + Show("retire_untracked", !FindLocked(Retire, &View)); + Show("retire_host_held", mincore(Spare, Page, &Resident) == 0); + Show("retire_second", UnmapLocked(Retire + Page, Page)); + Show("retire_released", RetiredCount); + Show("retire_host_gone", mincore(Spare, Page, &Resident) != 0 && errno == ENOMEM); + Show("retire_rest_gone", mincore(Spare + Page, Page, &Resident) != 0 && errno == ENOMEM); + + auto* Kept = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Full = 0x7a0000000000ULL; + AddEntry(Full, Page, reinterpret_cast(Kept), false, PROT_READ | PROT_WRITE); + for (uint32_t i = 0; i < MaxRegions; ++i) { + Retired[i] = {0x10000000ULL + i * 2 * Page, Page}; + } + RetiredCount = MaxRegions; + MunmapFailures = MaxRegions + 1; + Show("retire_full_unmap", UnmapLocked(Full, Page)); + Show("retire_full_tracked", FindLocked(Full, &View)); + Show("retire_full_host_held", mincore(Kept, Page, &Resident) == 0); + RetiredCount = 0; + MunmapFailures = 0; + Show("retire_full_after", UnmapLocked(Full, Page)); + Show("retire_full_gone", !FindLocked(Full, &View)); + + struct { + uint64_t Host; + uint64_t Low; + uint64_t High; + uint32_t Size; + bool Valid; + } Monitor {}; + uint64_t Context[32] {}; + alignas(16) uint64_t Cell[2] = {5, 0}; + const auto CellHost = reinterpret_cast(Cell); + EmulateExclusive(Monitor, 0xc85f7c20, CellHost, Context); + Show("ldxr_value", Context[0]); + Context[0] = 9; + EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context); + Show("stxr_status", Context[2]); + Show("stxr_memory", Cell[0]); + EmulateExclusive(Monitor, 0xc85f7c20, CellHost, Context); + Cell[0] = 11; + Context[0] = 12; + EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context); + Show("contended_status", Context[2]); + Show("contended_memory", Cell[0]); + Context[0] = 13; + EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context); + Show("unarmed_status", Context[2]); + Show("unarmed_memory", Cell[0]); + Cell[0] = 1; + Cell[1] = 2; + EmulateExclusive(Monitor, 0xc87f0c20, CellHost, Context); + Show("ldxp_low", Context[0]); + Show("ldxp_high", Context[3]); + Context[0] = 7; + Context[3] = 8; + EmulateExclusive(Monitor, 0xc8220c20, CellHost, Context); + Show("stxp_status", Context[2]); + Show("stxp_memory", Cell[0] * 16 + Cell[1]); + Cell[0] = 0x1122334455667788ULL; + EmulateExclusive(Monitor, 0x085f7c20, CellHost, Context); + Show("ldxrb_value", Context[0]); + Context[0] = 0x1ab; + EmulateExclusive(Monitor, 0x0802fc20, CellHost, Context); + Show("stlxrb_status", Context[2]); + Show("stlxrb_memory", Cell[0]); + Show("misaligned", EmulateExclusive(Monitor, 0xc85f7c20, CellHost + 4, Context)); + + Show("writeonly_load", ExclusiveReachable(0xc85f7c20, PROT_WRITE)); + Show("writeonly_store", ExclusiveReachable(0xc8027c20, PROT_WRITE)); + Show("writeonly_pair_store", ExclusiveReachable(0xc8220c20, PROT_WRITE)); + Show("exec_only_load", ExclusiveReachable(0xc85f7c20, PROT_EXEC)); + + const uint32_t GuardEntries = Count.load(); + Show("guard_restore", Protect(Guard + Page, Page, PROT_READ | PROT_WRITE)); + FindLocked(Guard + Page, &Part); + Show("guard_restored_guest", Part.Guest - Guard); + Show("guard_restored_size", Part.Size); + Show("guard_restored_merged", GuardEntries - Count.load()); + Show("split_hosts_kept_apart", FindLocked(Split + Page, &Part) && Part.Guest == Split + Page && Part.Size == Page); + + const uint64_t Toggles = 1100; + auto* Striped = static_cast(mmap(nullptr, Toggles * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Stripe = 0x790000000000ULL; + AddEntry(Stripe, Toggles * Page, reinterpret_cast(Striped), false, PROT_READ | PROT_WRITE); + const uint32_t StripeEntries = Count.load(); + uint64_t ToggleFailures = 0; + for (uint64_t i = 0; i < Toggles; ++i) { + ToggleFailures += Protect(Stripe + i * Page, Page, PROT_READ) != 0; + ToggleFailures += Protect(Stripe + i * Page, Page, PROT_READ | PROT_WRITE) != 0; + } + Show("toggle_failures", ToggleFailures); + Show("toggle_entries", Count.load() - StripeEntries); + FindLocked(Stripe, &Part); + Show("toggle_pages", Part.Size / Page); + + uint64_t SemApart[6] = {1, Split + Page - 12, 3, 0, 0, 0}; + Show("semop_split_result", Call(Sys::SYSCALL_x64_semop, SemApart, &Storage)); + uint64_t SemFits[6] = {1, Split + Page - 12, 2, 0, 0, 0}; + Show("semop_fits_result", Call(Sys::SYSCALL_x64_semop, SemFits, &Storage)); + uint64_t GroupsApart[6] = {4, Split + Page - 12, 0, 0, 0, 0}; + Show("getgroups_split_result", Call(Sys::SYSCALL_x64_getgroups, GroupsApart, &Storage)); + uint64_t EventsApart[6] = {1, 1, 2, Split + Page - 32, 0, 0}; + Show("io_getevents_split_result", Call(Sys::SYSCALL_x64_io_getevents, EventsApart, &Storage)); + uint64_t EventsFit[6] = {1, 1, 1, Split + Page - 32, 0, 0}; + Show("io_getevents_fits_result", Call(Sys::SYSCALL_x64_io_getevents, EventsFit, &Storage)); + uint64_t PagesApart[6] = {0, 2, Split + Page - 8, 0, 0, 0}; + Show("move_pages_split_result", Call(Sys::SYSCALL_x64_move_pages, PagesApart, &Storage)); + + char BatchLow[16]; + struct iovec SendVectors[2] = {{reinterpret_cast(Single + 256), 32}, {BatchLow, sizeof(BatchLow)}}; + struct mmsghdr Outgoing[2] {}; + Outgoing[0].msg_hdr.msg_iov = &SendVectors[0]; + Outgoing[0].msg_hdr.msg_iovlen = 1; + Outgoing[1].msg_hdr.msg_iov = &SendVectors[1]; + Outgoing[1].msg_hdr.msg_iovlen = 1; + ArgumentStorage SendBatch; + uint64_t Send[6] = {static_cast(Peer), reinterpret_cast(Outgoing), 2, 0, 0, 0}; + Show("sendmmsg_result", Call(Sys::SYSCALL_x64_sendmmsg, Send, &SendBatch)); + auto* HostSend = reinterpret_cast(Send[1]); + Show("sendmmsg_copied", HostSend != Outgoing); + Show("sendmmsg_high_base", reinterpret_cast(HostSend[0].msg_hdr.msg_iov[0].iov_base) - Base); + Show("sendmmsg_low_base", HostSend[1].msg_hdr.msg_iov[0].iov_base == BatchLow); + Show("sendmmsg_guest_untouched", reinterpret_cast(Outgoing[0].msg_hdr.msg_iov[0].iov_base) - Single); + Show("sendmmsg_submitted", Send[2]); + SendCalls = 0; + HostSend[0].msg_len = 32; + Show("sendmmsg_finish", FinishResult(1, &SendBatch)); + Show("sendmmsg_later_sends", SendCalls); + Show("sendmmsg_lengths", Outgoing[0].msg_len * 0x100 + Outgoing[1].msg_len); + Outgoing[0].msg_len = 0; + Outgoing[1].msg_len = 0; + ArgumentStorage DeclinedBatch; + uint64_t Declined[6] = {static_cast(Peer), reinterpret_cast(Outgoing), 2, 0, 0, 0}; + Call(Sys::SYSCALL_x64_sendmmsg, Declined, &DeclinedBatch); + reinterpret_cast(Declined[1])[0].msg_len = 32; + SendFailures = 1; + Show("sendmmsg_refused_finish", FinishResult(1, &DeclinedBatch)); + Show("sendmmsg_refused_lengths", Outgoing[0].msg_len * 0x100 + Outgoing[1].msg_len); + + struct iovec ReceiveVectors[2] = {{reinterpret_cast(Single + 512), 64}, {BatchLow, sizeof(BatchLow)}}; + struct mmsghdr Arriving[2] {}; + Arriving[0].msg_hdr.msg_iov = &ReceiveVectors[0]; + Arriving[0].msg_hdr.msg_iovlen = 1; + Arriving[1].msg_hdr.msg_iov = &ReceiveVectors[1]; + Arriving[1].msg_hdr.msg_iovlen = 1; + ArgumentStorage ReceiveBatch; + uint64_t Batch[6] = {3, reinterpret_cast(Arriving), 2, 0, 0, 0}; + Show("recvmmsg_result", Call(Sys::SYSCALL_x64_recvmmsg, Batch, &ReceiveBatch)); + auto* HostReceive = reinterpret_cast(Batch[1]); + Show("recvmmsg_copied", HostReceive != Arriving); + Show("recvmmsg_base", reinterpret_cast(HostReceive[0].msg_hdr.msg_iov[0].iov_base) - Base); + HostReceive[0].msg_len = 40; + HostReceive[0].msg_hdr.msg_flags = MSG_TRUNC; + HostReceive[1].msg_len = 5; + FinishSyscallArguments(1, &ReceiveBatch); + Show("recvmmsg_first_length", Arriving[0].msg_len); + Show("recvmmsg_first_flags", Arriving[0].msg_hdr.msg_flags); + Show("recvmmsg_second_length", Arriving[1].msg_len); + Show("recvmmsg_guest_iov", Arriving[0].msg_hdr.msg_iov == &ReceiveVectors[0]); + + std::vector Many(1100); + Many[0].msg_hdr.msg_iov = &ReceiveVectors[0]; + Many[0].msg_hdr.msg_iovlen = 1; + ArgumentStorage ManyBatch; + uint64_t Wide[6] = {3, reinterpret_cast(Many.data()), Many.size(), 0, 0, 0}; + Show("recvmmsg_wide_result", Call(Sys::SYSCALL_x64_recvmmsg, Wide, &ManyBatch)); + Show("recvmmsg_wide_count", Wide[2]); + uint64_t BatchApart[6] = {3, Split + Page - 64, 2, 0, 0, 0}; + Show("sendmmsg_split_result", Call(Sys::SYSCALL_x64_sendmmsg, BatchApart, &ManyBatch)); + + ArgumentStorage Sizes; + uint64_t StatSplit[6] = {3, Split + Page - 64, 0, 0, 0, 0}; + Show("fstat_split_result", Call(Sys::SYSCALL_x64_fstat, StatSplit, &Sizes)); + uint64_t StatEdge[6] = {3, Single + Page - 144, 0, 0, 0, 0}; + Show("fstat_edge_result", Call(Sys::SYSCALL_x64_fstat, StatEdge, &Sizes)); + uint64_t NameEdge[6] = {Single + Page - 390, 0, 0, 0, 0, 0}; + Show("uname_edge_result", Call(Sys::SYSCALL_x64_uname, NameEdge, &Sizes)); + uint64_t NameOver[6] = {Single + Page - 389, 0, 0, 0, 0, 0}; + Show("uname_over_result", Call(Sys::SYSCALL_x64_uname, NameOver, &Sizes)); + uint64_t Action[6] = {10, Single + Page - 32, 0, 8, 0, 0}; + Show("sigaction_edge_result", Call(Sys::SYSCALL_x64_rt_sigaction, Action, &Sizes)); + uint64_t ActionOver[6] = {10, Single + Page - 24, 0, 8, 0, 0}; + Show("sigaction_over_result", Call(Sys::SYSCALL_x64_rt_sigaction, ActionOver, &Sizes)); + uint64_t MaskApart[6] = {0, Split + Page - 4, 0, 8, 0, 0}; + Show("sigprocmask_split_result", Call(Sys::SYSCALL_x64_rt_sigprocmask, MaskApart, &Sizes)); + uint64_t MaskFits[6] = {0, Split + Page - 8, 0, 8, 0, 0}; + Show("sigprocmask_fits_result", Call(Sys::SYSCALL_x64_rt_sigprocmask, MaskFits, &Sizes)); + uint64_t Sleep[6] = {Single + Page - 16, 0, 0, 0, 0, 0}; + Show("nanosleep_edge_result", Call(Sys::SYSCALL_x64_nanosleep, Sleep, &Sizes)); + uint64_t SleepOver[6] = {Single + Page - 8, 0, 0, 0, 0, 0}; + Show("nanosleep_over_result", Call(Sys::SYSCALL_x64_nanosleep, SleepOver, &Sizes)); + uint64_t Residency[6] = {Low, 3 * Page, Split + Page - 2, 0, 0, 0}; + Show("mincore_split_result", Call(Sys::SYSCALL_x64_mincore, Residency, &Sizes)); + uint64_t ResidencyFits[6] = {Low, 2 * Page, Split + Page - 2, 0, 0, 0}; + Show("mincore_fits_result", Call(Sys::SYSCALL_x64_mincore, ResidencyFits, &Sizes)); + uint64_t Lock[6] = {3, F_GETLK, Split + Page - 16, 0, 0, 0}; + Show("fcntl_lock_split_result", Call(Sys::SYSCALL_x64_fcntl, Lock, &Sizes)); + uint64_t LockFits[6] = {3, F_GETLK, Single + Page - 32, 0, 0, 0}; + Show("fcntl_lock_fits_result", Call(Sys::SYSCALL_x64_fcntl, LockFits, &Sizes)); + Show("fcntl_lock_fits_buffer", LockFits[2] - Base); + + std::memcpy(Backing + 3 * Page - 2, "ab", 2); + std::memcpy(Backing + 4 * Page, "cd", 3); + uint64_t PathApart[6] = {Split + Page - 2, 0, 0, 0, 0, 0}; + Show("open_split_result", Call(Sys::SYSCALL_x64_open, PathApart, &Sizes)); + std::memcpy(Backing + 6 * Page - 2, "ab", 2); + std::memcpy(Backing + 6 * Page, "cd", 3); + uint64_t PathJoined[6] = {Joined + Page - 2, 0, 0, 0, 0, 0}; + Show("open_joined_result", Call(Sys::SYSCALL_x64_open, PathJoined, &Sizes)); + Show("open_joined_path", PathJoined[0] - Base); + std::memcpy(Backing + 3000, "dir/file", 9); + uint64_t PathInside[6] = {static_cast(AT_FDCWD), Single + 3000, 0, 0, 0, 0}; + Show("openat_inside_result", Call(Sys::SYSCALL_x64_openat, PathInside, &Sizes)); + Show("openat_inside_path", PathInside[1] - Base); + std::memset(Backing + Page - 8, 'x', 8); + uint64_t PathOpen[6] = {Single + Page - 8, 0, 0, 0, 0, 0}; + Show("open_unterminated_result", Call(Sys::SYSCALL_x64_open, PathOpen, &Sizes)); + uint64_t RenameApart[6] = {Single + 3000, Split + Page - 2, 0, 0, 0, 0}; + Show("rename_split_result", Call(Sys::SYSCALL_x64_rename, RenameApart, &Sizes)); + + socklen_t AddressLength = 16; + uint64_t Accept[6] = {3, Split + Page - 16, reinterpret_cast(&AddressLength), 0, 0, 0}; + Show("accept_fits_result", Call(Sys::SYSCALL_x64_accept, Accept, &Sizes)); + AddressLength = 32; + uint64_t AcceptOver[6] = {3, Split + Page - 16, reinterpret_cast(&AddressLength), 0, 0, 0}; + Show("accept_split_result", Call(Sys::SYSCALL_x64_accept, AcceptOver, &Sizes)); + AddressLength = 4096; + uint64_t AcceptCapped[6] = {3, Single + Page - 128, reinterpret_cast(&AddressLength), 0, 0, 0}; + Show("accept_capped_result", Call(Sys::SYSCALL_x64_accept, AcceptCapped, &Sizes)); + const uint32_t HighLength = 32; + std::memcpy(Backing + 40, &HighLength, sizeof(HighLength)); + uint64_t AcceptHigh[6] = {3, Split + Page - 16, Single + 40, 0, 0, 0}; + Show("accept_high_length_result", Call(Sys::SYSCALL_x64_accept, AcceptHigh, &Sizes)); + uint32_t OptionLength = 8; + uint64_t Option[6] = {3, 1, 2, Split + Page - 4, reinterpret_cast(&OptionLength), 0}; + Show("getsockopt_split_result", Call(Sys::SYSCALL_x64_getsockopt, Option, &Sizes)); + OptionLength = 4; + uint64_t OptionFits[6] = {3, 1, 2, Split + Page - 4, reinterpret_cast(&OptionLength), 0}; + Show("getsockopt_fits_result", Call(Sys::SYSCALL_x64_getsockopt, OptionFits, &Sizes)); + + uint64_t QueueFits[6] = {1, Split + Page - 16, 8, 0, 0, 0}; + Show("msgsnd_fits_result", Call(Sys::SYSCALL_x64_msgsnd, QueueFits, &Sizes)); + uint64_t QueueOver[6] = {1, Split + Page - 16, 9, 0, 0, 0}; + Show("msgsnd_split_result", Call(Sys::SYSCALL_x64_msgsnd, QueueOver, &Sizes)); + uint64_t QueueReceive[6] = {1, Split + Page - 16, 9, 0, 0, 0}; + Show("msgrcv_split_result", Call(Sys::SYSCALL_x64_msgrcv, QueueReceive, &Sizes)); + uint64_t QueueHuge[6] = {1, Single, 1ULL << 40, 0, 0, 0}; + Show("msgsnd_huge_result", Call(Sys::SYSCALL_x64_msgsnd, QueueHuge, &Sizes)); + + std::memcpy(Backing + 100, "x", 2); + uint64_t ValidFailures = 0; + uint64_t ValidTranslated = 0; + uint64_t StatValid[6] = {Single + 100, Single + 1024, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_stat, StatValid, &Sizes) != 0; + ValidTranslated += StatValid[0] == Base + 100 && StatValid[1] == Base + 1024; + uint64_t StatxValid[6] = {static_cast(AT_FDCWD), Single + 100, 0, 0x7ff, Single + 1536, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_statx, StatxValid, &Sizes) != 0; + ValidTranslated += StatxValid[1] == Base + 100 && StatxValid[4] == Base + 1536; + uint64_t ClockValid[6] = {1, Single + 2048, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_clock_gettime, ClockValid, &Sizes) != 0; + ValidTranslated += ClockValid[1] == Base + 2048; + uint64_t WaitValid[6] = {static_cast(-1), Single + 64, 0, Single + 512, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_wait4, WaitValid, &Sizes) != 0; + ValidTranslated += WaitValid[1] == Base + 64 && WaitValid[3] == Base + 512; + uint64_t PipeValid[6] = {Single + 8, 0, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_pipe2, PipeValid, &Sizes) != 0; + ValidTranslated += PipeValid[0] == Base + 8; + uint64_t LimitValid[6] = {0, 7, Single + 2560, Single + 2600, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_prlimit_64, LimitValid, &Sizes) != 0; + ValidTranslated += LimitValid[2] == Base + 2560 && LimitValid[3] == Base + 2600; + uint64_t TimerValid[6] = {1, 0, Single + 2304, Single + 2336, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_timer_settime, TimerValid, &Sizes) != 0; + ValidTranslated += TimerValid[2] == Base + 2304 && TimerValid[3] == Base + 2336; + AddressLength = 16; + uint64_t AcceptValid[6] = {3, Single + 256, reinterpret_cast(&AddressLength), 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_accept, AcceptValid, &Sizes) != 0; + ValidTranslated += AcceptValid[1] == Base + 256; + uint64_t NameValid[6] = {Single, 0, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_uname, NameValid, &Sizes) != 0; + ValidTranslated += NameValid[0] == Base; + uint64_t SignalValid[6] = {10, Single + 2800, Single + 2900, 8, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_rt_sigaction, SignalValid, &Sizes) != 0; + ValidTranslated += SignalValid[1] == Base + 2800 && SignalValid[2] == Base + 2900; + Show("single_valid_failures", ValidFailures); + Show("single_valid_translated", ValidTranslated); + + struct TestIocb { + uint64_t Data; + uint32_t Key; + int32_t ReadWriteFlags; + uint16_t Opcode; + int16_t Priority; + uint32_t File; + uint64_t Buffer; + uint64_t Bytes; + int64_t Offset; + uint64_t Reserved; + uint32_t Flags; + uint32_t ResultFile; + }; + TestIocb ReadBlock {}; + ReadBlock.Data = 0x77; + ReadBlock.Key = 5; + ReadBlock.Buffer = Single + 768; + ReadBlock.Bytes = 64; + char VectorLow[16]; + struct iovec Scatter[2] = {{reinterpret_cast(Single + 800), 16}, {VectorLow, sizeof(VectorLow)}}; + TestIocb Vectored {}; + Vectored.Opcode = 7; + Vectored.Buffer = reinterpret_cast(Scatter); + Vectored.Bytes = 2; + TestIocb ReadExpected = ReadBlock; + const TestIocb VectoredExpected = Vectored; + auto GuestBlocksUntouched = [&] { + return std::memcmp(&ReadBlock, &ReadExpected, sizeof(TestIocb)) == 0 && std::memcmp(&Vectored, &VectoredExpected, sizeof(TestIocb)) == 0; + }; + struct TestEvent { + uint64_t Data; + uint64_t Object; + int64_t Result; + int64_t Result2; + }; + auto Deliver = [](const uint64_t* Args, const void* Events, size_t Size) { + static_cast(FEX::HLE::FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Args[3]), Events, Size)); + }; + uint64_t Submitted[2] = {reinterpret_cast(&ReadBlock), reinterpret_cast(&Vectored)}; + ArgumentStorage Submit; + uint64_t SubmitArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + const auto CopiesBefore = IoCopyCount.load(); + ProtectCalls = 0; + Show("io_submit_result", Call(Sys::SYSCALL_x64_io_submit, SubmitArgs, &Submit)); + Show("io_submit_count", SubmitArgs[1]); + Show("io_submit_list_copied", SubmitArgs[2] != reinterpret_cast(Submitted)); + const auto* Sent = reinterpret_cast(SubmitArgs[2]); + const auto* SentRead = reinterpret_cast(Sent[0]); + const auto* SentVector = reinterpret_cast(Sent[1]); + Show("io_submit_private_blocks", SentRead != &ReadBlock && SentVector != &Vectored); + Show("io_submit_buffer", SentRead->Buffer - Base); + Show("io_submit_fields_kept", SentRead->Data == 0x77 && SentRead->Bytes == 64 && SentRead->Key == 5); + const auto* HostScatter = reinterpret_cast(SentVector->Buffer); + Show("io_submit_vector_copied", HostScatter != Scatter); + Show("io_submit_vector_base", reinterpret_cast(HostScatter[0].iov_base) - Base); + Show("io_submit_vector_low", HostScatter[1].iov_base == VectorLow); + Show("io_submit_guest_key", ReadBlock.Key); + Show("io_submit_guest_untouched", GuestBlocksUntouched()); + Show("io_submit_copies", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(2, &Submit); + Show("io_submit_accepted_key", ReadBlock.Key); + ReadExpected.Key = 0; + Show("io_submit_copies_kept", IoCopyCount.load() - CopiesBefore); + Show("io_submit_finished_untouched", GuestBlocksUntouched()); + + TestEvent CancelEvent {}; + ArgumentStorage Cancel; + uint64_t CancelArgs[6] = {1, reinterpret_cast(&ReadBlock), reinterpret_cast(&CancelEvent), 0, 0, 0}; + Show("io_cancel_result", Call(Sys::SYSCALL_x64_io_cancel, CancelArgs, &Cancel)); + Show("io_cancel_private", CancelArgs[1] == Sent[0]); + ArgumentStorage CancelElsewhere; + uint64_t ElsewhereArgs[6] = {2, reinterpret_cast(&ReadBlock), reinterpret_cast(&CancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, ElsewhereArgs, &CancelElsewhere); + Show("io_cancel_other_context", ElsewhereArgs[1] == reinterpret_cast(&ReadBlock)); + + TestEvent Reaped[3] = {{0x77, Sent[0], 64, 0}, {0, Sent[1], 16, 0}, {8, Base + 1536, 16, 0}}; + ArgumentStorage ReapCopies; + uint64_t ReapCopiesArgs[6] = {1, 1, 3, reinterpret_cast(Reaped), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ReapCopiesArgs, &ReapCopies); + Show("io_getevents_host_buffer", ReapCopiesArgs[3] == reinterpret_cast(ReapCopies.EventBuffer.data())); + Deliver(ReapCopiesArgs, Reaped, sizeof(Reaped)); + FinishSyscallArguments(3, &ReapCopies); + Show("io_getevents_copy_object", Reaped[0].Object == reinterpret_cast(&ReadBlock)); + Show("io_getevents_vector_object", Reaped[1].Object == reinterpret_cast(&Vectored)); + Show("io_getevents_alias_object", Reaped[2].Object - Single); + Show("io_getevents_copies_freed", IoCopyCount.load() - CopiesBefore); + Show("io_getevents_untouched", GuestBlocksUntouched()); + Show("io_submit_protect_calls", ProtectCalls); + + auto* HighBlock = reinterpret_cast(Backing + 1536); + *HighBlock = {}; + HighBlock->Opcode = 1; + HighBlock->Buffer = reinterpret_cast(LowBuffer); + HighBlock->Bytes = sizeof(LowBuffer); + uint64_t HighList[1] = {Single + 1536}; + ArgumentStorage HighSubmit; + uint64_t HighArgs[6] = {1, 1, reinterpret_cast(HighList), 0, 0, 0}; + Show("io_submit_high_result", Call(Sys::SYSCALL_x64_io_submit, HighArgs, &HighSubmit)); + Show("io_submit_high_copied", HighArgs[2] != reinterpret_cast(HighList)); + Show("io_submit_high_block", reinterpret_cast(HighArgs[2])[0] - Base); + Show("io_submit_high_guest_list", HighList[0] - Single); + Show("io_submit_high_uncopied", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(1, &HighSubmit); + + TestIocb BadBlock {}; + BadBlock.Buffer = Split + Page - 8; + BadBlock.Bytes = 16; + uint64_t Mixed[2] = {reinterpret_cast(&ReadBlock), reinterpret_cast(&BadBlock)}; + ArgumentStorage Partial; + uint64_t PartialArgs[6] = {1, 2, reinterpret_cast(Mixed), 0, 0, 0}; + Show("io_submit_partial_result", Call(Sys::SYSCALL_x64_io_submit, PartialArgs, &Partial)); + Show("io_submit_partial_count", PartialArgs[1]); + Show("io_submit_partial_copies", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(static_cast(-EFAULT), &Partial); + Show("io_submit_partial_released", IoCopyCount.load() - CopiesBefore); + Show("io_submit_partial_untouched", GuestBlocksUntouched()); + ArgumentStorage Truncated; + uint64_t TruncatedArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, TruncatedArgs, &Truncated); + const uint64_t TruncatedFirst = reinterpret_cast(TruncatedArgs[2])[0]; + FinishSyscallArguments(1, &Truncated); + Show("io_submit_short_kept", IoCopyCount.load() - CopiesBefore); + Show("io_submit_short_first_live", FindIoCopyLocked(TruncatedFirst) != nullptr); + ArgumentStorage OtherContext; + uint64_t OtherContextArgs[6] = {3, 1, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, OtherContextArgs, &OtherContext); + FinishSyscallArguments(1, &OtherContext); + ArgumentStorage Destroy; + uint64_t DestroyArgs[6] = {1, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DestroyArgs, &Destroy); + FinishSyscallArguments(0, &Destroy); + Show("io_destroy_released", IoCopyCount.load() - CopiesBefore); + ArgumentStorage DestroyFailed; + uint64_t DestroyFailedArgs[6] = {3, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DestroyFailedArgs, &DestroyFailed); + FinishSyscallArguments(static_cast(-EINVAL), &DestroyFailed); + Show("io_destroy_failed_kept", IoCopyCount.load() - CopiesBefore); + ArgumentStorage DestroyOther; + uint64_t DestroyOtherArgs[6] = {3, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DestroyOtherArgs, &DestroyOther); + FinishSyscallArguments(0, &DestroyOther); + Show("io_destroy_other_released", IoCopyCount.load() - CopiesBefore); + uint64_t OnlyCrossing[1] = {reinterpret_cast(&BadBlock)}; + ArgumentStorage FirstBad; + uint64_t FirstBadArgs[6] = {1, 1, reinterpret_cast(OnlyCrossing), 0, 0, 0}; + Show("io_submit_first_bad_result", Call(Sys::SYSCALL_x64_io_submit, FirstBadArgs, &FirstBad)); + FinishSyscallArguments(static_cast(-EFAULT), &FirstBad); + Show("io_submit_first_bad_copies", IoCopyCount.load() - CopiesBefore); + TestIocb KeyFirst = ReadBlock; + KeyFirst.Key = 5; + TestIocb KeySecond = ReadBlock; + KeySecond.Key = 6; + uint64_t KeyList[2] = {reinterpret_cast(&KeyFirst), reinterpret_cast(&KeySecond)}; + ArgumentStorage KeySubmit; + uint64_t KeySubmitArgs[6] = {4, 2, reinterpret_cast(KeyList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, KeySubmitArgs, &KeySubmit); + const uint64_t KeyFirstSent = reinterpret_cast(KeySubmitArgs[2])[0]; + Show("io_submit_keys_prepared", KeyFirst.Key == 5 && KeySecond.Key == 6); + TestEvent KeyCancelEvent {}; + ArgumentStorage EarlyCancel; + uint64_t EarlyCancelArgs[6] = {4, reinterpret_cast(&KeyFirst), reinterpret_cast(&KeyCancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, EarlyCancelArgs, &EarlyCancel); + Show("io_cancel_keyed_native", EarlyCancelArgs[1] == reinterpret_cast(&KeyFirst)); + FinishSyscallArguments(1, &KeySubmit); + Show("io_submit_key_accepted", KeyFirst.Key); + Show("io_submit_key_after_rejected", KeySecond.Key); + Show("io_submit_key_rejected_released", IoCopyCount.load() - CopiesBefore); + ArgumentStorage LateCancel; + uint64_t LateCancelArgs[6] = {4, reinterpret_cast(&KeyFirst), reinterpret_cast(&KeyCancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, LateCancelArgs, &LateCancel); + Show("io_cancel_accepted_private", LateCancelArgs[1] == KeyFirstSent); + TestIocb KeyA = ReadBlock; + KeyA.Key = 7; + TestIocb KeyB = ReadBlock; + KeyB.Key = 8; + TestIocb KeyC = ReadBlock; + KeyC.Key = 9; + uint64_t KeyTriple[3] = {reinterpret_cast(&KeyA), reinterpret_cast(&KeyB), reinterpret_cast(&KeyC)}; + ArgumentStorage RejectSubmit; + uint64_t RejectSubmitArgs[6] = {6, 3, reinterpret_cast(KeyTriple), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, RejectSubmitArgs, &RejectSubmit); + const auto* RejectSent = reinterpret_cast(RejectSubmitArgs[2]); + reinterpret_cast(RejectSent[0])->Key = 0; + reinterpret_cast(RejectSent[1])->Key = 0; + FinishSyscallArguments(1, &RejectSubmit); + Show("io_submit_rejected_key_cleared", KeyA.Key == 0 && KeyB.Key == 0); + Show("io_submit_unreached_key", KeyC.Key); + TestIocb KeyD = ReadBlock; + KeyD.Key = 3; + uint64_t KeySingle[1] = {reinterpret_cast(&KeyD)}; + ArgumentStorage FirstRejected; + uint64_t FirstRejectedArgs[6] = {6, 1, reinterpret_cast(KeySingle), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, FirstRejectedArgs, &FirstRejected); + reinterpret_cast(reinterpret_cast(FirstRejectedArgs[2])[0])->Key = 0; + FinishSyscallArguments(static_cast(-EBADF), &FirstRejected); + Show("io_submit_first_rejected_key", KeyD.Key); + ArgumentStorage RejectDestroy; + uint64_t RejectDestroyArgs[6] = {6, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, RejectDestroyArgs, &RejectDestroy); + FinishSyscallArguments(0, &RejectDestroy); + Show("io_submit_rejected_released", IoCopyCount.load() - CopiesBefore); + auto* SealedEvents = static_cast(mmap(nullptr, Page, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + int64_t NoWait[2] = {0, 0}; + const uint64_t Immediate = reinterpret_cast(NoWait); + ArgumentStorage UnwritableReap; + uint64_t UnwritableReapArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, UnwritableReapArgs, &UnwritableReap); + Show("io_getevents_unwritable_staged", UnwritableReapArgs[3] == reinterpret_cast(UnwritableReap.EventBuffer.data()) && + UnwritableReapArgs[2] == 1 && UnwritableReap.EventBuffer.size() == sizeof(TestEvent) / sizeof(uint64_t)); + Show("io_getevents_unwritable_result", FinishSyscallArguments(static_cast(-EFAULT), &UnwritableReap)); + Show("io_getevents_unwritable_kept", IoCopyCount.load() - CopiesBefore); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage SealedReap; + uint64_t SealedReapArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SealedReapArgs, &SealedReap); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent SealedEvent {0x77, KeyFirstSent, 64, 0}; + Deliver(SealedReapArgs, &SealedEvent, sizeof(SealedEvent)); + Show("io_getevents_sealed_result", FinishSyscallArguments(1, &SealedReap)); + Show("io_getevents_sealed_released", IoCopyCount.load() - CopiesBefore); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage StashedReap; + uint64_t StashedReapArgs[6] = {4, 1, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, StashedReapArgs, &StashedReap); + Show("io_getevents_stash_nonblocking", StashedReapArgs[1] == 0 && StashedReapArgs[2] == 1 && + StashedReapArgs[3] == reinterpret_cast(StashedReap.EventBuffer.data() + sizeof(TestEvent) / sizeof(uint64_t))); + Show("io_getevents_stash_result", FinishSyscallArguments(0, &StashedReap)); + Show("io_getevents_stash_event", SealedEvents[0].Object == reinterpret_cast(&KeyFirst) && SealedEvents[0].Data == 0x77); + ArgumentStorage DrainedReap; + uint64_t DrainedReapArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, DrainedReapArgs, &DrainedReap); + Show("io_getevents_stash_once", DrainedReapArgs[1] == 1 && DrainedReapArgs[2] == 1 && FinishSyscallArguments(0, &DrainedReap) == 0); + auto FailReap = [&](uint64_t Context, const TestEvent& Event) { + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage Failed; + uint64_t FailedArgs[6] = {Context, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, FailedArgs, &Failed); + mprotect(SealedEvents, Page, PROT_READ); + Deliver(FailedArgs, &Event, sizeof(Event)); + const auto Result = FinishSyscallArguments(1, &Failed); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + return Result; + }; + Show("io_getevents_stash_ready_failed", FailReap(4, {0x57, reinterpret_cast(&KeyD), 1, 0})); + ArgumentStorage ReadyReap; + uint64_t ReadyReapArgs[6] = {4, 1, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ReadyReapArgs, &ReadyReap); + const TestEvent Ready {0x58, reinterpret_cast(&KeyC), 1, 0}; + Deliver(ReadyReapArgs, &Ready, sizeof(Ready)); + Show("io_getevents_stash_ready_result", FinishSyscallArguments(1, &ReadyReap)); + Show("io_getevents_stash_ready_order", SealedEvents[0].Data == 0x57 && SealedEvents[1].Data == 0x58 && + SealedEvents[1].Object == reinterpret_cast(&KeyC)); + Show("io_getevents_stash_plain_failed", FailReap(4, {0x55, reinterpret_cast(&KeyD), 1, 0})); + ArgumentStorage TopUp; + uint64_t TopUpArgs[6] = {4, 2, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, TopUpArgs, &TopUp); + Show("io_getevents_stash_topup_args", TopUpArgs[1] == 1 && TopUpArgs[2] == 2 && + TopUpArgs[3] == reinterpret_cast(TopUp.EventBuffer.data() + sizeof(TestEvent) / sizeof(uint64_t))); + const TestEvent Fresh {0x66, reinterpret_cast(&KeyA), 2, 0}; + Deliver(TopUpArgs, &Fresh, sizeof(Fresh)); + Show("io_getevents_stash_topup_result", FinishSyscallArguments(1, &TopUp)); + Show("io_getevents_stash_topup_order", SealedEvents[0].Data == 0x55 && SealedEvents[0].Object == reinterpret_cast(&KeyD) && + SealedEvents[1].Data == 0x66 && SealedEvents[1].Object == reinterpret_cast(&KeyA)); + FailReap(4, {0x44, reinterpret_cast(&KeyB), 1, 0}); + ArgumentStorage FaultedRetry; + uint64_t FaultedRetryArgs[6] = {4, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, FaultedRetryArgs, &FaultedRetry); + Show("io_getevents_stash_fault_result", FinishSyscallArguments(static_cast(-EFAULT), &FaultedRetry)); + ArgumentStorage Interrupted; + uint64_t InterruptedArgs[6] = {4, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, InterruptedArgs, &Interrupted); + Show("io_getevents_stash_kept_after_fault", InterruptedArgs[1] == 1 && InterruptedArgs[2] == 1); + Show("io_getevents_stash_interrupted", FinishSyscallArguments(static_cast(-EINTR), &Interrupted)); + Show("io_getevents_stash_interrupted_event", SealedEvents[0].Data == 0x44 && SealedEvents[0].Object == reinterpret_cast(&KeyB)); + FailReap(4, {0x45, reinterpret_cast(&KeyB), 1, 0}); + ArgumentStorage RejectedMask; + uint64_t RejectedMaskArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_pgetevents, RejectedMaskArgs, &RejectedMask); + Show("io_getevents_stash_einval_result", FinishSyscallArguments(static_cast(-EINVAL), &RejectedMask)); + ArgumentStorage AfterRejected; + uint64_t AfterRejectedArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, AfterRejectedArgs, &AfterRejected); + Show("io_getevents_stash_einval_kept", FinishSyscallArguments(0, &AfterRejected) == 1 && SealedEvents[0].Data == 0x45); + FailReap(12, {0x46, reinterpret_cast(&KeyB), 1, 0}); + ArgumentStorage InFlight; + uint64_t InFlightArgs[6] = {12, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, InFlightArgs, &InFlight); + ArgumentStorage InFlightDestroy; + uint64_t InFlightDestroyArgs[6] = {12, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, InFlightDestroyArgs, &InFlightDestroy); + FinishSyscallArguments(0, &InFlightDestroy); + ArgumentStorage Recreated; + uint64_t RecreatedArgs[6] = {12, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, RecreatedArgs, &Recreated); + FinishSyscallArguments(static_cast(-EINVAL), &InFlight); + Show("io_getevents_stash_recreated_result", FinishSyscallArguments(0, &Recreated)); + ArgumentStorage AfterDestroy; + uint64_t AfterDestroyArgs[6] = {12, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, AfterDestroyArgs, &AfterDestroy); + Show("io_getevents_stash_destroyed_in_flight", AfterDestroyArgs[1] == 1 && AfterDestroyArgs[2] == 1 && FinishSyscallArguments(0, &AfterDestroy) == 0); + std::vector FullStash(65536); + ArgumentStorage Filling; + uint64_t FillingArgs[6] = {31, 1, FullStash.size(), reinterpret_cast(FullStash.data()), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, FillingArgs, &Filling); + ArgumentStorage Contended; + uint64_t ContendedArgs[6] = {31, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ContendedArgs, &Contended); + Show("io_getevents_stash_blocking_kept", FillingArgs[2] == FullStash.size() && ContendedArgs[1] == 1 && ContendedArgs[2] == 1); + FinishSyscallArguments(0, &Contended); + FinishSyscallArguments(0, &Filling); + ArgumentStorage Uncrowded; + uint64_t UncrowdedArgs[6] = {31, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, UncrowdedArgs, &Uncrowded); + Show("io_getevents_stash_reserve_released", UncrowdedArgs[1] == 1 && UncrowdedArgs[2] == 1); + FinishSyscallArguments(0, &Uncrowded); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage Owned; + uint64_t OwnedArgs[6] = {32, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, OwnedArgs, &Owned); + const auto* OwnedBuffer = Owned.EventBuffer.data(); + const bool OwnedReady = Owned.Recovery.size() == 1; + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent OwnedEvent {0x47, reinterpret_cast(&KeyB), 1, 0}; + Deliver(OwnedArgs, &OwnedEvent, sizeof(OwnedEvent)); + const auto OwnedResult = FinishSyscallArguments(1, &Owned); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + const auto& OwnedState = AioContextsLocked()[32]; + Show("io_getevents_recovery_preallocated", OwnedReady && OwnedResult == static_cast(-EFAULT) && Owned.Recovery.empty() && + OwnedState.Batches.size() == 1 && OwnedState.Batches.front().data() == OwnedBuffer); + ArgumentStorage OwnedRetry; + uint64_t OwnedRetryArgs[6] = {32, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, OwnedRetryArgs, &OwnedRetry); + Show("io_getevents_recovery_delivered", FinishSyscallArguments(0, &OwnedRetry) == 1 && SealedEvents[0].Data == 0x47); + uint32_t ReplacementRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + const uint64_t Replaced = reinterpret_cast(ReplacementRing); + FailReap(Replaced, {0x48, reinterpret_cast(&KeyB), 1, 0}); + const auto ReplacedCopies = IoCopyCount.load(); + ArgumentStorage OldSubmit; + uint64_t OldSubmitArgs[6] = {Replaced, 1, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, OldSubmitArgs, &OldSubmit); + const auto OldCopy = reinterpret_cast(OldSubmitArgs[2])[0]; + FinishSyscallArguments(1, &OldSubmit); + ArgumentStorage OldDestroy; + uint64_t OldDestroyArgs[6] = {Replaced, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, OldDestroyArgs, &OldDestroy); + uint64_t ReplacementContext = Replaced; + ArgumentStorage Replacement; + uint64_t ReplacementArgs[6] = {128, reinterpret_cast(&ReplacementContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, ReplacementArgs, &Replacement); + FinishSyscallArguments(0, &Replacement); + ArgumentStorage NewSubmit; + uint64_t NewSubmitArgs[6] = {Replaced, 1, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, NewSubmitArgs, &NewSubmit); + const auto NewCopy = reinterpret_cast(NewSubmitArgs[2])[0]; + FinishSyscallArguments(1, &NewSubmit); + ArgumentStorage StaleReap; + uint64_t StaleReapArgs[6] = {Replaced, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, StaleReapArgs, &StaleReap); + const bool StaleSkipped = StaleReapArgs[1] == 1 && StaleReapArgs[2] == 1; + FinishSyscallArguments(0, &StaleReap); + FailReap(Replaced, {0x49, reinterpret_cast(&KeyB), 1, 0}); + FinishSyscallArguments(0, &OldDestroy); + Show("io_destroy_replacement_copies_kept", StaleSkipped && IoCopyCount.load() - ReplacedCopies == 1 && OldCopy != NewCopy && + !FindIoCopyLocked(OldCopy) && FindIoCopyLocked(NewCopy)); + ArgumentStorage ReplacementRetry; + uint64_t ReplacementRetryArgs[6] = {Replaced, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ReplacementRetryArgs, &ReplacementRetry); + Show("io_destroy_replacement_stash_kept", FinishSyscallArguments(0, &ReplacementRetry) == 1 && SealedEvents[0].Data == 0x49); + ArgumentStorage NewDestroy; + uint64_t NewDestroyArgs[6] = {Replaced, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, NewDestroyArgs, &NewDestroy); + FinishSyscallArguments(0, &NewDestroy); + Show("io_destroy_replacement_released", IoCopyCount.load() - ReplacedCopies + (FindIoCopyLocked(NewCopy) != nullptr)); + uint32_t WakeRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + const uint64_t Woken = reinterpret_cast(WakeRing); + uint64_t WakeContext = Woken; + ArgumentStorage WakeSetup; + uint64_t WakeSetupArgs[6] = {128, reinterpret_cast(&WakeContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, WakeSetupArgs, &WakeSetup); + const bool SetupPrivate = WakeSetupArgs[1] == reinterpret_cast(&WakeSetup.SetupId); + FinishSyscallArguments(0, &WakeSetup); + const auto WakeGeneration = AioContextsLocked()[Woken].Generation; + ArgumentStorage WakeRejected; + uint64_t WakeRejectedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, WakeRejectedArgs, &WakeRejected); + FinishSyscallArguments(static_cast(-EINVAL), &WakeRejected); + Show("io_setup_generation_kept", SetupPrivate && WakeGeneration != 0 && AioContextsLocked().count(Woken) == 1 && + AioContextsLocked()[Woken].Generation == WakeGeneration && AioContextsLocked()[Woken].Live); + const uint64_t EventWords = sizeof(TestEvent) / sizeof(uint64_t); + const int ReapsBefore = AioReaps; + ArgumentStorage Blocked; + uint64_t BlockedArgs[6] = {Woken, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, BlockedArgs, &Blocked); + Show("io_getevents_blocking_sliced", Blocked.Blocking && BlockedArgs[1] == 2 && BlockedArgs[2] == 2 && + BlockedArgs[4] == reinterpret_cast(Blocked.Wait) && Blocked.Wait[0] == 0 && Blocked.Wait[1] == 20000000 && Blocked.Deadline < 0); + ArgumentStorage StashPair; + uint64_t StashPairArgs[6] = {Woken, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, StashPairArgs, &StashPair); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent StashPairEvents[2] = {{0x4a, reinterpret_cast(&KeyB), 1, 0}, {0x4b, reinterpret_cast(&KeyC), 1, 0}}; + Deliver(StashPairArgs, StashPairEvents, sizeof(StashPairEvents)); + const auto StashPairResult = FinishSyscallArguments(2, &StashPair); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + Show("io_getevents_slice_collects_stash", StashPairResult == static_cast(-EFAULT) && FinishSyscallArguments(0, &Blocked) == 2 && + AioReaps == ReapsBefore && SealedEvents[0].Data == 0x4a && SealedEvents[1].Data == 0x4b && + SealedEvents[1].Object == reinterpret_cast(&KeyC)); + ArgumentStorage Waiting; + uint64_t WaitingArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, WaitingArgs, &Waiting); + bool SiblingStashed = false; + AioReapHook = [&](const uint64_t* Words) -> long { + SiblingStashed = Words[1] == Woken && Words[2] == 1 && Words[3] == 1 && Words[4] == reinterpret_cast(Waiting.EventBuffer.data()) && + Words[5] == reinterpret_cast(Waiting.Wait) && Waiting.Wait[1] == 20000000 && + FailReap(Woken, {0x4c, reinterpret_cast(&KeyB), 1, 0}) == static_cast(-EFAULT); + return 0; + }; + const auto WaitingResult = FinishSyscallArguments(0, &Waiting); + AioReapHook = nullptr; + Show("io_getevents_slice_without_notification", SiblingStashed && WaitingResult == 1 && AioReaps == ReapsBefore + 1 && + AioReapArgs[0] == SYS_io_getevents && SealedEvents[0].Data == 0x4c); + ArgumentStorage Gathering; + uint64_t GatheringArgs[6] = {Woken, 3, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, GatheringArgs, &Gathering); + const TestEvent Trickle[3] = {{0x51, reinterpret_cast(&KeyA), 1, 0}, {0x52, reinterpret_cast(&KeyB), 1, 0}, + {0x53, reinterpret_cast(&KeyC), 1, 0}}; + Deliver(GatheringArgs, &Trickle[0], sizeof(TestEvent)); + int Waits = 0; + bool Remaining = true; + AioReapHook = [&](const uint64_t* Words) -> long { + ++Waits; + if (Waits == 1) { + Remaining = Remaining && Words[2] == 2 && Words[3] == 2 && Words[4] == reinterpret_cast(Gathering.EventBuffer.data() + EventWords); + return 0; + } + const uint64_t Have = Waits == 2 ? 1 : 2; + Remaining = Remaining && Words[2] == 3 - Have && Words[3] == 3 - Have && + Words[4] == reinterpret_cast(Gathering.EventBuffer.data() + Have * EventWords); + std::memcpy(reinterpret_cast(Words[4]), &Trickle[Have], sizeof(TestEvent)); + return 1; + }; + const auto GatheringResult = FinishSyscallArguments(1, &Gathering); + AioReapHook = nullptr; + Show("io_getevents_slices_accumulate", GatheringResult == 3 && Waits == 3 && Remaining && SealedEvents[0].Data == 0x51 && + SealedEvents[1].Data == 0x52 && SealedEvents[2].Data == 0x53 && SealedEvents[2].Object == reinterpret_cast(&KeyC)); + ArgumentStorage Interrupt; + uint64_t InterruptArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, InterruptArgs, &Interrupt); + const int ReapsInterrupt = AioReaps; + Show("io_getevents_slice_host_eintr", FinishSyscallArguments(0, &Interrupt) == static_cast(-EINTR) && AioReaps == ReapsInterrupt + 1); + FEX::HLE::TestThread.SignalInfo.DeferredSignalFrames.push_back(SIGUSR1); + ArgumentStorage Signalled; + uint64_t SignalledArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SignalledArgs, &Signalled); + const int ReapsSignalled = AioReaps; + const auto SignalledResult = FinishSyscallArguments(0, &Signalled); + ArgumentStorage SignalledSome; + uint64_t SignalledSomeArgs[6] = {Woken, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SignalledSomeArgs, &SignalledSome); + Deliver(SignalledSomeArgs, &Trickle[1], sizeof(TestEvent)); + const auto SignalledSomeResult = FinishSyscallArguments(1, &SignalledSome); + FEX::HLE::TestThread.SignalInfo.DeferredSignalFrames.clear(); + Show("io_getevents_slice_deferred_signal", SignalledResult == static_cast(-EINTR) && SignalledSomeResult == 1 && + AioReaps == ReapsSignalled && SealedEvents[0].Data == 0x52); + ArgumentStorage Polled; + uint64_t PolledArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, PolledArgs, &Polled); + const int ReapsPolled = AioReaps; + Show("io_getevents_zero_timeout", PolledArgs[4] == reinterpret_cast(Polled.Wait) && Polled.Wait[0] == 0 && Polled.Wait[1] == 0 && + FinishSyscallArguments(0, &Polled) == 0 && AioReaps == ReapsPolled); + int64_t ShortWait[2] = {0, 1000000}; + ArgumentStorage Timed; + uint64_t TimedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), reinterpret_cast(ShortWait), 0}; + const auto TimedStart = std::chrono::steady_clock::now(); + Call(Sys::SYSCALL_x64_io_getevents, TimedArgs, &Timed); + const bool TimedFirst = Timed.Wait[0] == 0 && Timed.Wait[1] > 0 && Timed.Wait[1] <= 1000000; + bool TimedBounded = true; + AioReapHook = [&](const uint64_t* Words) -> long { + const auto* Wait = reinterpret_cast(Words[5]); + TimedBounded = TimedBounded && Wait[0] == 0 && Wait[1] > 0 && Wait[1] <= 1000000; + return 0; + }; + const auto TimedResult = FinishSyscallArguments(0, &Timed); + const auto TimedTook = std::chrono::steady_clock::now() - TimedStart; + AioReapHook = nullptr; + Show("io_getevents_timeout_returns_empty", TimedFirst && TimedBounded && TimedResult == 0 && TimedTook >= std::chrono::milliseconds(1) && + ShortWait[0] == 0 && ShortWait[1] == 1000000); + int64_t LongWait[2] = {5, 0}; + uint64_t MaskWords[2] = {0, 8}; + ArgumentStorage Masked; + uint64_t MaskedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), reinterpret_cast(LongWait), reinterpret_cast(MaskWords)}; + Call(Sys::SYSCALL_x64_io_pgetevents, MaskedArgs, &Masked); + const bool MaskedSliced = Masked.Wait[0] == 0 && Masked.Wait[1] == 20000000 && Masked.Deadline > 0; + AioReapHook = [&](const uint64_t* Words) -> long { + std::memcpy(reinterpret_cast(Words[4]), &Trickle[2], sizeof(TestEvent)); + return 1; + }; + const auto MaskedResult = FinishSyscallArguments(0, &Masked); + AioReapHook = nullptr; + Show("io_pgetevents_slices_keep_mask", MaskedSliced && MaskedResult == 1 && AioReapArgs[0] == SYS_io_pgetevents && + AioReapArgs[6] == reinterpret_cast(MaskWords) && SealedEvents[0].Data == 0x53); + int64_t BadWait[2] = {0, 2000000000}; + ArgumentStorage Unsliced; + uint64_t UnslicedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), reinterpret_cast(BadWait), 0}; + Call(Sys::SYSCALL_x64_io_getevents, UnslicedArgs, &Unsliced); + const int ReapsUnsliced = AioReaps; + Show("io_getevents_odd_timeout_native", !Unsliced.Blocking && UnslicedArgs[1] == 1 && UnslicedArgs[4] == reinterpret_cast(BadWait) && + FinishSyscallArguments(0, &Unsliced) == 0 && AioReaps == ReapsUnsliced); + uint64_t* Published = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + uint32_t LostRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + *Published = reinterpret_cast(LostRing); + ArgumentStorage Unpublished; + uint64_t UnpublishedArgs[6] = {128, reinterpret_cast(Published), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, UnpublishedArgs, &Unpublished); + mprotect(Published, Page, PROT_READ); + Show("io_setup_unpublished_result", FinishSyscallArguments(0, &Unpublished)); + Show("io_setup_unpublished_destroyed", AioDestroyed == reinterpret_cast(LostRing) && + AioContextsLocked().count(reinterpret_cast(LostRing)) == 0); + mprotect(Published, Page, PROT_READ | PROT_WRITE); + uint32_t ReusedRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + const uint64_t Reused = reinterpret_cast(ReusedRing); + *Published = Reused; + uint64_t ReusedGeneration = 0; + AioDestroyHook = [&](uint64_t Ring) { ReusedGeneration = BeginContext(Ring); }; + ArgumentStorage ReusedSetup; + uint64_t ReusedSetupArgs[6] = {128, reinterpret_cast(Published), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, ReusedSetupArgs, &ReusedSetup); + mprotect(Published, Page, PROT_READ); + const auto ReusedResult = FinishSyscallArguments(0, &ReusedSetup); + AioDestroyHook = nullptr; + Show("io_setup_rollback_keeps_reused_context", ReusedResult == static_cast(-EFAULT) && ReusedGeneration != 0 && + AioContextsLocked().count(Reused) == 1 && AioContextsLocked()[Reused].Generation == ReusedGeneration); + ReleaseContext(Reused, ReusedGeneration); + mprotect(Published, Page, PROT_NONE); + ArgumentStorage UnreadableSetup; + uint64_t UnreadableArgs[6] = {128, reinterpret_cast(Published), 0, 0, 0, 0}; + Show("io_setup_unreadable_output_faults", Call(Sys::SYSCALL_x64_io_setup, UnreadableArgs, &UnreadableSetup) == static_cast(-EFAULT) && + UnreadableArgs[1] == reinterpret_cast(Published) && UnreadableSetup.SetupContext == 0 && + FinishSyscallArguments(static_cast(-EFAULT), &UnreadableSetup) == static_cast(-EFAULT)); + munmap(Published, Page); + ArgumentStorage BogusReap; + uint64_t BogusReapArgs[6] = {0x5bad, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, BogusReapArgs, &BogusReap); + FinishSyscallArguments(static_cast(-EINVAL), &BogusReap); + Show("io_getevents_invalid_context_forgotten", AioContextsLocked().count(0x5bad)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage Pending; + uint64_t PendingArgs[6] = {33, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, PendingArgs, &Pending); + ArgumentStorage Rejected; + uint64_t RejectedArgs[6] = {33, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_pgetevents, RejectedArgs, &Rejected); + FinishSyscallArguments(static_cast(-EINVAL), &Rejected); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent PendingEvent {0x4a, reinterpret_cast(&KeyB), 1, 0}; + Deliver(PendingArgs, &PendingEvent, sizeof(PendingEvent)); + FinishSyscallArguments(1, &Pending); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage PendingRetry; + uint64_t PendingRetryArgs[6] = {33, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, PendingRetryArgs, &PendingRetry); + Show("io_getevents_rejected_sibling_kept", FinishSyscallArguments(0, &PendingRetry) == 1 && SealedEvents[0].Data == 0x4a); + FailReap(10, {0x33, reinterpret_cast(&KeyC), 1, 0}); + ArgumentStorage StashDestroy; + uint64_t StashDestroyArgs[6] = {10, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, StashDestroyArgs, &StashDestroy); + FinishSyscallArguments(0, &StashDestroy); + ArgumentStorage DestroyedReap; + uint64_t DestroyedReapArgs[6] = {10, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, DestroyedReapArgs, &DestroyedReap); + Show("io_getevents_stash_destroyed", DestroyedReapArgs[2] == 1 && FinishSyscallArguments(0, &DestroyedReap) == 0); + ArgumentStorage TripleFailed; + uint64_t TripleFailedArgs[6] = {4, 3, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, TripleFailedArgs, &TripleFailed); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent Triple[3] = {{0x31, reinterpret_cast(&KeyA), 1, 0}, {0x32, reinterpret_cast(&KeyB), 1, 0}, + {0x33, reinterpret_cast(&KeyC), 1, 0}}; + Deliver(TripleFailedArgs, Triple, sizeof(Triple)); + Show("io_getevents_stash_triple_failed", FinishSyscallArguments(3, &TripleFailed)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage SealedRetry; + uint64_t SealedRetryArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SealedRetryArgs, &SealedRetry); + mprotect(SealedEvents, Page, PROT_READ); + Show("io_getevents_stash_retry_failed", FinishSyscallArguments(0, &SealedRetry)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage OrderedReap; + uint64_t OrderedReapArgs[6] = {4, 3, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, OrderedReapArgs, &OrderedReap); + Show("io_getevents_stash_ordered_result", FinishSyscallArguments(0, &OrderedReap)); + Show("io_getevents_stash_ordered", SealedEvents[0].Data == 0x31 && SealedEvents[1].Data == 0x32 && SealedEvents[2].Data == 0x33 && + SealedEvents[2].Object == reinterpret_cast(&KeyC)); + static TestEvent ManyEvents[100]; + for (uint64_t i = 0; i < 100; ++i) { + ManyEvents[i] = {0x1000 + i, reinterpret_cast(&KeyA), 1, 0}; + } + ArgumentStorage ManyFailed; + uint64_t ManyFailedArgs[6] = {4, 100, 100, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ManyFailedArgs, &ManyFailed); + mprotect(SealedEvents, Page, PROT_READ); + Deliver(ManyFailedArgs, ManyEvents, sizeof(ManyEvents)); + Show("io_getevents_stash_many_failed", FinishSyscallArguments(100, &ManyFailed)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage ManyRetry; + uint64_t ManyRetryArgs[6] = {4, 100, 100, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ManyRetryArgs, &ManyRetry); + bool ManyOrdered = FinishSyscallArguments(0, &ManyRetry) == 100; + for (uint64_t i = 0; i < 100; ++i) { + ManyOrdered = ManyOrdered && SealedEvents[i].Data == 0x1000 + i; + } + Show("io_getevents_stash_many_kept", ManyOrdered); + for (uint64_t Context = 100; Context < 120; ++Context) { + FailReap(Context, {Context, reinterpret_cast(&KeyA), 1, 0}); + } + bool EveryContext = true; + for (uint64_t Context = 100; Context < 120; ++Context) { + ArgumentStorage ContextRetry; + uint64_t ContextRetryArgs[6] = {Context, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ContextRetryArgs, &ContextRetry); + EveryContext = EveryContext && FinishSyscallArguments(0, &ContextRetry) == 1 && SealedEvents[0].Data == Context; + } + Show("io_getevents_stash_every_context", EveryContext); + TestIocb DirectBlock = ReadBlock; + uint64_t DirectList[1] = {reinterpret_cast(&DirectBlock)}; + auto SubmitDirect = [&] { + ArgumentStorage DirectSubmit; + uint64_t DirectSubmitArgs[6] = {11, 1, reinterpret_cast(DirectList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, DirectSubmitArgs, &DirectSubmit); + const auto Sent = reinterpret_cast(DirectSubmitArgs[2])[0]; + FinishSyscallArguments(1, &DirectSubmit); + return Sent; + }; + const auto DirectBefore = IoCopyCount.load(); + const auto DirectSent = SubmitDirect(); + mprotect(SealedEvents, Page, PROT_READ); + ArgumentStorage DirectReap; + uint64_t DirectReapArgs[6] = {11, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, DirectReapArgs, &DirectReap); + Show("io_getevents_unwritable_first_staged", DirectReapArgs[3] == reinterpret_cast(DirectReap.EventBuffer.data()) && DirectReapArgs[2] == 1); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + const TestEvent DirectEvent {0x21, DirectSent, 64, 0}; + Deliver(DirectReapArgs, &DirectEvent, sizeof(DirectEvent)); + Show("io_getevents_late_writable_result", FinishSyscallArguments(1, &DirectReap)); + Show("io_getevents_late_writable_object", SealedEvents[0].Object == reinterpret_cast(&DirectBlock)); + Show("io_getevents_late_writable_released", IoCopyCount.load() - DirectBefore); + const auto HiddenSent = SubmitDirect(); + SealedEvents[0] = {}; + mprotect(SealedEvents, Page, PROT_READ); + ArgumentStorage HiddenReap; + uint64_t HiddenReapArgs[6] = {11, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, HiddenReapArgs, &HiddenReap); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + const TestEvent HiddenEvent {0x22, HiddenSent, 64, 0}; + Deliver(HiddenReapArgs, &HiddenEvent, sizeof(HiddenEvent)); + mprotect(SealedEvents, Page, PROT_NONE); + Show("io_getevents_hidden_result", FinishSyscallArguments(1, &HiddenReap)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + Show("io_getevents_hidden_no_private", SealedEvents[0].Object == 0); + Show("io_getevents_hidden_released", IoCopyCount.load() - DirectBefore); + ArgumentStorage HiddenRetry; + uint64_t HiddenRetryArgs[6] = {11, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, HiddenRetryArgs, &HiddenRetry); + Show("io_getevents_hidden_retry", FinishSyscallArguments(0, &HiddenRetry) == 1 && SealedEvents[0].Data == 0x22 && + SealedEvents[0].Object == reinterpret_cast(&DirectBlock)); + ArgumentStorage DirectDestroy; + uint64_t DirectDestroyArgs[6] = {11, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DirectDestroyArgs, &DirectDestroy); + FinishSyscallArguments(0, &DirectDestroy); + munmap(SealedEvents, Page); + munmap(SealedEvents, Page); + ArgumentStorage WrappedReap; + uint64_t WrappedReapArgs[6] = {4, 1, 1024, 0xFFFF'FFFF'FFFF'F000ULL, 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, WrappedReapArgs, &WrappedReap); + Show("io_getevents_wrapped_staged", WrappedReapArgs[3] == reinterpret_cast(WrappedReap.EventBuffer.data()) && WrappedReapArgs[2] == 1 && + WrappedReap.EventBuffer.size() == sizeof(TestEvent) / sizeof(uint64_t)); + Show("io_getevents_wrapped_result", FinishSyscallArguments(static_cast(-EFAULT), &WrappedReap)); + auto* EdgeEvents = static_cast(mmap(nullptr, 2 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + mprotect(EdgeEvents + Page, Page, PROT_READ); + ArgumentStorage EdgeReap; + uint64_t EdgeReapArgs[6] = {4, 3, 4, reinterpret_cast(EdgeEvents + Page - 2 * sizeof(TestEvent)), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, EdgeReapArgs, &EdgeReap); + Show("io_getevents_writable_prefix", EdgeReapArgs[2]); + Show("io_getevents_writable_min", EdgeReapArgs[1]); + Show("io_getevents_writable_buffer", EdgeReap.EventBuffer.size() * sizeof(uint64_t) / sizeof(TestEvent)); + munmap(EdgeEvents, 2 * Page); + uint32_t Ring[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + uint64_t RingContext = reinterpret_cast(Ring); + ArgumentStorage Setup; + uint64_t SetupArgs[6] = {128, reinterpret_cast(&RingContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, SetupArgs, &Setup); + FinishSyscallArguments(0, &Setup); + Show("io_setup_magic", Ring[4]); + Show("io_setup_header_kept", Ring[0] == 0 && Ring[1] == 128 && Ring[2] == 0 && Ring[3] == 0 && Ring[5] == 1 && Ring[6] == 0 && Ring[7] == 32); + uint32_t KeptRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + uint64_t KeptContext = reinterpret_cast(KeptRing); + ArgumentStorage FailedSetup; + uint64_t FailedSetupArgs[6] = {128, reinterpret_cast(&KeptContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, FailedSetupArgs, &FailedSetup); + FinishSyscallArguments(static_cast(-EINVAL), &FailedSetup); + Show("io_setup_failed_magic", KeptRing[4]); + + TestEvent Completions[2] = {{7, Base + 1536, 16, 0}, {8, Base + 1536, 16, 0}}; + ArgumentStorage Reap; + uint64_t ReapArgs[6] = {1, 1, 2, reinterpret_cast(Completions), 0, 0}; + Show("io_getevents_result", Call(Sys::SYSCALL_x64_io_getevents, ReapArgs, &Reap)); + Deliver(ReapArgs, Completions, sizeof(Completions)); + FinishSyscallArguments(1, &Reap); + Show("io_getevents_object", Completions[0].Object - Single); + Show("io_getevents_unreported", Completions[1].Object - Base); + + uint64_t Pages[2] = {Single + 16, Low}; + int PageStatus[2] = {}; + ArgumentStorage Move; + uint64_t MoveArgs[6] = {0, 2, reinterpret_cast(Pages), 0, reinterpret_cast(PageStatus), 0}; + Show("move_pages_result", Call(Sys::SYSCALL_x64_move_pages, MoveArgs, &Move)); + Show("move_pages_copied", MoveArgs[2] != reinterpret_cast(Pages)); + Show("move_pages_first", reinterpret_cast(MoveArgs[2])[0] - Base); + Show("move_pages_second", reinterpret_cast(MoveArgs[2])[1] == Low); + Show("move_pages_guest_list", Pages[0] - Single); + ArgumentStorage Remote; + uint64_t RemoteArgs[6] = {1, 2, reinterpret_cast(Pages), 0, reinterpret_cast(PageStatus), 0}; + Show("move_pages_remote_result", Call(Sys::SYSCALL_x64_move_pages, RemoteArgs, &Remote)); + Show("move_pages_remote_kept", RemoteArgs[2] == reinterpret_cast(Pages)); + + uint32_t LowWord = 0; + uint64_t Waiters[2][3] = {{0, Single + 64, 2}, {0, reinterpret_cast(&LowWord), 2}}; + ArgumentStorage Wait; + uint64_t WaitArgs[6] = {reinterpret_cast(Waiters), 2, 0, 0, 1, 0}; + Show("futex_waitv_result", Call(Sys::SYSCALL_x64_futex_waitv, WaitArgs, &Wait)); + Show("futex_waitv_copied", WaitArgs[0] != reinterpret_cast(Waiters)); + Show("futex_waitv_first", reinterpret_cast(WaitArgs[0])[1] - Base); + Show("futex_waitv_second", reinterpret_cast(WaitArgs[0])[4] == reinterpret_cast(&LowWord)); + Show("futex_waitv_guest", Waiters[0][1] - Single); + uint64_t Straddling[1][3] = {{0, Split + Page - 2, 2}}; + ArgumentStorage WaitBad; + uint64_t WaitBadArgs[6] = {reinterpret_cast(Straddling), 1, 0, 0, 1, 0}; + Show("futex_waitv_split_result", Call(Sys::SYSCALL_x64_futex_waitv, WaitBadArgs, &WaitBad)); + uint64_t Requeue[2][3] = {{0, Single + 64, 2}, {0, Single + 128, 2}}; + ArgumentStorage RequeueStorage; + uint64_t RequeueArgs[6] = {reinterpret_cast(Requeue), 0, 1, 1, 0, 0}; + Show("futex_requeue_result", Call(Sys::SYSCALL_x64_futex_requeue, RequeueArgs, &RequeueStorage)); + Show("futex_requeue_second", reinterpret_cast(RequeueArgs[0])[4] - Base); + + const uint64_t Mapped = 0x780000000000ULL; + const int Anonymous = MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED; + Show("map_result", Map(Mapped, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0) - Mapped); + const uint32_t MappedEntries = Count.load(); + Show("map_unmap", Unmap(Mapped + Page, Page)); + Show("map_again", Map(Mapped + Page, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0) - Mapped); + FindLocked(Mapped, &Part); + Show("map_merged_size", Part.Size); + Show("map_merged_entries", Count.load() - MappedEntries); + Show("map_unmap_again", Unmap(Mapped + Page, Page)); + Show("map_readonly", Map(Mapped + Page, Page, PROT_READ, Anonymous, -1, 0) - Mapped); + FindLocked(Mapped, &Part); + Show("map_readonly_size", Part.Size); + Show("map_readonly_entries", Count.load() - MappedEntries); + + auto* Order = static_cast(mmap(nullptr, 5 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t OrderHost = reinterpret_cast(Order); + const uint64_t Ordered = 0x770000000000ULL; + const uint32_t OrderEntries = Count.load(); + AddEntry(Ordered + Page, Page, OrderHost + Page, false, PROT_READ); + AddEntry(Ordered + 3 * Page, Page, OrderHost + 4 * Page, false, PROT_READ); + AddEntry(Ordered, Page, OrderHost, false, PROT_READ); + AddEntry(Ordered + 2 * Page, Page, OrderHost + 3 * Page, false, PROT_READ); + Show("slot_order_restore", Protect(Ordered, 4 * Page, PROT_READ | PROT_WRITE)); + Show("slot_order_entries", Count.load() - OrderEntries); + FindLocked(Ordered + 2 * Page, &Part); + Show("slot_order_second_size", Part.Size); + + ArgumentStorage Widths; + uint64_t GroupsWide[6] = {(1ULL << 32) + 1, Single + Page - 4, 0, 0, 0, 0}; + Show("getgroups_wide_result", Call(Sys::SYSCALL_x64_getgroups, GroupsWide, &Widths)); + Show("getgroups_wide_list", GroupsWide[1] - Base); + uint64_t GroupsNegative[6] = {0xffffffffULL, Single + Page - 4, 0, 0, 0, 0}; + Show("getgroups_negative_result", Call(Sys::SYSCALL_x64_getgroups, GroupsNegative, &Widths)); + uint64_t GroupsLarge[6] = {(1ULL << 32) + 2, Single + Page - 4, 0, 0, 0, 0}; + Show("getgroups_large_result", Call(Sys::SYSCALL_x64_getgroups, GroupsLarge, &Widths)); + uint64_t PollWide[6] = {Single + Page - 8, (1ULL << 32) + 1, 0, 0, 0, 0}; + Show("poll_wide_result", Call(Sys::SYSCALL_x64_poll, PollWide, &Widths)); + uint64_t EpollNegative[6] = {3, Single + Page - 12, 0xffffffffULL, 0, 0, 0}; + Show("epoll_negative_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollNegative, &Widths)); + ArgumentStorage NegativeReap; + uint64_t EventsNegative[6] = {1, 1, static_cast(-1), Single, 0, 0}; + Show("io_getevents_negative_result", Call(Sys::SYSCALL_x64_io_getevents, EventsNegative, &NegativeReap)); + + struct iovec PrefixVectors[2] = {{reinterpret_cast(Single + 256), 32}, {reinterpret_cast(Split + Page - 8), 16}}; + struct mmsghdr Prefix[2] {}; + Prefix[0].msg_hdr.msg_iov = &PrefixVectors[0]; + Prefix[0].msg_hdr.msg_iovlen = 1; + Prefix[1].msg_hdr.msg_iov = &PrefixVectors[1]; + Prefix[1].msg_hdr.msg_iovlen = 1; + ArgumentStorage PrefixBatch; + uint64_t PrefixArgs[6] = {3, reinterpret_cast(Prefix), 2, 0, 0, 0}; + Show("sendmmsg_prefix_result", Call(Sys::SYSCALL_x64_sendmmsg, PrefixArgs, &PrefixBatch)); + Show("sendmmsg_prefix_count", PrefixArgs[2]); + ArgumentStorage PrefixBad; + uint64_t PrefixBadArgs[6] = {3, reinterpret_cast(&Prefix[1]), 1, 0, 0, 0}; + Show("sendmmsg_first_bad_result", Call(Sys::SYSCALL_x64_sendmmsg, PrefixBadArgs, &PrefixBad)); + auto* ApartFirst = reinterpret_cast(Backing + 3 * Page - sizeof(struct mmsghdr)); + auto* ApartSecond = reinterpret_cast(Backing + 4 * Page); + char ApartLow[32]; + struct iovec ApartVectors[2] = {{ApartLow, 11}, {ApartLow, 22}}; + *ApartFirst = {}; + ApartFirst->msg_hdr.msg_iov = &ApartVectors[0]; + ApartFirst->msg_hdr.msg_iovlen = 1; + *ApartSecond = {}; + ApartSecond->msg_hdr.msg_iov = &ApartVectors[1]; + ApartSecond->msg_hdr.msg_iovlen = 1; + ArgumentStorage ApartBatch; + uint64_t HeadersApart[6] = {static_cast(Peer), Split + Page - sizeof(struct mmsghdr), 2, 0, 0, 0}; + Show("sendmmsg_headers_apart_result", Call(Sys::SYSCALL_x64_sendmmsg, HeadersApart, &ApartBatch)); + Show("sendmmsg_headers_apart_count", HeadersApart[2]); + auto* ApartHost = reinterpret_cast(HeadersApart[1]); + Show("sendmmsg_headers_apart_first", ApartHost[0].msg_hdr.msg_iov[0].iov_len); + Show("sendmmsg_headers_apart_second", ApartHost[1].msg_hdr.msg_iov[0].iov_len); + SendCalls = 0; + ApartHost[0].msg_len = 11; + Show("sendmmsg_headers_apart_finish", FinishResult(1, &ApartBatch)); + Show("sendmmsg_headers_apart_sent", SentLengths[0]); + Show("sendmmsg_headers_apart_lengths", ApartFirst->msg_len * 0x100 + ApartSecond->msg_len); + + struct iovec MovingVector = {reinterpret_cast(Single + 256), 32}; + const uint64_t Moving = 0x760000000000ULL; + Map(Moving, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t OldHost {}; + TranslateRange(Moving, Page, &OldHost); + auto* MovingHeaders = reinterpret_cast(OldHost); + MovingHeaders[0] = {}; + MovingHeaders[0].msg_hdr.msg_iov = &MovingVector; + MovingHeaders[0].msg_hdr.msg_iovlen = 1; + ArgumentStorage MovingBatch; + uint64_t MovingArgs[6] = {3, Moving, 1, 0, 0, 0}; + Show("moved_result", Call(Sys::SYSCALL_x64_sendmmsg, MovingArgs, &MovingBatch)); + reinterpret_cast(MovingArgs[1])[0].msg_len = 32; + Unmap(Moving, Page); + auto* Unrelated = static_cast(mmap(reinterpret_cast(OldHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0)); + Map(Moving, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t NewHost {}; + TranslateRange(Moving, Page, &NewHost); + Show("moved_finish", FinishResult(1, &MovingBatch)); + Show("moved_unrelated_placed", reinterpret_cast(Unrelated) == OldHost && NewHost != OldHost); + Show("moved_unrelated_length", Unrelated[0].msg_len); + Show("moved_new_length", reinterpret_cast(NewHost)[0].msg_len); + + const uint64_t Sealed = 0x750000000000ULL; + Map(Sealed, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t SealedHost {}; + TranslateRange(Sealed, 2 * Page, &SealedHost); + auto* SealedHeaders = reinterpret_cast(SealedHost + Page - sizeof(struct mmsghdr)); + for (int i = 0; i < 3; ++i) { + SealedHeaders[i] = {}; + SealedHeaders[i].msg_hdr.msg_iov = &MovingVector; + SealedHeaders[i].msg_hdr.msg_iovlen = 1; + } + Protect(Sealed + Page, Page, PROT_READ); + ArgumentStorage SealedBatch; + uint64_t SealedArgs[6] = {static_cast(Peer), Sealed + Page - sizeof(struct mmsghdr), 3, 0, 0, 0}; + Show("sealed_result", Call(Sys::SYSCALL_x64_sendmmsg, SealedArgs, &SealedBatch)); + Show("sealed_submitted", SealedArgs[2]); + auto* SealedCopy = reinterpret_cast(SealedArgs[1]); + SealedCopy[0].msg_len = 32; + SendCalls = 0; + Show("sealed_finish", FinishResult(1, &SealedBatch)); + Show("sealed_later_sends", SendCalls); + Show("sealed_first_length", SealedHeaders[0].msg_len); + Show("sealed_second_length", SealedHeaders[1].msg_len); + Show("sealed_third_length", SealedHeaders[2].msg_len); + ArgumentStorage SealedOnly; + uint64_t SealedOnlyArgs[6] = {3, Sealed + Page, 1, 0, 0, 0}; + Show("sealed_only_result", Call(Sys::SYSCALL_x64_sendmmsg, SealedOnlyArgs, &SealedOnly)); + reinterpret_cast(SealedOnlyArgs[1])[0].msg_len = 32; + Show("sealed_only_finish", FinishResult(1, &SealedOnly)); + + ArgumentStorage Embedded; + uint8_t* SplitEnd = Backing + 3 * Page; + const uint32_t Sizes32[] = {64, 0, 72}; + const char* PerfNames[] = {"perf_attr_fits_result", "perf_attr_default_result", "perf_attr_large_result"}; + for (int i = 0; i < 3; ++i) { + std::memcpy(SplitEnd - 64 + 4, &Sizes32[i], 4); + uint64_t PerfArgs[6] = {Split + Page - 64, 0, static_cast(-1), static_cast(-1), 0, 0}; + Show(PerfNames[i], Call(Sys::SYSCALL_x64_perf_event_open, PerfArgs, &Embedded)); + } + const uint32_t SchedSizes[] = {48, 56}; + const char* SchedNames[] = {"sched_attr_fits_result", "sched_attr_large_result"}; + for (int i = 0; i < 2; ++i) { + std::memcpy(SplitEnd - 48, &SchedSizes[i], 4); + uint64_t SchedArgs[6] = {0, Split + Page - 48, 0, 0, 0, 0}; + Show(SchedNames[i], Call(Sys::SYSCALL_x64_sched_setattr, SchedArgs, &Embedded)); + } + const uint32_t CapHeader1[2] = {0x19980330, 0}; + const uint32_t CapHeader3[2] = {0x20080522, 0}; + uint64_t CapV1[6] = {reinterpret_cast(CapHeader1), Split + Page - 12, 0, 0, 0, 0}; + Show("capget_v1_result", Call(Sys::SYSCALL_x64_capget, CapV1, &Embedded)); + Show("capget_v1_data", CapV1[1] - Base); + uint64_t CapV3[6] = {reinterpret_cast(CapHeader3), Split + Page - 12, 0, 0, 0, 0}; + Show("capget_v3_result", Call(Sys::SYSCALL_x64_capget, CapV3, &Embedded)); + uint64_t CapSetV3[6] = {reinterpret_cast(CapHeader3), Split + Page - 12, 0, 0, 0, 0}; + Show("capset_v3_result", Call(Sys::SYSCALL_x64_capset, CapSetV3, &Embedded)); + uint32_t CapGuest[2] = {0x19980330, 0}; + ArgumentStorage CapCopy; + uint64_t CapCopyArgs[6] = {reinterpret_cast(CapGuest), Split + Page - 12, 0, 0, 0, 0}; + Show("capget_copy_result", Call(Sys::SYSCALL_x64_capget, CapCopyArgs, &CapCopy)); + Show("capget_copy_private", CapCopyArgs[0] != reinterpret_cast(CapGuest)); + CapGuest[0] = 0x20080522; + Show("capget_copy_version", reinterpret_cast(CapCopyArgs[0])[0]); + Show("capget_copy_finish", FinishResult(0, &CapCopy)); + Show("capget_copy_guest_version", CapGuest[0]); + uint32_t CapUnknown[2] = {0x1234, 0}; + ArgumentStorage CapInvalid; + uint64_t CapInvalidArgs[6] = {reinterpret_cast(CapUnknown), Single + 64, 0, 0, 0, 0}; + Show("capget_invalid_result", Call(Sys::SYSCALL_x64_capget, CapInvalidArgs, &CapInvalid)); + reinterpret_cast(CapInvalidArgs[0])[0] = 0x20080522; + Show("capget_invalid_finish", FinishResult(static_cast(-EINVAL), &CapInvalid)); + Show("capget_invalid_version", CapUnknown[0]); + const uint32_t HandleBytes[] = {8, 16}; + const char* HandleNames[] = {"name_to_handle_fits_result", "name_to_handle_large_result"}; + const char* OpenNames[] = {"open_by_handle_fits_result", "open_by_handle_large_result"}; + int MountId = 0; + for (int i = 0; i < 2; ++i) { + std::memcpy(SplitEnd - 16, &HandleBytes[i], 4); + uint64_t HandleArgs[6] = {static_cast(AT_FDCWD), reinterpret_cast("x"), Split + Page - 16, reinterpret_cast(&MountId), 0, 0}; + Show(HandleNames[i], Call(Sys::SYSCALL_x64_name_to_handle_at, HandleArgs, &Embedded)); + uint64_t OpenArgs[6] = {3, Split + Page - 16, 0, 0, 0, 0}; + Show(OpenNames[i], Call(Sys::SYSCALL_x64_open_by_handle_at, OpenArgs, &Embedded)); + } + const uint32_t OversizedHandle = 1000; + std::memcpy(SplitEnd - 4, &OversizedHandle, 4); + uint64_t HandleHeaderSplit[6] = {static_cast(AT_FDCWD), reinterpret_cast("x"), Split + Page - 4, reinterpret_cast(&MountId), 0, 0}; + Show("name_to_handle_header_split_result", Call(Sys::SYSCALL_x64_name_to_handle_at, HandleHeaderSplit, &Embedded)); + uint64_t OpenHeaderSplit[6] = {3, Split + Page - 4, 0, 0, 0, 0}; + Show("open_by_handle_header_split_result", Call(Sys::SYSCALL_x64_open_by_handle_at, OpenHeaderSplit, &Embedded)); + std::memcpy(SplitEnd - 8, &OversizedHandle, 4); + uint64_t OpenHeaderFits[6] = {3, Split + Page - 8, 0, 0, 0, 0}; + Show("open_by_handle_header_fits_result", Call(Sys::SYSCALL_x64_open_by_handle_at, OpenHeaderFits, &Embedded)); + const uint32_t RequestSizes[] = {24, 32}; + const char* RequestNames[] = {"statmount_fits_result", "statmount_large_result"}; + for (int i = 0; i < 2; ++i) { + std::memcpy(SplitEnd - 24, &RequestSizes[i], 4); + uint64_t RequestArgs[6] = {Split + Page - 24, 0, 0, 0, 0, 0}; + Show(RequestNames[i], Call(Sys::SYSCALL_x64_statmount, RequestArgs, &Embedded)); + } + uint64_t PathRule[6] = {3, 1, Split + Page - 12, 0, 0, 0}; + Show("landlock_path_result", Call(Sys::SYSCALL_x64_landlock_add_rule, PathRule, &Embedded)); + uint64_t PortRule[6] = {3, 2, Split + Page - 12, 0, 0, 0}; + Show("landlock_port_result", Call(Sys::SYSCALL_x64_landlock_add_rule, PortRule, &Embedded)); + + const uint64_t Nameless = 0x740000000000ULL; + Map(Nameless, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t NamelessHost {}; + TranslateRange(Nameless, 2 * Page, &NamelessHost); + const uint64_t NamelessGuestHeader = Nameless + Page - 16; + auto* NamelessHeader = reinterpret_cast(NamelessHost + Page - 16); + struct iovec NamelessVector = {reinterpret_cast(Single + 128), 64}; + *NamelessHeader = {}; + NamelessHeader->msg_iov = &NamelessVector; + NamelessHeader->msg_iovlen = 1; + Protect(Nameless, Page, PROT_READ); + ArgumentStorage NamelessReceive; + uint64_t NamelessArgs[6] = {3, NamelessGuestHeader, 0, 0, 0, 0}; + Show("recvmsg_nameless_result", Call(Sys::SYSCALL_x64_recvmsg, NamelessArgs, &NamelessReceive)); + NamelessReceive.Message.msg_flags = MSG_TRUNC; + Show("recvmsg_nameless_finish", FinishResult(64, &NamelessReceive)); + Show("recvmsg_nameless_flags", NamelessHeader->msg_flags); + char NameBuffer[16]; + const uint64_t Named = 0x700000000000ULL; + Map(Named, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t NamedHost {}; + TranslateRange(Named, 2 * Page, &NamedHost); + auto* NamedHeader = reinterpret_cast(NamedHost + Page - 16); + *NamedHeader = {}; + NamedHeader->msg_name = NameBuffer; + NamedHeader->msg_namelen = sizeof(NameBuffer); + NamedHeader->msg_iov = &NamelessVector; + NamedHeader->msg_iovlen = 1; + Protect(Named, Page, PROT_READ); + ArgumentStorage NamedReceive; + uint64_t NamedArgs[6] = {3, Named + Page - 16, 0, 0, 0, 0}; + Show("recvmsg_named_result", Call(Sys::SYSCALL_x64_recvmsg, NamedArgs, &NamedReceive)); + Show("recvmsg_named_private", NamedArgs[1] != NamedHost + Page - 16); + Show("recvmsg_named_name_kept", reinterpret_cast(NamedArgs[1])->msg_name == NameBuffer); + Show("recvmsg_named_finish", FinishResult(64, &NamedReceive)); + + const uint64_t Flagged = 0x730000000000ULL; + Map(Flagged, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t FlaggedHost {}; + TranslateRange(Flagged, 2 * Page, &FlaggedHost); + auto* FlaggedHeader = reinterpret_cast(FlaggedHost + Page - offsetof(struct msghdr, msg_flags)); + *FlaggedHeader = {}; + FlaggedHeader->msg_iov = &NamelessVector; + FlaggedHeader->msg_iovlen = 1; + FlaggedHeader->msg_controllen = 99; + Protect(Flagged + Page, Page, PROT_READ); + ArgumentStorage FlaggedReceive; + uint64_t FlaggedArgs[6] = {3, Flagged + Page - offsetof(struct msghdr, msg_flags), 0, 0, 0, 0}; + Show("recvmsg_flags_first_result", Call(Sys::SYSCALL_x64_recvmsg, FlaggedArgs, &FlaggedReceive)); + FlaggedReceive.Message.msg_controllen = 0; + Show("recvmsg_flags_first_finish", FinishResult(64, &FlaggedReceive)); + Show("recvmsg_flags_first_controllen", FlaggedHeader->msg_controllen); + + const uint64_t Blocks = 0x720000000000ULL; + Map(Blocks, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t BlocksHost {}; + TranslateRange(Blocks, Page, &BlocksHost); + auto* HighIocb = reinterpret_cast(BlocksHost); + *HighIocb = {}; + HighIocb->Data = 0x99; + HighIocb->Opcode = 7; + HighIocb->Buffer = reinterpret_cast(Scatter); + HighIocb->Bytes = 2; + const TestIocb HighExpected = *HighIocb; + uint64_t HighIocbList[1] = {Blocks}; + ArgumentStorage HighCopy; + uint64_t HighCopyArgs[6] = {1, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Show("io_submit_high_copy_result", Call(Sys::SYSCALL_x64_io_submit, HighCopyArgs, &HighCopy)); + const uint64_t HighSent = reinterpret_cast(HighCopyArgs[2])[0]; + Show("io_submit_high_copy_private", HighSent != BlocksHost && FindIoCopyLocked(HighSent) != nullptr); + Show("io_submit_high_copy_vector", reinterpret_cast(reinterpret_cast(HighSent)->Buffer)[0].iov_base == reinterpret_cast(Base + 800)); + Show("io_submit_high_copy_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0); + ArgumentStorage HighCancel; + uint64_t HighCancelArgs[6] = {1, Blocks, reinterpret_cast(&CancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, HighCancelArgs, &HighCancel); + Show("io_cancel_high_private", HighCancelArgs[1] == HighSent); + Show("io_submit_high_copy_hidden", Protect(Blocks, Page, PROT_NONE)); + uint64_t SealedProbe = 0; + auto HiddenRead = [&] { return FEX::HLE::FaultSafeUserMemAccess::CopyFromUser(&SealedProbe, &HighIocb->Buffer, sizeof(SealedProbe)) != 0; }; + auto HiddenWrite = [&] { return FEX::HLE::FaultSafeUserMemAccess::CopyToUser(&HighIocb->Buffer, &SealedProbe, sizeof(SealedProbe)) != 0; }; + ProtectCalls = 0; + FinishSyscallArguments(1, &HighCopy); + Show("io_submit_high_copy_sealed", HiddenRead() && HiddenWrite()); + ArgumentStorage HiddenCancel; + uint64_t HiddenCancelArgs[6] = {1, Blocks, reinterpret_cast(&CancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, HiddenCancelArgs, &HiddenCancel); + Show("io_cancel_hidden_native", HiddenCancelArgs[1] == BlocksHost); + TestEvent HighReaped[1] = {{0x99, HighSent, 16, 0}}; + ArgumentStorage HighReap; + uint64_t HighReapArgs[6] = {1, 1, 1, reinterpret_cast(HighReaped), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, HighReapArgs, &HighReap); + Deliver(HighReapArgs, HighReaped, sizeof(HighReaped)); + FinishSyscallArguments(1, &HighReap); + Show("io_getevents_high_object", HighReaped[0].Object - Blocks); + Show("io_getevents_high_sealed", HiddenRead() && HiddenWrite()); + Show("io_getevents_high_protect_calls", ProtectCalls); + Show("io_getevents_high_freed", IoCopyCount.load() - CopiesBefore); + Protect(Blocks, Page, PROT_READ | PROT_WRITE); + Show("io_getevents_high_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0); + + Protect(Blocks, Page, PROT_READ); + ArgumentStorage SealedSubmit; + uint64_t SealedSubmitArgs[6] = {1, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Show("io_submit_read_only_result", Call(Sys::SYSCALL_x64_io_submit, SealedSubmitArgs, &SealedSubmit)); + Show("io_submit_read_only_count", SealedSubmitArgs[1]); + Show("io_submit_read_only_passed", reinterpret_cast(SealedSubmitArgs[2])[0] == BlocksHost); + Show("io_submit_read_only_copies", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(static_cast(-EBADF), &SealedSubmit); + TestIocb Leading = ReadBlock; + uint64_t LeadingList[2] = {reinterpret_cast(&Leading), Blocks}; + ArgumentStorage LeadingSubmit; + uint64_t LeadingSubmitArgs[6] = {5, 2, reinterpret_cast(LeadingList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, LeadingSubmitArgs, &LeadingSubmit); + const auto* LeadingSent = reinterpret_cast(LeadingSubmitArgs[2]); + Show("io_submit_read_only_after_copy", LeadingSubmitArgs[1] == 2 && FindIoCopyLocked(LeadingSent[0]) != nullptr && LeadingSent[1] == BlocksHost); + FinishSyscallArguments(1, &LeadingSubmit); + ArgumentStorage LeadingDestroy; + uint64_t LeadingDestroyArgs[6] = {5, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, LeadingDestroyArgs, &LeadingDestroy); + FinishSyscallArguments(0, &LeadingDestroy); + Show("io_submit_read_only_after_copy_released", IoCopyCount.load() - CopiesBefore); + Show("io_submit_read_only_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0); + Protect(Blocks, Page, PROT_READ | PROT_WRITE); + HighIocb->Opcode = 1; + HighIocb->Buffer = reinterpret_cast(LowBuffer); + HighIocb->Bytes = sizeof(LowBuffer); + Protect(Blocks, Page, PROT_READ); + ArgumentStorage ReadOnlyNative; + uint64_t ReadOnlyNativeArgs[6] = {1, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Show("io_submit_read_only_native_result", Call(Sys::SYSCALL_x64_io_submit, ReadOnlyNativeArgs, &ReadOnlyNative)); + Show("io_submit_read_only_native_block", reinterpret_cast(ReadOnlyNativeArgs[2])[0] == BlocksHost); + Show("io_submit_read_only_native_copies", IoCopyCount.load() - CopiesBefore); + Protect(Blocks, Page, PROT_READ | PROT_WRITE); + HighIocb->Opcode = 7; + HighIocb->Buffer = reinterpret_cast(Scatter); + HighIocb->Bytes = 2; + HighIocb->Key = 4; + ArgumentStorage KeyedHigh; + uint64_t KeyedHighArgs[6] = {7, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, KeyedHighArgs, &KeyedHigh); + FinishSyscallArguments(1, &KeyedHigh); + Show("io_submit_high_key_accepted", HighIocb->Key); + HighIocb->Key = 4; + ArgumentStorage MovedHigh; + uint64_t MovedHighArgs[6] = {7, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, MovedHighArgs, &MovedHigh); + Unmap(Blocks, Page); + void* ReusedPage = mmap(reinterpret_cast(BlocksHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0); + Show("io_submit_key_reused_mapped", ReusedPage == reinterpret_cast(BlocksHost)); + if (ReusedPage == reinterpret_cast(BlocksHost)) { + static_cast(ReusedPage)->Key = 4; + FinishSyscallArguments(1, &MovedHigh); + Show("io_submit_key_unmapped_skipped", static_cast(ReusedPage)->Key); + munmap(ReusedPage, Page); + } + Map(Blocks, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + static uint64_t RacedHost; + static uint32_t RacedSeen; + static TestIocb* RacedStandIn; + static std::thread RacedSibling; + static std::atomic RacedAttempted; + static bool RacedBlocked; + TranslateRange(Blocks, Page, &RacedHost); + auto* RacedIocb = reinterpret_cast(RacedHost); + *RacedIocb = {}; + RacedIocb->Opcode = 7; + RacedIocb->Buffer = reinterpret_cast(Scatter); + RacedIocb->Bytes = 2; + RacedIocb->Key = 4; + ArgumentStorage RacedHigh; + uint64_t RacedHighArgs[6] = {7, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, RacedHighArgs, &RacedHigh); + FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] { + RacedSibling = std::thread([] { + std::unique_lock Lock {FEX::HLE::_SyscallHandler->VMATracking.Mutex, std::try_to_lock}; + RacedBlocked = !Lock.owns_lock(); + RacedAttempted = 1; + if (!Lock.owns_lock()) { + Lock.lock(); + } + RacedSeen = reinterpret_cast(RacedHost)->Key; + Unmap(Blocks, Page); + void* StandIn = mmap(reinterpret_cast(RacedHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0); + if (StandIn == reinterpret_cast(RacedHost)) { + RacedStandIn = static_cast(StandIn); + RacedStandIn->Key = 4; + } + }); + while (RacedAttempted.load() == 0) { + std::this_thread::yield(); + } + }; + FinishSyscallArguments(1, &RacedHigh); + RacedSibling.join(); + Show("io_submit_key_store_blocked_writer", RacedBlocked); + Show("io_submit_key_store_before_unmap", RacedSeen); + Show("io_submit_key_store_stand_in", RacedStandIn != nullptr ? RacedStandIn->Key : 0xff); + Show("io_submit_key_store_released", FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held); + if (RacedStandIn != nullptr) { + munmap(RacedStandIn, Page); + } + ArgumentStorage KeyedDestroy; + uint64_t KeyedDestroyArgs[6] = {7, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, KeyedDestroyArgs, &KeyedDestroy); + FinishSyscallArguments(0, &KeyedDestroy); + Show("io_submit_keyed_high_released", IoCopyCount.load() - CopiesBefore); + + auto* LowBlock = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + *LowBlock = {}; + LowBlock->Opcode = 7; + LowBlock->Buffer = reinterpret_cast(Scatter); + LowBlock->Bytes = 2; + const TestIocb LowExpected = *LowBlock; + uint64_t LowList[1] = {reinterpret_cast(LowBlock)}; + ArgumentStorage LowCopy; + uint64_t LowCopyArgs[6] = {1, 1, reinterpret_cast(LowList), 0, 0, 0}; + Show("low_iocb_result", Call(Sys::SYSCALL_x64_io_submit, LowCopyArgs, &LowCopy)); + const uint64_t LowSent = reinterpret_cast(LowCopyArgs[2])[0]; + Show("low_iocb_private", LowSent != reinterpret_cast(LowBlock) && FindIoCopyLocked(LowSent) != nullptr); + mprotect(LowBlock, Page, PROT_READ); + ProtectCalls = 0; + FinishSyscallArguments(1, &LowCopy); + Show("low_iocb_untouched", std::memcmp(LowBlock, &LowExpected, sizeof(TestIocb)) == 0); + const auto Regions = Count.load(); + Count.store(0); + ArgumentStorage QuietCancel; + uint64_t QuietCancelArgs[6] = {1, reinterpret_cast(LowBlock), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, QuietCancelArgs, &QuietCancel); + Show("low_iocb_quiet_cancel", QuietCancelArgs[1] == LowSent); + TestEvent QuietReaped[1] = {{0, LowSent, 16, 0}}; + ArgumentStorage QuietReap; + uint64_t QuietReapArgs[6] = {1, 1, 1, reinterpret_cast(QuietReaped), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, QuietReapArgs, &QuietReap); + Show("low_iocb_quiet_host_buffer", QuietReapArgs[3] == reinterpret_cast(QuietReap.EventBuffer.data())); + Deliver(QuietReapArgs, QuietReaped, sizeof(QuietReaped)); + FinishSyscallArguments(1, &QuietReap); + uint32_t QuietRing[8] = {0, 64, 0, 0, 0xa10a10a1, 1, 0, 32}; + uint64_t QuietRingContext = reinterpret_cast(QuietRing); + ArgumentStorage QuietSetup; + uint64_t QuietSetupArgs[6] = {64, reinterpret_cast(&QuietRingContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, QuietSetupArgs, &QuietSetup); + FinishSyscallArguments(0, &QuietSetup); + Show("low_quiet_setup_magic", QuietRing[4]); + Count.store(Regions); + Show("low_iocb_quiet_object", QuietReaped[0].Object == reinterpret_cast(LowBlock)); + Show("low_iocb_quiet_freed", IoCopyCount.load() - CopiesBefore); + Show("low_iocb_protect_calls", ProtectCalls); + Show("low_iocb_reaped_untouched", std::memcmp(LowBlock, &LowExpected, sizeof(TestIocb)) == 0); + munmap(LowBlock, Page); + + for (auto& Copy : IoCopies) { + Copy.Used = true; + } + IoCopyCount = MaxIoCopies; + ArgumentStorage Crowded; + uint64_t CrowdedArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + Show("io_submit_crowded_result", Call(Sys::SYSCALL_x64_io_submit, CrowdedArgs, &Crowded)); + Show("io_submit_crowded_untouched", GuestBlocksUntouched()); + IoCopies[5].Used = false; + IoCopyCount = MaxIoCopies - 1; + ArgumentStorage LastCopy; + uint64_t LastCopyArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + Show("io_submit_last_copy_result", Call(Sys::SYSCALL_x64_io_submit, LastCopyArgs, &LastCopy)); + Show("io_submit_last_copy_count", LastCopyArgs[1]); + Show("io_submit_last_copy_slot", reinterpret_cast(LastCopyArgs[2])[0] == reinterpret_cast(&IoCopies[5])); + for (auto& Copy : IoCopies) { + Copy.Used = false; + } + IoCopyCount = 0; + + auto* CapPage = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + CapPage[0] = 0x1234; + ArgumentStorage CapSealed; + uint64_t CapSealedArgs[6] = {reinterpret_cast(CapPage), Single + 64, 0, 0, 0, 0}; + Show("capget_sealed_result", Call(Sys::SYSCALL_x64_capget, CapSealedArgs, &CapSealed)); + reinterpret_cast(CapSealedArgs[0])[0] = 0x20080522; + mprotect(CapPage, Page, PROT_READ); + Show("capget_sealed_finish", FinishResult(static_cast(-EINVAL), &CapSealed)); + Show("capget_sealed_version", CapPage[0]); + + struct iovec ShortVector = {reinterpret_cast(Single + 256), 32}; + struct mmsghdr Shorts[3] {}; + for (auto& Short : Shorts) { + Short.msg_hdr.msg_iov = &ShortVector; + Short.msg_hdr.msg_iovlen = 1; + } + ArgumentStorage ShortFirst; + uint64_t ShortFirstArgs[6] = {static_cast(Peer), reinterpret_cast(Shorts), 3, 0, 0, 0}; + Show("sendmmsg_short_first_result", Call(Sys::SYSCALL_x64_sendmmsg, ShortFirstArgs, &ShortFirst)); + reinterpret_cast(ShortFirstArgs[1])[0].msg_len = 10; + SendCalls = 0; + Show("sendmmsg_short_first_finish", FinishResult(1, &ShortFirst)); + Show("sendmmsg_short_first_sends", SendCalls); + Show("sendmmsg_short_first_lengths", Shorts[0].msg_len * 0x10000 + Shorts[1].msg_len * 0x100 + Shorts[2].msg_len); + for (auto& Short : Shorts) { + Short.msg_len = 0; + } + ArgumentStorage ShortSecond; + uint64_t ShortSecondArgs[6] = {static_cast(Peer), reinterpret_cast(Shorts), 3, 0, 0, 0}; + Show("sendmmsg_short_second_result", Call(Sys::SYSCALL_x64_sendmmsg, ShortSecondArgs, &ShortSecond)); + Show("sendmmsg_short_second_submitted", ShortSecondArgs[2]); + const int Pinned = ShortSecond.Socket; + Show("sendmmsg_pinned_distinct", Pinned >= 0 && Pinned != Peer); + Show("sendmmsg_pinned_dispatched", ShortSecondArgs[0] == static_cast(Pinned)); + reinterpret_cast(ShortSecondArgs[1])[0].msg_len = 32; + SendCalls = 0; + SendLimit = 5; + SentSocket = -1; + Show("sendmmsg_short_second_finish", FinishResult(1, &ShortSecond)); + SendLimit = ~size_t {}; + Show("sendmmsg_short_second_sends", SendCalls); + Show("sendmmsg_short_second_lengths", Shorts[0].msg_len * 0x10000 + Shorts[1].msg_len * 0x100 + Shorts[2].msg_len); + Show("sendmmsg_pinned_used", SentSocket == Pinned); + Show("sendmmsg_pinned_closed", fcntl(Pinned, F_GETFD) == -1 && errno == EBADF && ShortSecond.Socket == -1); + for (auto& Short : Shorts) { + Short.msg_len = 0; + } + ArgumentStorage ShortFailed; + uint64_t ShortFailedArgs[6] = {static_cast(Peer), reinterpret_cast(Shorts), 3, 0, 0, 0}; + Call(Sys::SYSCALL_x64_sendmmsg, ShortFailedArgs, &ShortFailed); + const int FailedPin = ShortFailed.Socket; + Show("sendmmsg_error_finish", FinishResult(static_cast(-EAGAIN), &ShortFailed)); + Show("sendmmsg_error_closed", FailedPin >= 0 && fcntl(FailedPin, F_GETFD) == -1 && errno == EBADF); + int Pair[2]; + if (socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, Pair) != 0) { + std::fprintf(stderr, "socketpair: %s\n", std::strerror(errno)); + return 1; + } + struct iovec Payloads[3] = {}; + for (int i = 0; i < 3; ++i) { + std::memset(Backing + 2048 + 16 * i, 'A' + i, 4); + Payloads[i] = {reinterpret_cast(Single + 2048 + 16 * i), 4}; + } + auto Drain = [&] { + uint64_t Packed = 0; + unsigned char Data[16]; + while (recv(Pair[1], Data, sizeof(Data), MSG_DONTWAIT) > 0) { + Packed = Packed * 0x100 + Data[0]; + } + return Packed; + }; + auto Dispatch = [&](uint64_t* Args) { + return static_cast(sendmmsg(static_cast(Args[0]), reinterpret_cast(Args[1]), static_cast(Args[2]), 0)); + }; + auto Lengths = [&](struct mmsghdr* Headers) { + return Headers[0].msg_len * 0x10000 + Headers[1].msg_len * 0x100 + Headers[2].msg_len; + }; + PassSend = true; + + struct mmsghdr Real[3] {}; + for (int i = 0; i < 3; ++i) { + Real[i].msg_hdr.msg_iov = &Payloads[i]; + Real[i].msg_hdr.msg_iovlen = 1; + } + DupFailures = 1; + ArgumentStorage Emfile; + uint64_t EmfileArgs[6] = {static_cast(Pair[0]), reinterpret_cast(Real), 3, 0, 0, 0}; + Show("sendmmsg_emfile_result", Call(Sys::SYSCALL_x64_sendmmsg, EmfileArgs, &Emfile)); + Show("sendmmsg_emfile_submitted", EmfileArgs[2]); + Show("sendmmsg_emfile_original", EmfileArgs[0] == static_cast(Pair[0]) && Emfile.Socket == -1 && DupFailures == 0); + Show("sendmmsg_emfile_first_only", Drain()); + Show("sendmmsg_emfile_finish", FinishResult(Dispatch(EmfileArgs), &Emfile)); + Show("sendmmsg_emfile_received", Drain()); + Show("sendmmsg_emfile_lengths", Lengths(Real)); + + const uint64_t ReadOnly = 0x730000000000ULL; + Map(ReadOnly, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t ReadOnlyHost {}; + TranslateRange(ReadOnly, 2 * Page, &ReadOnlyHost); + auto* ReadOnlyHeaders = reinterpret_cast(ReadOnlyHost + Page - sizeof(struct mmsghdr)); + for (int i = 0; i < 3; ++i) { + ReadOnlyHeaders[i] = {}; + ReadOnlyHeaders[i].msg_hdr.msg_iov = &Payloads[i]; + ReadOnlyHeaders[i].msg_hdr.msg_iovlen = 1; + } + Protect(ReadOnly + Page, Page, PROT_READ); + DupFailures = 1; + ArgumentStorage ReadOnlyBatch; + uint64_t ReadOnlyArgs[6] = {static_cast(Pair[0]), ReadOnly + Page - sizeof(struct mmsghdr), 3, 0, 0, 0}; + Show("sendmmsg_emfile_readonly_result", Call(Sys::SYSCALL_x64_sendmmsg, ReadOnlyArgs, &ReadOnlyBatch)); + Show("sendmmsg_emfile_readonly_submitted", ReadOnlyArgs[2]); + Show("sendmmsg_emfile_readonly_finish", FinishResult(Dispatch(ReadOnlyArgs), &ReadOnlyBatch)); + Show("sendmmsg_emfile_readonly_received", Drain()); + Show("sendmmsg_emfile_readonly_lengths", Lengths(ReadOnlyHeaders)); + + DupFailures = 1; + ArgumentStorage ReadOnlyFirst; + uint64_t ReadOnlyFirstArgs[6] = {static_cast(Pair[0]), ReadOnly + Page, 1, 0, 0, 0}; + Show("sendmmsg_emfile_only_result", Call(Sys::SYSCALL_x64_sendmmsg, ReadOnlyFirstArgs, &ReadOnlyFirst)); + Show("sendmmsg_emfile_only_finish", FinishResult(Dispatch(ReadOnlyFirstArgs), &ReadOnlyFirst)); + Show("sendmmsg_emfile_only_received", Drain()); + DupFailures = 0; + + auto* Unreadable = static_cast(mmap(nullptr, Page, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + struct mmsghdr Middle[3] {}; + for (int i = 0; i < 3; ++i) { + Middle[i].msg_hdr.msg_iov = i == 1 ? Unreadable : &Payloads[i]; + Middle[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage MiddleBatch; + uint64_t MiddleArgs[6] = {static_cast(Pair[0]), reinterpret_cast(Middle), 3, 0, 0, 0}; + Show("sendmmsg_unreadable_middle_result", Call(Sys::SYSCALL_x64_sendmmsg, MiddleArgs, &MiddleBatch)); + Show("sendmmsg_unreadable_middle_submitted", MiddleArgs[2]); + Show("sendmmsg_unreadable_middle_queued", MiddleBatch.Messages.size()); + Show("sendmmsg_unreadable_middle_finish", FinishResult(Dispatch(MiddleArgs), &MiddleBatch)); + Show("sendmmsg_unreadable_middle_received", Drain()); + Show("sendmmsg_unreadable_middle_lengths", Lengths(Middle)); + + struct mmsghdr Last[3] {}; + for (int i = 0; i < 3; ++i) { + Last[i].msg_hdr.msg_iov = i == 2 ? Unreadable : &Payloads[i]; + Last[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage LastBatch; + uint64_t LastArgs[6] = {static_cast(Pair[0]), reinterpret_cast(Last), 3, 0, 0, 0}; + Show("sendmmsg_unreadable_last_result", Call(Sys::SYSCALL_x64_sendmmsg, LastArgs, &LastBatch)); + Show("sendmmsg_unreadable_last_submitted", LastArgs[2]); + Show("sendmmsg_unreadable_last_queued", LastBatch.Messages.size()); + const int LastPin = LastBatch.Socket; + Show("sendmmsg_unreadable_last_pinned", LastPin >= 0 && LastArgs[0] == static_cast(LastPin)); + Show("sendmmsg_unreadable_last_finish", FinishResult(Dispatch(LastArgs), &LastBatch)); + Show("sendmmsg_unreadable_last_received", Drain()); + Show("sendmmsg_unreadable_last_lengths", Lengths(Last)); + + struct mmsghdr First[3] {}; + for (int i = 0; i < 3; ++i) { + First[i].msg_hdr.msg_iov = i == 0 ? Unreadable : &Payloads[i]; + First[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage FirstBatch; + uint64_t FirstArgs[6] = {static_cast(Pair[0]), reinterpret_cast(First), 3, 0, 0, 0}; + Show("sendmmsg_unreadable_first_result", Call(Sys::SYSCALL_x64_sendmmsg, FirstArgs, &FirstBatch)); + Show("sendmmsg_unreadable_first_native", FirstArgs[1] == reinterpret_cast(First) && FirstArgs[2] == 3 && FirstBatch.GuestMessages == 0); + Show("sendmmsg_unreadable_first_error", static_cast(sendmmsg(Pair[0], First, 3, 0)) == static_cast(-1) && errno == EFAULT); + Show("sendmmsg_unreadable_first_received", Drain()); + PassSend = false; + + auto* LowVectors = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + char KeptLow[16]; + LowVectors[0] = {KeptLow, sizeof(KeptLow)}; + struct mmsghdr Growing[3] {}; + Growing[0].msg_hdr.msg_iov = &ShortVector; + Growing[0].msg_hdr.msg_iovlen = 1; + for (int i = 1; i < 3; ++i) { + Growing[i].msg_hdr.msg_iov = LowVectors; + Growing[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage Grown; + uint64_t GrownArgs[6] = {static_cast(Peer), reinterpret_cast(Growing), 3, 0, 0, 0}; + Show("sendmmsg_grown_result", Call(Sys::SYSCALL_x64_sendmmsg, GrownArgs, &Grown)); + auto* GrownCopy = reinterpret_cast(GrownArgs[1]); + Show("sendmmsg_grown_private", GrownCopy[1].msg_hdr.msg_iov != LowVectors && GrownCopy[1].msg_hdr.msg_iov[0].iov_base == KeptLow); + GrownCopy[0].msg_len = 32; + SendCalls = 0; + GrowAfterSend = LowVectors; + Show("sendmmsg_grown_finish", FinishResult(1, &Grown)); + GrowAfterSend = nullptr; + Show("sendmmsg_grown_sends", SendCalls); + Show("sendmmsg_grown_lengths", Growing[0].msg_len * 0x10000 + Growing[1].msg_len * 0x100 + Growing[2].msg_len); + for (auto& Message : Growing) { + Message.msg_len = 0; + } + LowVectors[0] = {KeptLow, sizeof(KeptLow)}; + ArgumentStorage Vanished; + uint64_t VanishedArgs[6] = {static_cast(Peer), reinterpret_cast(Growing), 3, 0, 0, 0}; + Show("sendmmsg_vanished_result", Call(Sys::SYSCALL_x64_sendmmsg, VanishedArgs, &Vanished)); + reinterpret_cast(VanishedArgs[1])[0].msg_len = 32; + SendCalls = 0; + SendLimit = 5; + UnmapAfterSend = LowVectors; + Show("sendmmsg_vanished_finish", FinishResult(1, &Vanished)); + SendLimit = ~size_t {}; + Show("sendmmsg_vanished_sends", SendCalls); + Show("sendmmsg_vanished_unmapped", UnmapAfterSend == nullptr && msync(LowVectors, Page, MS_ASYNC) == -1 && errno == ENOMEM); + Show("sendmmsg_vanished_lengths", Growing[0].msg_len * 0x10000 + Growing[1].msg_len * 0x100 + Growing[2].msg_len); + + uint64_t AccessRegs[32] {}; + AccessRegs[0] = 0x10000; + AccessRegs[2] = 0xfffffffeULL; + auto Decode = [&](const char* Name, uint32_t Insn) { + uint64_t Address {}; + uint32_t Size {}; + bool Plain {}; + const bool Known = DecodeAccess(Insn, AccessRegs, &Address, &Size, &Plain); + std::printf("decode_%s_known %x\n", Name, Known); + std::printf("decode_%s_offset %llx\n", Name, static_cast(Address - AccessRegs[0])); + std::printf("decode_%s_size %x\n", Name, Size); + std::printf("decode_%s_plain %x\n", Name, Plain); + }; + Decode("str_x_imm", 0xf9000401); + Decode("ldr_x_pre", 0xf85fcc01); + Decode("ldr_x_post", 0xf8408401); + Decode("stur_x", 0xf81fc001); + Decode("ldr_w_lsl", 0xb8627801); + Decode("ldr_w_sxtw", 0xb862c801); + Decode("ldr_w_uxtw", 0xb8624801); + Decode("ldr_w_reserved", 0xb8620801); + Decode("stp_x", 0xa9010c01); + Decode("ldp_w_negative", 0x297f0c01); + Decode("ldp_q_post", 0xacc10c01); + Decode("str_q", 0x3d800401); + Decode("ld1_four", 0x4c402001); + Decode("st1_post", 0x4c9f7c01); + Decode("ld1_lane", 0x0d409001); + Decode("ld4r", 0x4d60e801); + Decode("ldadd", 0xf8210002); + Decode("ldar", 0xc8dffc01); + Decode("casp", 0x48227c04); + Decode("ldxp", 0xc87f0c01); + Decode("ldapur", 0x995fc001); + Decode("ldraa", 0xf8200400); + + auto* Backings = static_cast(mmap(nullptr, 6 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Backed = reinterpret_cast(Backings); + const uint64_t SeparateGuest = 0x6f0000000000ULL; + const uint64_t Adjacent = 0x6f0000100000ULL; + AddEntry(SeparateGuest, Page, Backed, false, PROT_READ | PROT_WRITE); + AddEntry(SeparateGuest + Page, Page, Backed + 2 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Adjacent, Page, Backed + 4 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Adjacent + Page, Page, Backed + 5 * Page, false, PROT_READ | PROT_WRITE); + std::memset(Backings + Page, 0xee, Page); + uint64_t StoreRegs[32] {}; + StoreRegs[0] = SeparateGuest + Page - 4; + StoreRegs[1] = 0x1122334455667788ULL; + uint64_t SplitAddress {}; + uint32_t SplitSize {}; + bool SplitPlain {}; + DecodeAccess(0xf9000001, StoreRegs, &SplitAddress, &SplitSize, &SplitPlain); + AccessPiece SplitPieces[MaxAccessPieces] {}; + const auto SplitParts = PlanAccessLocked(SplitAddress, SplitSize, SplitPieces); + Show("split_access_parts", SplitParts); + Show("split_access_first", SplitPieces[0].Host - Backed); + Show("split_access_second", SplitPieces[1].Host - Backed); + Show("split_access_sizes", SplitPieces[0].Size * 0x10 + SplitPieces[1].Size); + Show("split_access_guests", (SplitPieces[0].Guest == SeparateGuest + Page - 4) * 0x10 + (SplitPieces[1].Guest == SeparateGuest + Page)); + Show("split_access_contiguous", HostContiguous(SplitPieces, SplitParts)); + Show("split_access_store_reachable", PiecesReachable(SplitPieces, SplitParts, true)); + alignas(16) uint8_t Window[96] {}; + const auto WindowOffset = SplitAddress & 15; + CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true); + std::memcpy(Window + WindowOffset, &StoreRegs[1], sizeof(StoreRegs[1])); + CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, false); + uint32_t SplitWords[3] {}; + std::memcpy(&SplitWords[0], Backings + Page - 4, 4); + std::memcpy(&SplitWords[1], Backings + 2 * Page, 4); + std::memcpy(&SplitWords[2], Backings + Page, 4); + Show("split_store_low", SplitWords[0]); + Show("split_store_high", SplitWords[1]); + Show("split_store_neighbour", SplitWords[2]); + std::memset(Window, 0, sizeof(Window)); + CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true); + uint64_t SplitLoaded {}; + std::memcpy(&SplitLoaded, Window + WindowOffset, sizeof(SplitLoaded)); + Show("split_load_value", SplitLoaded); + SplitPieces[1].Prot = PROT_READ; + Show("split_readonly_store", PiecesReachable(SplitPieces, SplitParts, true)); + Show("split_readonly_load", PiecesReachable(SplitPieces, SplitParts, false)); + SplitPieces[1].Prot = PROT_NONE; + Show("split_none_load", PiecesReachable(SplitPieces, SplitParts, false)); + AccessPiece EdgePieces[MaxAccessPieces] {}; + Show("split_unmapped_parts", PlanAccessLocked(SeparateGuest + 2 * Page - 4, 8, EdgePieces)); + Show("split_inside_parts", PlanAccessLocked(SeparateGuest + 16, 64, EdgePieces)); + Show("split_inside_host", EdgePieces[0].Host - Backed); + AccessPiece JoinedPieces[MaxAccessPieces] {}; + const auto JoinedParts = PlanAccessLocked(Adjacent + Page - 4, 8, JoinedPieces); + Show("joined_access_parts", JoinedParts); + Show("joined_access_contiguous", HostContiguous(JoinedPieces, JoinedParts)); + Show("joined_access_delta", JoinedPieces[0].Host - (Adjacent + Page - 4) == Backed + 4 * Page - Adjacent); + + uint64_t OrderedRegs[32] {}; + Show("ordered_load_parts", EmulateOrdered(0xd9400001, SplitPieces, SplitParts, OrderedRegs)); + Show("ordered_load_value", OrderedRegs[1]); + OrderedRegs[1] = 0xa1a2a3a4b5b6b7b8ULL; + Show("ordered_store_parts", EmulateOrdered(0xd9000001, SplitPieces, SplitParts, OrderedRegs)); + uint32_t OrderedWords[2] {}; + std::memcpy(&OrderedWords[0], Backings + Page - 4, 4); + std::memcpy(&OrderedWords[1], Backings + 2 * Page, 4); + Show("ordered_store_low", OrderedWords[0]); + Show("ordered_store_high", OrderedWords[1]); + AccessPiece WordPieces[MaxAccessPieces] {}; + const auto WordParts = PlanAccessLocked(SeparateGuest + Page - 2, 4, WordPieces); + OrderedRegs[1] = 0; + Show("ordered_signed_parts", EmulateOrdered(0x99800001, WordPieces, WordParts, OrderedRegs) == WordParts && WordParts == 2); + Show("ordered_signed_value", OrderedRegs[1]); + mprotect(Backings + 2 * Page, Page, PROT_NONE); + OrderedRegs[1] = 0x77; + Show("ordered_fault_parts", EmulateOrdered(0xd9400001, SplitPieces, SplitParts, OrderedRegs)); + Show("ordered_fault_untouched", OrderedRegs[1]); + Show("gather_fault_piece", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true)); + Show("scatter_fault_piece", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, false)); + mprotect(Backings + 2 * Page, Page, PROT_READ | PROT_WRITE); + Show("gather_whole", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true)); + Show("probe_instruction", ProbeInstruction(16)); + Show("probe_instruction_low", ProbeInstruction(2)); + auto OrderedKind = [](uint32_t Insn) { return static_cast(IsOrderedAccess(Insn)); }; + Show("ordered_kinds", OrderedKind(0xd9400001) << 20 | OrderedKind(0x99800001) << 16 | OrderedKind(0xc8dffc01) << 12 | OrderedKind(0xc89ffc01) << 8 | + OrderedKind(0xf8bfc001) << 4 | OrderedKind(0xf9400001)); + Show("ordered_atomics", OrderedKind(0xf8210002) << 8 | OrderedKind(0x48227c04) << 4 | OrderedKind(0xc87f0c01)); + auto WriteKind = [](uint32_t Insn) { return static_cast(IsWrite(Insn)); }; + Show("write_loads", WriteKind(0xb9800001) << 20 | WriteKind(0x99800001) << 16 | WriteKind(0x39c00001) << 12 | WriteKind(0xf9400001) << 8 | + WriteKind(0x3dc00401) << 4 | WriteKind(0xd9400001)); + Show("write_stores", WriteKind(0xf9000001) << 12 | WriteKind(0xd9000001) << 8 | WriteKind(0x3d800401) << 4 | WriteKind(0x39000001)); + Show("extend_signed_half_w", ExtendOrdered(0x59c00001, 0x8001)); + Show("extend_signed_half_x", ExtendOrdered(0x59800001, 0x8001)); + Show("extend_unsigned_byte", ExtendOrdered(0x19400001, 0x80)); + Show("extend_ldar", ExtendOrdered(0x889ffc01 | (1U << 22), 0x80000000)); + + TestHold Held {}; + std::atomic WriterIn {0}; + uint64_t HoldResults[4] {}; + std::thread Holder([&] { + { + MappingHold Hold {Held}; + Hold.Keep(); + } + HoldResults[0] = Held.Held; + std::thread Writer([&] { + std::unique_lock Exclusive {FEX::HLE::_SyscallHandler->VMATracking.Mutex}; + WriterIn = 1; + }); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + HoldResults[1] = WriterIn.load(); + ReleaseMappings(Held); + Writer.join(); + HoldResults[2] = WriterIn.load() * 0x10 + Held.Held; + { + MappingHold Hold {Held}; + } + HoldResults[3] = ExclusiveFromAnotherThread() * 0x10 + Held.Held; + }); + Holder.join(); + Show("hold_kept_held", HoldResults[0]); + Show("hold_blocks_writer", HoldResults[1]); + Show("hold_released", HoldResults[2]); + Show("hold_scoped", HoldResults[3]); + + struct sigaction TrapAction {}; + TrapAction.sa_sigaction = CountTrap; + TrapAction.sa_flags = SA_SIGINFO; + sigaction(SIGTRAP, &TrapAction, nullptr); + uint64_t DeferResults[12] {}; + std::thread Deferring([&] { + siginfo_t User {}; + User.si_signo = SIGTRAP; + User.si_code = SI_QUEUE; + User.si_pid = getpid(); + User.si_uid = getuid(); + User.si_value.sival_int = 0x1234; + siginfo_t Breakpoint {}; + Breakpoint.si_signo = SIGTRAP; + Breakpoint.si_code = TRAP_BRKPT; + TestHold Deferred {}; + DeferResults[0] = DeferWhileHeld(Deferred, SIGTRAP, &User); + { + MappingHold Hold {Deferred}; + Hold.Keep(); + } + sigset_t Current; + pthread_sigmask(SIG_BLOCK, nullptr, &Current); + DeferResults[1] = sigismember(&Current, SIGTRAP) * 0x100 + sigismember(&Current, SIGSEGV) * 0x10 + sigismember(&Current, SIGILL); + DeferResults[2] = DeferWhileHeld(Deferred, SIGTRAP, &User) * 0x100 + DeferWhileHeld(Deferred, SIGTRAP, &Breakpoint) * 0x10 + + DeferWhileHeld(Deferred, SIGILL, &User); + DeferResults[3] = TrapsSeen.load(); + DeferResults[4] = ReleaseMappings(Deferred); + DeferResults[5] = TrapsSeen.load() * 0x10 + Deferred.Held; + DeferResults[6] = ExclusiveFromAnotherThread(); + sigset_t Trap; + sigemptyset(&Trap); + sigaddset(&Trap, SIGTRAP); + pthread_sigmask(SIG_UNBLOCK, &Trap, nullptr); + DeferResults[7] = TrapsSeen.load(); + DeferResults[8] = static_cast(TrapCode.load()) * 0x10000ULL + static_cast(TrapValue.load()); + { + MappingHold Hold {Deferred}; + User.si_value.sival_int = 0x5678; + DeferWhileHeld(Deferred, SIGTRAP, &User); + } + DeferResults[9] = TrapsSeen.load(); + pthread_sigmask(SIG_BLOCK, nullptr, &Current); + DeferResults[10] = sigismember(&Current, SIGTRAP); + pthread_sigmask(SIG_UNBLOCK, &Trap, nullptr); + DeferResults[11] = TrapsSeen.load() * 0x10000ULL + static_cast(TrapValue.load()); + }); + Deferring.join(); + Show("defer_unheld", DeferResults[0]); + Show("defer_held_mask", DeferResults[1]); + Show("defer_kinds", DeferResults[2]); + Show("defer_not_run_while_held", DeferResults[3]); + Show("defer_requeued", DeferResults[4]); + Show("defer_after_release", DeferResults[5]); + Show("defer_lock_free", DeferResults[6]); + Show("defer_delivered", DeferResults[7]); + Show("defer_info", DeferResults[8]); + Show("defer_scoped_pending", DeferResults[9]); + Show("defer_scoped_blocked", DeferResults[10]); + Show("defer_scoped_delivered", DeferResults[11]); + const uint64_t Delivering = 0x730000000000ULL; + Map(Delivering, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + static int TrapsBefore; + TrapsBefore = TrapsSeen.load(); + FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] { + siginfo_t User {}; + User.si_signo = SIGTRAP; + User.si_code = SI_QUEUE; + User.si_pid = getpid(); + User.si_uid = getuid(); + DeferWhileHeld(FEX::HLE::TestThread.HighMemoryTrap.Mappings, SIGTRAP, &User); + }; + const uint32_t DeliveringValue = 0x5a; + Show("guest_store_deferred_result", CopyToGuest(Delivering, &DeliveringValue, sizeof(DeliveringValue))); + Show("guest_store_deferred_delivered", TrapsSeen.load() - TrapsBefore); + sigset_t AfterStore; + pthread_sigmask(SIG_BLOCK, nullptr, &AfterStore); + Show("guest_store_deferred_unblocked", !sigismember(&AfterStore, SIGTRAP)); + Unmap(Delivering, Page); + return 0; +} +""" + + +def added_lines(text, path): + lines = [] + inside = False + for line in text.splitlines(): + if line.startswith("diff --git "): + inside = line.endswith(" b/" + path) + continue + if inside and line.startswith("+") and not line.startswith("+++"): + lines.append(line[1:]) + return lines + + +def block(lines, signature): + start = next(i for i, line in enumerate(lines) if line.lstrip().startswith(signature)) + indent = lines[start][: len(lines[start]) - len(lines[start].lstrip())] + if lines[start].rstrip().endswith(";"): + return lines[start] + end = next(i for i in range(start + 1, len(lines)) if lines[i] in (indent + "}", indent + "};")) + return "\n".join(lines[start:end + 1]) + + +def span(lines, first, stop): + start = next(i for i, line in enumerate(lines) if line.startswith(first)) + end = next(i for i in range(start + 1, len(lines)) if lines[i].startswith(stop)) + return "\n".join(lines[start:end]) + + +def syscall_enum(code): + entries = [] + for name in sorted(set(re.findall(r"SYSCALL_x64_(\w+)", code))): + kernel = KERNEL_NAMES.get(name, name) + fallback = NEWER_SYSCALLS.get(name) + if fallback is None: + entries.append(f"SYSCALL_x64_{name} = __NR_{kernel},") + else: + entries.append(f"#ifdef __NR_{kernel}\nSYSCALL_x64_{name} = __NR_{kernel},\n#else\nSYSCALL_x64_{name} = {fallback},\n#endif") + return "enum Syscalls_x64 : int {\n" + "\n".join(entries) + "\n};" + + +def harness(): + text = PATCH.read_text() + source = added_lines(text, SOURCE) + header = [line for line in added_lines(text, HEADER) if not line.startswith(("#pragma", "#include