mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
63
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db0ee92d50 | ||
|
|
f9eeef44ed | ||
|
|
eeb10e02fd | ||
|
|
e935263ccb | ||
|
|
673675b45e | ||
|
|
153c873898 | ||
|
|
cec2e4ed70 | ||
|
|
affb0da37f | ||
|
|
8cf1e60cc2 | ||
|
|
e3faee459f | ||
|
|
20df8b1858 | ||
|
|
4ab9635ceb | ||
|
|
34fff40b56 | ||
|
|
5d05c36033 | ||
|
|
ec281db0d1 | ||
|
|
1a7a116939 | ||
|
|
c7cd7c18e6 | ||
|
|
80dbec57d7 | ||
|
|
e04e38b44c | ||
|
|
90c7dece92 | ||
|
|
6d78142a67 | ||
|
|
5cd6fe8864 | ||
|
|
186bae8f3e | ||
|
|
3bb22dc92b | ||
|
|
f3f410059d | ||
|
|
6e7908ed81 | ||
|
|
9ca6fa064e | ||
|
|
aab15f3146 | ||
|
|
11af78340a | ||
|
|
2c95ebd22d | ||
|
|
7ce53ccbed | ||
|
|
1b4aaf8a3b | ||
|
|
4793d1df62 | ||
|
|
9dfbc05933 | ||
|
|
8ec6e646d9 | ||
|
|
41412450fd | ||
|
|
bf772b7c55 | ||
|
|
29b04b66eb | ||
|
|
044c8ee475 | ||
|
|
ca499115ac | ||
|
|
d7898360e3 | ||
|
|
fcd197934a | ||
|
|
768661928e | ||
|
|
18cd1cf07f | ||
|
|
41f15b03bb | ||
|
|
5c887bfc59 | ||
|
|
430d777c5c | ||
|
|
5f129fb4db | ||
|
|
7404fba5a3 | ||
|
|
54ca518553 | ||
|
|
72c8b8426d | ||
|
|
6dc3d01674 | ||
|
|
df2cfa40b3 | ||
|
|
e101a78791 | ||
|
|
aaa9fb129c | ||
|
|
23d7e639ca | ||
|
|
4ef23ed0e9 | ||
|
|
ff35cce127 | ||
|
|
0951b602b7 | ||
|
|
57055be6fb | ||
|
|
c6743730aa | ||
|
|
780c5658d0 | ||
|
|
a9e8a01bb6 |
No files matched your search
@@ -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
|
||||
|
||||
+10
-108
@@ -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,89 +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. 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")"
|
||||
ln -sfn "$(cd "$jars" && pwd)" "$m2"
|
||||
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: ../robolectric-jars
|
||||
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
|
||||
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
|
||||
|
||||
# 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: ../robolectric-jars
|
||||
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
|
||||
@@ -872,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
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
name: Unit tests
|
||||
run-name: ${{ github.event_name == 'pull_request' && format('unit tests for pr {0} on {1} against {2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.base.sha) || format('unit tests for {0} on {1}', github.ref_name, github.sha) }}
|
||||
|
||||
# Runs beside Build APK rather than inside it, so a test build is published as soon as the APK compiles.
|
||||
# Build validation folds this workflow's result into the "Build APK" commit status, and Release APKs requires it.
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
paths-ignore:
|
||||
- '**/*.md'
|
||||
- 'LICENSE'
|
||||
- '.gitignore'
|
||||
- 'docs/**'
|
||||
- '.github/ISSUE_TEMPLATE/**'
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
types: [ opened, synchronize, reopened, ready_for_review ]
|
||||
paths-ignore:
|
||||
- '**/*.md'
|
||||
- 'LICENSE'
|
||||
- '.gitignore'
|
||||
- 'docs/**'
|
||||
- '.github/ISSUE_TEMPLATE/**'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
concurrency:
|
||||
group: unit-tests-${{ github.event.pull_request.number || (github.event_name == 'push' && 'main') || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' }}
|
||||
|
||||
jobs:
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
sparse-checkout: |
|
||||
/*
|
||||
!/docs/releases/media/
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Merge the pinned APK base
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config user.name "ci"
|
||||
git config user.email "ci@users.noreply.github.com"
|
||||
git fetch --no-tags origin "$PR_BASE_SHA"
|
||||
git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true
|
||||
git merge --no-ff --no-edit FETCH_HEAD || { echo "::error::the pull request conflicts with main; Build APK lists the files"; exit 1; }
|
||||
|
||||
- name: Check out MaliBridge
|
||||
run: git submodule update --init external/MaliBridge
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
cache-read-only: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
|
||||
cache-cleanup: ${{ github.event_name == 'pull_request' && 'never' || 'on-success' }}
|
||||
|
||||
- name: Resolve the pinned Android NDK
|
||||
run: bash tools/ci/resolve-ndk.sh
|
||||
|
||||
- name: Set the APK build label
|
||||
id: build-label
|
||||
env:
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
BUILD_REF: ${{ github.ref_name }}
|
||||
BUILD_SHA: ${{ github.sha }}
|
||||
run: bash tools/ci/build-label.sh
|
||||
|
||||
- name: Resolve the Robolectric version
|
||||
id: robolectric
|
||||
run: |
|
||||
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
|
||||
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
|
||||
# The cache path sits beside the workspace because runner homes are at different depths from it, and
|
||||
# actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects
|
||||
# "..". Runners that keep their own ~/.m2 skip the cache.
|
||||
- name: Place Robolectric's Android jars beside the workspace
|
||||
id: robolectric-jars
|
||||
run: |
|
||||
set -euo pipefail
|
||||
jars="$GITHUB_WORKSPACE/../robolectric-jars"
|
||||
m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented"
|
||||
if [ -d "$m2" ] && [ ! -L "$m2" ]; then
|
||||
echo "cache=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
mkdir -p "$jars" "$(dirname "$m2")"
|
||||
jars=$(cd "$jars" && pwd)
|
||||
ln -sfn "$jars" "$m2"
|
||||
echo "path=$jars" >> "$GITHUB_OUTPUT"
|
||||
echo "cache=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Restore Robolectric's Android jars
|
||||
id: robolectric-cache
|
||||
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: ${{ steps.robolectric-jars.outputs.path }}
|
||||
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
|
||||
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
|
||||
- name: Count the restored Robolectric jars
|
||||
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||
run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV"
|
||||
- name: Unit tests
|
||||
id: unit-tests
|
||||
env:
|
||||
DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }}
|
||||
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
|
||||
run: |
|
||||
set -o pipefail
|
||||
mkdir -p app/build
|
||||
log=app/build/unit-tests.log
|
||||
attempt_log=app/build/unit-tests-attempt.log
|
||||
: > "$log"
|
||||
mirror=()
|
||||
central='https://(repo1\.maven\.org|repo\.maven\.apache\.org)/maven2/org/robolectric/'
|
||||
gradle_error='((Caused by: )?org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: |>[[:space:]]+)?'
|
||||
java_error='((Caused by: )?java\.io\.IOException: )?'
|
||||
# A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next.
|
||||
for wait in 60 180 0; do
|
||||
status=0
|
||||
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PskipRust=true -PunitTestsOnly=true -PndkVersion="$NDK_VERSION" "${mirror[@]}" 2>&1 | tee "$attempt_log" || status=$?
|
||||
cat "$attempt_log" >> "$log"
|
||||
if [ "$status" = 0 ] || [ "$wait" = 0 ]; then
|
||||
exit "$status"
|
||||
fi
|
||||
if [ "${#mirror[@]}" = 0 ] && grep -qE \
|
||||
-e "^[[:space:]]*${gradle_error}Could not (GET|HEAD) '?${central}[^'[:space:]]+'?\. Received status code 429([[:space:]]|$)" \
|
||||
-e "^[[:space:]]*${java_error}Server returned HTTP response code: 429 for URL: ${central}[^[:space:]]+" "$attempt_log"; then
|
||||
mirror=(-ProbolectricMavenMirror=https://maven-central.storage-download.googleapis.com/maven2)
|
||||
echo "::notice::Maven Central rate limited Robolectric. Retrying unit tests with the Google Cloud mirror." | tee -a "$log"
|
||||
continue
|
||||
fi
|
||||
if ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://(repo\.maven\.apache\.org|repo1\.maven\.org)/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://(repo\.maven\.apache\.org|repo1\.maven\.org)/)' "$attempt_log"; then
|
||||
exit "$status"
|
||||
fi
|
||||
echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" | tee -a "$log"
|
||||
sleep "$wait"
|
||||
done
|
||||
|
||||
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
|
||||
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
|
||||
- name: Save Robolectric's Android jars
|
||||
id: robolectric-jars-final
|
||||
if: always() && steps.robolectric-jars.outputs.cache == 'true'
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import glob, os, zipfile
|
||||
root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars')
|
||||
for f in glob.glob(os.path.join(root, '**', '*'), recursive=True):
|
||||
if not os.path.isfile(f):
|
||||
continue
|
||||
try:
|
||||
ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None
|
||||
except Exception:
|
||||
ok = False
|
||||
if not ok:
|
||||
os.remove(f)
|
||||
PY
|
||||
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
|
||||
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
|
||||
- name: Store Robolectric's Android jars
|
||||
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: ${{ steps.robolectric-jars.outputs.path }}
|
||||
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
|
||||
|
||||
- name: Upload unit test diagnostics
|
||||
id: unit-test-diagnostics
|
||||
if: always() && steps.unit-tests.outcome != 'skipped'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: unit-test-results
|
||||
path: |
|
||||
app/build/unit-tests.log
|
||||
app/build/test-results/testReleaseUnitTest/
|
||||
app/build/reports/tests/testReleaseUnitTest/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
overwrite: true
|
||||
@@ -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 '<class>'` and `python3 -m unittest discover -s tools/tests -p 'test_<area>*.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/<job-id>/logs`, or `gh run download <run> -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/<job-id>/logs`, or `gh run download <run> -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 <run> --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`.
|
||||
|
||||
|
||||
+8
-1
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<com.droiddeck.launcher.frontend.Li
|
||||
@DroidDeckPreviews @Composable private fun SettingsPreview() = Launcher("setup")
|
||||
@DroidDeckPreviews @Composable private fun RuntimeMissingPreview() = Launcher("setup", ready = false)
|
||||
|
||||
/** [content] over a stand-in wallpaper as the frost shows it, with see-through [cards] or solid ones. */
|
||||
@Composable
|
||||
private fun Frosted(transparency: Int = FROST_WALLPAPER_DEFAULT, cards: Boolean = false, cardTransparency: Int = FROST_DEFAULT, content: @Composable () -> 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<PreviewCase> = 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) },
|
||||
|
||||
@@ -33,6 +33,9 @@
|
||||
<uses-permission android:name="android.permission.REORDER_TASKS" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
<!-- Granted only with adb shell pm grant; lets the agent turn Wireless debugging on where Settings hides it (Quest). -->
|
||||
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
@@ -274,6 +277,17 @@
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".agent.AgentChatActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity="${applicationId}.agentchat"
|
||||
android:resizeableActivity="true"
|
||||
android:theme="@style/AppTheme"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density">
|
||||
<layout android:defaultWidth="720dp" android:defaultHeight="800dp" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".agent.AgentStartActivity"
|
||||
android:exported="true"
|
||||
@@ -414,5 +428,133 @@
|
||||
android:name="backend:com.google.android.datatransport.cct.CctBackendFactory"
|
||||
tools:node="remove" />
|
||||
</service>
|
||||
<service android:name=".runtime.GuestWorker0" android:exported="false" android:process=":g0" />
|
||||
<service android:name=".runtime.GuestWorker1" android:exported="false" android:process=":g1" />
|
||||
<service android:name=".runtime.GuestWorker2" android:exported="false" android:process=":g2" />
|
||||
<service android:name=".runtime.GuestWorker3" android:exported="false" android:process=":g3" />
|
||||
<service android:name=".runtime.GuestWorker4" android:exported="false" android:process=":g4" />
|
||||
<service android:name=".runtime.GuestWorker5" android:exported="false" android:process=":g5" />
|
||||
<service android:name=".runtime.GuestWorker6" android:exported="false" android:process=":g6" />
|
||||
<service android:name=".runtime.GuestWorker7" android:exported="false" android:process=":g7" />
|
||||
<service android:name=".runtime.GuestWorker8" android:exported="false" android:process=":g8" />
|
||||
<service android:name=".runtime.GuestWorker9" android:exported="false" android:process=":g9" />
|
||||
<service android:name=".runtime.GuestWorker10" android:exported="false" android:process=":g10" />
|
||||
<service android:name=".runtime.GuestWorker11" android:exported="false" android:process=":g11" />
|
||||
<service android:name=".runtime.GuestWorker12" android:exported="false" android:process=":g12" />
|
||||
<service android:name=".runtime.GuestWorker13" android:exported="false" android:process=":g13" />
|
||||
<service android:name=".runtime.GuestWorker14" android:exported="false" android:process=":g14" />
|
||||
<service android:name=".runtime.GuestWorker15" android:exported="false" android:process=":g15" />
|
||||
<service android:name=".runtime.GuestWorker16" android:exported="false" android:process=":g16" />
|
||||
<service android:name=".runtime.GuestWorker17" android:exported="false" android:process=":g17" />
|
||||
<service android:name=".runtime.GuestWorker18" android:exported="false" android:process=":g18" />
|
||||
<service android:name=".runtime.GuestWorker19" android:exported="false" android:process=":g19" />
|
||||
<service android:name=".runtime.GuestWorker20" android:exported="false" android:process=":g20" />
|
||||
<service android:name=".runtime.GuestWorker21" android:exported="false" android:process=":g21" />
|
||||
<service android:name=".runtime.GuestWorker22" android:exported="false" android:process=":g22" />
|
||||
<service android:name=".runtime.GuestWorker23" android:exported="false" android:process=":g23" />
|
||||
<service android:name=".runtime.GuestWorker24" android:exported="false" android:process=":g24" />
|
||||
<service android:name=".runtime.GuestWorker25" android:exported="false" android:process=":g25" />
|
||||
<service android:name=".runtime.GuestWorker26" android:exported="false" android:process=":g26" />
|
||||
<service android:name=".runtime.GuestWorker27" android:exported="false" android:process=":g27" />
|
||||
<service android:name=".runtime.GuestWorker28" android:exported="false" android:process=":g28" />
|
||||
<service android:name=".runtime.GuestWorker29" android:exported="false" android:process=":g29" />
|
||||
<service android:name=".runtime.GuestWorker30" android:exported="false" android:process=":g30" />
|
||||
<service android:name=".runtime.GuestWorker31" android:exported="false" android:process=":g31" />
|
||||
<service android:name=".runtime.GuestWorker32" android:exported="false" android:process=":g32" />
|
||||
<service android:name=".runtime.GuestWorker33" android:exported="false" android:process=":g33" />
|
||||
<service android:name=".runtime.GuestWorker34" android:exported="false" android:process=":g34" />
|
||||
<service android:name=".runtime.GuestWorker35" android:exported="false" android:process=":g35" />
|
||||
<service android:name=".runtime.GuestWorker36" android:exported="false" android:process=":g36" />
|
||||
<service android:name=".runtime.GuestWorker37" android:exported="false" android:process=":g37" />
|
||||
<service android:name=".runtime.GuestWorker38" android:exported="false" android:process=":g38" />
|
||||
<service android:name=".runtime.GuestWorker39" android:exported="false" android:process=":g39" />
|
||||
<service android:name=".runtime.GuestWorker40" android:exported="false" android:process=":g40" />
|
||||
<service android:name=".runtime.GuestWorker41" android:exported="false" android:process=":g41" />
|
||||
<service android:name=".runtime.GuestWorker42" android:exported="false" android:process=":g42" />
|
||||
<service android:name=".runtime.GuestWorker43" android:exported="false" android:process=":g43" />
|
||||
<service android:name=".runtime.GuestWorker44" android:exported="false" android:process=":g44" />
|
||||
<service android:name=".runtime.GuestWorker45" android:exported="false" android:process=":g45" />
|
||||
<service android:name=".runtime.GuestWorker46" android:exported="false" android:process=":g46" />
|
||||
<service android:name=".runtime.GuestWorker47" android:exported="false" android:process=":g47" />
|
||||
<service android:name=".runtime.GuestWorker48" android:exported="false" android:process=":g48" />
|
||||
<service android:name=".runtime.GuestWorker49" android:exported="false" android:process=":g49" />
|
||||
<service android:name=".runtime.GuestWorker50" android:exported="false" android:process=":g50" />
|
||||
<service android:name=".runtime.GuestWorker51" android:exported="false" android:process=":g51" />
|
||||
<service android:name=".runtime.GuestWorker52" android:exported="false" android:process=":g52" />
|
||||
<service android:name=".runtime.GuestWorker53" android:exported="false" android:process=":g53" />
|
||||
<service android:name=".runtime.GuestWorker54" android:exported="false" android:process=":g54" />
|
||||
<service android:name=".runtime.GuestWorker55" android:exported="false" android:process=":g55" />
|
||||
<service android:name=".runtime.GuestWorker56" android:exported="false" android:process=":g56" />
|
||||
<service android:name=".runtime.GuestWorker57" android:exported="false" android:process=":g57" />
|
||||
<service android:name=".runtime.GuestWorker58" android:exported="false" android:process=":g58" />
|
||||
<service android:name=".runtime.GuestWorker59" android:exported="false" android:process=":g59" />
|
||||
<service android:name=".runtime.GuestWorker60" android:exported="false" android:process=":g60" />
|
||||
<service android:name=".runtime.GuestWorker61" android:exported="false" android:process=":g61" />
|
||||
<service android:name=".runtime.GuestWorker62" android:exported="false" android:process=":g62" />
|
||||
<service android:name=".runtime.GuestWorker63" android:exported="false" android:process=":g63" />
|
||||
<service android:name=".runtime.GuestWorker64" android:exported="false" android:process=":g64" />
|
||||
<service android:name=".runtime.GuestWorker65" android:exported="false" android:process=":g65" />
|
||||
<service android:name=".runtime.GuestWorker66" android:exported="false" android:process=":g66" />
|
||||
<service android:name=".runtime.GuestWorker67" android:exported="false" android:process=":g67" />
|
||||
<service android:name=".runtime.GuestWorker68" android:exported="false" android:process=":g68" />
|
||||
<service android:name=".runtime.GuestWorker69" android:exported="false" android:process=":g69" />
|
||||
<service android:name=".runtime.GuestWorker70" android:exported="false" android:process=":g70" />
|
||||
<service android:name=".runtime.GuestWorker71" android:exported="false" android:process=":g71" />
|
||||
<service android:name=".runtime.GuestWorker72" android:exported="false" android:process=":g72" />
|
||||
<service android:name=".runtime.GuestWorker73" android:exported="false" android:process=":g73" />
|
||||
<service android:name=".runtime.GuestWorker74" android:exported="false" android:process=":g74" />
|
||||
<service android:name=".runtime.GuestWorker75" android:exported="false" android:process=":g75" />
|
||||
<service android:name=".runtime.GuestWorker76" android:exported="false" android:process=":g76" />
|
||||
<service android:name=".runtime.GuestWorker77" android:exported="false" android:process=":g77" />
|
||||
<service android:name=".runtime.GuestWorker78" android:exported="false" android:process=":g78" />
|
||||
<service android:name=".runtime.GuestWorker79" android:exported="false" android:process=":g79" />
|
||||
<service android:name=".runtime.GuestWorker80" android:exported="false" android:process=":g80" />
|
||||
<service android:name=".runtime.GuestWorker81" android:exported="false" android:process=":g81" />
|
||||
<service android:name=".runtime.GuestWorker82" android:exported="false" android:process=":g82" />
|
||||
<service android:name=".runtime.GuestWorker83" android:exported="false" android:process=":g83" />
|
||||
<service android:name=".runtime.GuestWorker84" android:exported="false" android:process=":g84" />
|
||||
<service android:name=".runtime.GuestWorker85" android:exported="false" android:process=":g85" />
|
||||
<service android:name=".runtime.GuestWorker86" android:exported="false" android:process=":g86" />
|
||||
<service android:name=".runtime.GuestWorker87" android:exported="false" android:process=":g87" />
|
||||
<service android:name=".runtime.GuestWorker88" android:exported="false" android:process=":g88" />
|
||||
<service android:name=".runtime.GuestWorker89" android:exported="false" android:process=":g89" />
|
||||
<service android:name=".runtime.GuestWorker90" android:exported="false" android:process=":g90" />
|
||||
<service android:name=".runtime.GuestWorker91" android:exported="false" android:process=":g91" />
|
||||
<service android:name=".runtime.GuestWorker92" android:exported="false" android:process=":g92" />
|
||||
<service android:name=".runtime.GuestWorker93" android:exported="false" android:process=":g93" />
|
||||
<service android:name=".runtime.GuestWorker94" android:exported="false" android:process=":g94" />
|
||||
<service android:name=".runtime.GuestWorker95" android:exported="false" android:process=":g95" />
|
||||
<service android:name=".runtime.GuestWorker96" android:exported="false" android:process=":g96" />
|
||||
<service android:name=".runtime.GuestWorker97" android:exported="false" android:process=":g97" />
|
||||
<service android:name=".runtime.GuestWorker98" android:exported="false" android:process=":g98" />
|
||||
<service android:name=".runtime.GuestWorker99" android:exported="false" android:process=":g99" />
|
||||
<service android:name=".runtime.GuestWorker100" android:exported="false" android:process=":g100" />
|
||||
<service android:name=".runtime.GuestWorker101" android:exported="false" android:process=":g101" />
|
||||
<service android:name=".runtime.GuestWorker102" android:exported="false" android:process=":g102" />
|
||||
<service android:name=".runtime.GuestWorker103" android:exported="false" android:process=":g103" />
|
||||
<service android:name=".runtime.GuestWorker104" android:exported="false" android:process=":g104" />
|
||||
<service android:name=".runtime.GuestWorker105" android:exported="false" android:process=":g105" />
|
||||
<service android:name=".runtime.GuestWorker106" android:exported="false" android:process=":g106" />
|
||||
<service android:name=".runtime.GuestWorker107" android:exported="false" android:process=":g107" />
|
||||
<service android:name=".runtime.GuestWorker108" android:exported="false" android:process=":g108" />
|
||||
<service android:name=".runtime.GuestWorker109" android:exported="false" android:process=":g109" />
|
||||
<service android:name=".runtime.GuestWorker110" android:exported="false" android:process=":g110" />
|
||||
<service android:name=".runtime.GuestWorker111" android:exported="false" android:process=":g111" />
|
||||
<service android:name=".runtime.GuestWorker112" android:exported="false" android:process=":g112" />
|
||||
<service android:name=".runtime.GuestWorker113" android:exported="false" android:process=":g113" />
|
||||
<service android:name=".runtime.GuestWorker114" android:exported="false" android:process=":g114" />
|
||||
<service android:name=".runtime.GuestWorker115" android:exported="false" android:process=":g115" />
|
||||
<service android:name=".runtime.GuestWorker116" android:exported="false" android:process=":g116" />
|
||||
<service android:name=".runtime.GuestWorker117" android:exported="false" android:process=":g117" />
|
||||
<service android:name=".runtime.GuestWorker118" android:exported="false" android:process=":g118" />
|
||||
<service android:name=".runtime.GuestWorker119" android:exported="false" android:process=":g119" />
|
||||
<service android:name=".runtime.GuestWorker120" android:exported="false" android:process=":g120" />
|
||||
<service android:name=".runtime.GuestWorker121" android:exported="false" android:process=":g121" />
|
||||
<service android:name=".runtime.GuestWorker122" android:exported="false" android:process=":g122" />
|
||||
<service android:name=".runtime.GuestWorker123" android:exported="false" android:process=":g123" />
|
||||
<service android:name=".runtime.GuestWorker124" android:exported="false" android:process=":g124" />
|
||||
<service android:name=".runtime.GuestWorker125" android:exported="false" android:process=":g125" />
|
||||
<service android:name=".runtime.GuestWorker126" android:exported="false" android:process=":g126" />
|
||||
<service android:name=".runtime.GuestWorker127" android:exported="false" android:process=":g127" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -4130,6 +4130,24 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) {
|
||||
return read_input(fd, buf, count);
|
||||
}
|
||||
|
||||
// glibc's fortify failure; bionic (DroidDeck-Bionic preloads this library into its Wine processes) has no
|
||||
// __chk_fail, and a library naming it there cannot be loaded, which stops every Wine program from starting.
|
||||
#if defined(__BIONIC__)
|
||||
[[noreturn]] static void fakeinput_chk_fail(void) { abort(); }
|
||||
#else
|
||||
extern "C" [[noreturn]] void __chk_fail(void);
|
||||
[[noreturn]] static void fakeinput_chk_fail(void) { __chk_fail(); }
|
||||
#endif
|
||||
|
||||
/* Programs built with _FORTIFY_SOURCE (Flatpak runtimes among them) call these instead of read, poll
|
||||
* and ppoll, and glibc's versions go straight to the kernel. */
|
||||
EXPORT ssize_t __read_chk(int fd, void *buf, size_t count, size_t buflen) {
|
||||
static auto next_read_chk = reinterpret_cast<ssize_t (*)(int, void *, size_t, size_t)>(dlsym(RTLD_NEXT, "__read_chk"));
|
||||
if (count > buflen) fakeinput_chk_fail();
|
||||
if (next_read_chk && !is_fake_input_fd(fd)) return next_read_chk(fd, buf, count, buflen);
|
||||
return read_input(fd, buf, count);
|
||||
}
|
||||
|
||||
EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) {
|
||||
if (!is_fake_input_fd(fd)) return syscall(SYS_readv, fd, iov, iovcnt);
|
||||
if (iovcnt < 0 || iovcnt > IOV_MAX) {
|
||||
@@ -4378,6 +4396,17 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
||||
return my_ppoll(fds, nfds, timeout, sigmask);
|
||||
}
|
||||
|
||||
EXPORT int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fdslen) {
|
||||
if (fdslen / sizeof(*fds) < nfds) fakeinput_chk_fail();
|
||||
return poll(fds, nfds, timeout);
|
||||
}
|
||||
|
||||
EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout,
|
||||
const sigset_t *sigmask, size_t fdslen) {
|
||||
if (fdslen / sizeof(*fds) < nfds) fakeinput_chk_fail();
|
||||
return ppoll(fds, nfds, timeout, sigmask);
|
||||
}
|
||||
|
||||
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
||||
fd_set *exceptfds, struct timeval *timeout) {
|
||||
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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_{};
|
||||
|
||||
@@ -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<VkBuffer> flowUbo; std::vector<VkDeviceMemory> flowUboMem; std::vector<void*> 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<VkDescriptorSet> 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<VkDescriptorSet> 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
#pragma once
|
||||
#include "vk_dispatch.hpp"
|
||||
#include "config.hpp"
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
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<ScratchState> scratch_;
|
||||
|
||||
Pipe pLuma_, pDown_, pFlow_, pFlowM4_, pExpand_, pExpandM4_, pSynth_;
|
||||
Pipe pGmReduce_, pGmPrewarp_;
|
||||
|
||||
@@ -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<VkBuffer> flowUbo; std::vector<VkDeviceMemory> flowUboMem; std::vector<void*> 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<VkDescriptorSet> 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<VkDescriptorSet> 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<ScratchState>()) {}
|
||||
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<FrameGen::Img>& pyrA, std::vector<FrameGen::Img>& 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<FrameGen::Img>& pyrA, std::vector<FrameGen::Img>& 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;
|
||||
|
||||
@@ -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)
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <jni.h>
|
||||
#include <EGL/egl.h>
|
||||
#include <GLES3/gl3.h>
|
||||
#include <android/bitmap.h>
|
||||
#include <android/log.h>
|
||||
#include <android_native_app_glue.h>
|
||||
#include <time.h>
|
||||
@@ -22,10 +23,14 @@
|
||||
#include <cerrno>
|
||||
#include <cstddef>
|
||||
#include <ctime>
|
||||
#include <pthread.h>
|
||||
#include <algorithm>
|
||||
#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<XrSwapchainImageOpenGLESKHR> 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<const char *> 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<PFN_xrVoidFunction *>(&setPerformance_));
|
||||
if (XR_FAILED(result)) setPerformance_ = nullptr;
|
||||
}
|
||||
if (surfaceSupported_ && XR_FAILED(xrGetInstanceProcAddr(instance_, "xrCreateSwapchainAndroidSurfaceKHR",
|
||||
reinterpret_cast<PFN_xrVoidFunction *>(&createSurfaceSwapchain_)))) {
|
||||
createSurfaceSwapchain_ = nullptr;
|
||||
surfaceSupported_ = false;
|
||||
}
|
||||
if (timespecSupported_) check(xrGetInstanceProcAddr(instance_, "xrConvertTimeToTimespecTimeKHR",
|
||||
reinterpret_cast<PFN_xrVoidFunction *>(&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<XrSwapchainImageBaseHeader *>(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<XrSwapchainImageBaseHeader *>(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<XrCompositionLayerQuad> quads;
|
||||
std::vector<XrCompositionLayerImageLayoutFB> 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<XrCompositionLayerBaseHeader *>(&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<const XrCompositionLayerBaseHeader *> layers;
|
||||
if (draw) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
|
||||
for (auto &quad : quads) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&quad));
|
||||
if (overlay) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&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<XrCompositionLayerQuad> &quads, std::vector<XrCompositionLayerImageLayoutFB> &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<XrHapticBaseHeader *>(&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(); }
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#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");
|
||||
@@ -0,0 +1,229 @@
|
||||
#pragma once
|
||||
#include <GLES3/gl3.h>
|
||||
#include <openxr/openxr.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#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<void *>(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;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -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)); }
|
||||
|
||||
@@ -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
|
||||
};
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "droiddeck-ahb-v1-server-protocol.h"
|
||||
#include <android/hardware_buffer.h>
|
||||
#include <errno.h>
|
||||
#include <linux/sync_file.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <pthread.h>
|
||||
@@ -145,6 +146,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 +159,7 @@ static void handle_released(uint64_t id, int fd) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ab->fence_src) return;
|
||||
send_deferred_release(ab);
|
||||
maybe_free(ab);
|
||||
}
|
||||
@@ -197,15 +205,19 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
|
||||
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) {
|
||||
} else {
|
||||
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));
|
||||
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");
|
||||
}
|
||||
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
|
||||
int r;
|
||||
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
|
||||
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;
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <stdarg.h>
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/timerfd.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/sysmacros.h>
|
||||
@@ -242,6 +243,10 @@ struct surface {
|
||||
enum surface_role role;
|
||||
struct wl_resource *idle_buffer;
|
||||
struct wl_listener idle_buffer_destroy;
|
||||
struct surface_state *waiting;
|
||||
struct wl_event_source *waiting_source, *waiting_timer;
|
||||
int waiting_fd;
|
||||
int64_t waiting_since_ns;
|
||||
uint32_t *idle_px;
|
||||
int idle_w, idle_h;
|
||||
struct wl_resource *xdg_surface, *xdg_toplevel;
|
||||
@@ -373,6 +378,8 @@ static struct {
|
||||
unsigned copy_scenes;
|
||||
unsigned releases, releases_held;
|
||||
int64_t release_ns, release_max_ns;
|
||||
unsigned commit_waits, commit_wait_limits;
|
||||
int64_t commit_wait_ns, commit_wait_max_ns;
|
||||
} g_perf;
|
||||
|
||||
static void schedule_render(void);
|
||||
@@ -846,6 +853,55 @@ static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) {
|
||||
s->pending_buffer = NULL;
|
||||
}
|
||||
|
||||
struct surface_state {
|
||||
struct wl_resource *buffer;
|
||||
struct wl_listener buffer_destroy;
|
||||
int attach;
|
||||
int src_set, dst_set, opaque_set;
|
||||
float src[4];
|
||||
int dst[2], opaque[4];
|
||||
struct damage_list damage_buf, damage_local;
|
||||
struct wl_list frames, feedback;
|
||||
};
|
||||
|
||||
static void on_state_buffer_destroyed(struct wl_listener *l, void *data) {
|
||||
struct surface_state *st = wl_container_of(l, st, buffer_destroy);
|
||||
wl_list_remove(&st->buffer_destroy.link);
|
||||
wl_list_init(&st->buffer_destroy.link);
|
||||
st->buffer = NULL;
|
||||
st->attach = 0;
|
||||
}
|
||||
|
||||
static void surface_state_take(struct surface *s, struct surface_state *st) {
|
||||
st->attach = s->pending_attach;
|
||||
st->buffer = s->pending_buffer;
|
||||
wl_list_init(&st->buffer_destroy.link);
|
||||
if (st->buffer) {
|
||||
wl_list_remove(&s->pending_buffer_destroy.link);
|
||||
wl_list_init(&s->pending_buffer_destroy.link);
|
||||
st->buffer_destroy.notify = on_state_buffer_destroyed;
|
||||
wl_resource_add_destroy_listener(st->buffer, &st->buffer_destroy);
|
||||
}
|
||||
s->pending_buffer = NULL;
|
||||
s->pending_attach = 0;
|
||||
st->src_set = s->pending_src_set;
|
||||
memcpy(st->src, s->pending_src, sizeof(st->src));
|
||||
st->dst_set = s->pending_dst_set;
|
||||
memcpy(st->dst, s->pending_dst, sizeof(st->dst));
|
||||
st->opaque_set = s->pending_opaque_set;
|
||||
memcpy(st->opaque, s->pending_opaque, sizeof(st->opaque));
|
||||
s->pending_src_set = s->pending_dst_set = s->pending_opaque_set = 0;
|
||||
st->damage_buf = s->pending_damage_buf;
|
||||
st->damage_local = s->pending_damage_local;
|
||||
s->pending_damage_buf.n = s->pending_damage_local.n = 0;
|
||||
wl_list_init(&st->frames);
|
||||
wl_list_insert_list(&st->frames, &s->pending_frames);
|
||||
wl_list_init(&s->pending_frames);
|
||||
wl_list_init(&st->feedback);
|
||||
wl_list_insert_list(&st->feedback, &s->pending_feedback);
|
||||
wl_list_init(&s->pending_feedback);
|
||||
}
|
||||
|
||||
static void fire_frames(struct wl_list *frames) {
|
||||
struct wl_resource *cb, *tmp;
|
||||
uint32_t t;
|
||||
@@ -1363,35 +1419,23 @@ static void surface_drop_idle(struct surface *s) {
|
||||
if (buffer) send_buffer_release(buffer);
|
||||
}
|
||||
|
||||
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
static void surface_state_apply(struct surface *s, struct surface_state *st) {
|
||||
struct surface *child;
|
||||
|
||||
if (s->xdg_toplevel && !s->toplevel_committed) {
|
||||
s->toplevel_committed = 1;
|
||||
send_toplevel_configure(s);
|
||||
if (st->src_set) {
|
||||
s->src_set = st->src[2] > 0;
|
||||
memcpy(s->src, st->src, sizeof(s->src));
|
||||
}
|
||||
if (st->dst_set) {
|
||||
s->dst_set = st->dst[0] > 0;
|
||||
memcpy(s->dst, st->dst, sizeof(s->dst));
|
||||
}
|
||||
if (st->opaque_set) memcpy(s->opaque, st->opaque, sizeof(s->opaque));
|
||||
|
||||
if (s->pending_src_set) {
|
||||
s->src_set = s->pending_src[2] > 0;
|
||||
memcpy(s->src, s->pending_src, sizeof(s->src));
|
||||
s->pending_src_set = 0;
|
||||
}
|
||||
if (s->pending_dst_set) {
|
||||
s->dst_set = s->pending_dst[0] > 0;
|
||||
memcpy(s->dst, s->pending_dst, sizeof(s->dst));
|
||||
s->pending_dst_set = 0;
|
||||
}
|
||||
if (s->pending_opaque_set) {
|
||||
memcpy(s->opaque, s->pending_opaque, sizeof(s->opaque));
|
||||
s->pending_opaque_set = 0;
|
||||
}
|
||||
|
||||
s->damage_buf = s->pending_damage_buf;
|
||||
s->damage_local = s->pending_damage_local;
|
||||
s->pending_damage_buf.n = s->pending_damage_local.n = 0;
|
||||
if (s->pending_attach) {
|
||||
struct wl_resource *buffer = s->pending_buffer;
|
||||
s->damage_buf = st->damage_buf;
|
||||
s->damage_local = st->damage_local;
|
||||
if (st->attach) {
|
||||
struct wl_resource *buffer = st->buffer;
|
||||
struct dmabuf_buffer *db = get_dmabuf(buffer);
|
||||
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
|
||||
uint8_t pixel[4];
|
||||
@@ -1400,12 +1444,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
if (!buffer) g_pace.null_attaches++;
|
||||
else if (!db) s->last_dmabuf = NULL;
|
||||
|
||||
if (buffer) {
|
||||
wl_list_remove(&s->pending_buffer_destroy.link);
|
||||
wl_list_init(&s->pending_buffer_destroy.link);
|
||||
}
|
||||
s->pending_buffer = NULL;
|
||||
s->pending_attach = 0;
|
||||
wl_list_remove(&st->buffer_destroy.link);
|
||||
wl_list_init(&st->buffer_destroy.link);
|
||||
st->buffer = NULL;
|
||||
st->attach = 0;
|
||||
|
||||
surface_drop_idle(s);
|
||||
buf_trace_attach(buffer);
|
||||
@@ -1442,10 +1484,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
}
|
||||
}
|
||||
|
||||
wl_list_insert_list(s->frames.prev, &s->pending_frames);
|
||||
wl_list_init(&s->pending_frames);
|
||||
wl_list_insert_list(s->feedback.prev, &s->pending_feedback);
|
||||
wl_list_init(&s->pending_feedback);
|
||||
wl_list_insert_list(s->frames.prev, &st->frames);
|
||||
wl_list_init(&st->frames);
|
||||
wl_list_insert_list(s->feedback.prev, &st->feedback);
|
||||
wl_list_init(&st->feedback);
|
||||
constraints_surface_commit(s);
|
||||
droiddeck_color_commit(s->resource);
|
||||
|
||||
@@ -1455,6 +1497,186 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
}
|
||||
schedule_render();
|
||||
}
|
||||
|
||||
#define COMMIT_WAIT_LIMIT_MS 1000
|
||||
|
||||
static struct surface *g_zero_copy_shown, *g_unwaited;
|
||||
|
||||
static int state_unfinished_fd(const struct surface *s, const struct surface_state *st, int *unwaited) {
|
||||
struct dmabuf_buffer *db = st->attach ? get_dmabuf(st->buffer) : NULL;
|
||||
int fd = -1;
|
||||
*unwaited = 0;
|
||||
for (int i = 0; db && fd < 0 && i < db->n_planes; i++) {
|
||||
if (db->fd[i] < 0) continue;
|
||||
struct pollfd p = {.fd = db->fd[i], .events = POLLIN};
|
||||
int r;
|
||||
do { r = poll(&p, 1, 0); } while (r < 0 && errno == EINTR);
|
||||
if (r == 0) fd = db->fd[i];
|
||||
}
|
||||
if (fd >= 0 && s == g_zero_copy_shown && ahb_swapchain_has_ahb(db)) {
|
||||
*unwaited = 1;
|
||||
return -1;
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
static void settle_unwaited(void) {
|
||||
struct surface *s = g_unwaited;
|
||||
if (!s) return;
|
||||
g_unwaited = NULL;
|
||||
struct dmabuf_buffer *db = s->dmabuf_buf;
|
||||
const int64_t deadline = now_ns() + 100000000LL;
|
||||
for (int i = 0; db && i < db->n_planes; i++) {
|
||||
if (db->fd[i] < 0) continue;
|
||||
struct pollfd p = {.fd = db->fd[i], .events = POLLIN};
|
||||
for (;;) {
|
||||
const int64_t left = deadline - now_ns();
|
||||
const int r = poll(&p, 1, left > 0 ? (int)((left + 999999) / 1000000) : 0);
|
||||
if (r >= 0 || errno != EINTR || left <= 0) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void surface_state_discard(struct surface_state *st) {
|
||||
struct wl_resource *cb, *tmp;
|
||||
wl_list_remove(&st->buffer_destroy.link);
|
||||
wl_resource_for_each_safe(cb, tmp, &st->frames) wl_resource_destroy(cb);
|
||||
feedback_discard_all(&st->feedback);
|
||||
free(st);
|
||||
}
|
||||
|
||||
static void surface_state_merge(struct surface_state *older, struct surface_state *newer) {
|
||||
if (older->attach && !newer->attach) {
|
||||
newer->attach = 1;
|
||||
newer->buffer = older->buffer;
|
||||
wl_list_remove(&older->buffer_destroy.link);
|
||||
wl_list_init(&older->buffer_destroy.link);
|
||||
if (newer->buffer) {
|
||||
newer->buffer_destroy.notify = on_state_buffer_destroyed;
|
||||
wl_resource_add_destroy_listener(newer->buffer, &newer->buffer_destroy);
|
||||
}
|
||||
wl_list_insert_list(&newer->feedback, &older->feedback);
|
||||
wl_list_init(&older->feedback);
|
||||
} else if (older->attach) {
|
||||
if (older->buffer && older->buffer != newer->buffer) send_buffer_release(older->buffer);
|
||||
g_pace.replaced += feedback_discard_all(&older->feedback);
|
||||
}
|
||||
if (older->src_set && !newer->src_set) {
|
||||
newer->src_set = 1;
|
||||
memcpy(newer->src, older->src, sizeof(newer->src));
|
||||
}
|
||||
if (older->dst_set && !newer->dst_set) {
|
||||
newer->dst_set = 1;
|
||||
memcpy(newer->dst, older->dst, sizeof(newer->dst));
|
||||
}
|
||||
if (older->opaque_set && !newer->opaque_set) {
|
||||
newer->opaque_set = 1;
|
||||
memcpy(newer->opaque, older->opaque, sizeof(newer->opaque));
|
||||
}
|
||||
for (int i = 0; i < older->damage_buf.n; i++)
|
||||
note_damage(&newer->damage_buf, older->damage_buf.r[i][0], older->damage_buf.r[i][1],
|
||||
older->damage_buf.r[i][2], older->damage_buf.r[i][3]);
|
||||
for (int i = 0; i < older->damage_local.n; i++)
|
||||
note_damage(&newer->damage_local, older->damage_local.r[i][0], older->damage_local.r[i][1],
|
||||
older->damage_local.r[i][2], older->damage_local.r[i][3]);
|
||||
wl_list_insert_list(&newer->frames, &older->frames);
|
||||
wl_list_init(&older->frames);
|
||||
surface_state_discard(older);
|
||||
}
|
||||
|
||||
static void surface_wait_stop(struct surface *s) {
|
||||
if (s->waiting_source) wl_event_source_remove(s->waiting_source);
|
||||
if (s->waiting_timer) wl_event_source_remove(s->waiting_timer);
|
||||
if (s->waiting_fd >= 0) close(s->waiting_fd);
|
||||
s->waiting_source = s->waiting_timer = NULL;
|
||||
s->waiting_fd = -1;
|
||||
}
|
||||
|
||||
static void surface_wait_end(struct surface *s, int over_limit) {
|
||||
struct surface_state *st = s->waiting;
|
||||
if (!st) return;
|
||||
surface_wait_stop(s);
|
||||
s->waiting = NULL;
|
||||
const int64_t waited = now_ns() - s->waiting_since_ns;
|
||||
g_perf.commit_waits++;
|
||||
g_perf.commit_wait_ns += waited;
|
||||
if (waited > g_perf.commit_wait_max_ns) g_perf.commit_wait_max_ns = waited;
|
||||
if (over_limit) g_perf.commit_wait_limits++;
|
||||
if (st->attach && g_unwaited == s) g_unwaited = NULL;
|
||||
surface_state_apply(s, st);
|
||||
free(st);
|
||||
}
|
||||
|
||||
static int on_commit_ready(int fd, uint32_t mask, void *data) {
|
||||
surface_wait_end(data, 0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int on_commit_wait_limit(void *data) {
|
||||
static int said;
|
||||
if (!said) {
|
||||
said = 1;
|
||||
droiddeck_log("compositor", "a client's GPU writes ran past %d ms; its frame is shown as it is", COMMIT_WAIT_LIMIT_MS);
|
||||
}
|
||||
surface_wait_end(data, 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int surface_wait_start(struct surface *s, int fd, int timeout_ms) {
|
||||
struct wl_event_loop *loop = wl_display_get_event_loop(g_display);
|
||||
s->waiting_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
|
||||
if (s->waiting_fd >= 0) {
|
||||
s->waiting_source = wl_event_loop_add_fd(loop, s->waiting_fd, WL_EVENT_READABLE, on_commit_ready, s);
|
||||
s->waiting_timer = wl_event_loop_add_timer(loop, on_commit_wait_limit, s);
|
||||
}
|
||||
if (!s->waiting_source || !s->waiting_timer ||
|
||||
wl_event_source_timer_update(s->waiting_timer, timeout_ms) != 0) {
|
||||
surface_wait_stop(s);
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
|
||||
if (s->xdg_toplevel && !s->toplevel_committed) {
|
||||
s->toplevel_committed = 1;
|
||||
send_toplevel_configure(s);
|
||||
}
|
||||
struct surface_state *st = calloc(1, sizeof(*st));
|
||||
if (!st) {
|
||||
struct surface_state now;
|
||||
surface_state_take(s, &now);
|
||||
surface_state_apply(s, &now);
|
||||
return;
|
||||
}
|
||||
surface_state_take(s, st);
|
||||
const int was_waiting = s->waiting != NULL;
|
||||
if (was_waiting) {
|
||||
surface_wait_stop(s);
|
||||
surface_state_merge(s->waiting, st);
|
||||
s->waiting = NULL;
|
||||
}
|
||||
int unwaited;
|
||||
const int fd = state_unfinished_fd(s, st, &unwaited);
|
||||
if (!was_waiting) s->waiting_since_ns = now_ns();
|
||||
const int64_t left_ms = COMMIT_WAIT_LIMIT_MS - (now_ns() - s->waiting_since_ns) / 1000000;
|
||||
if (fd >= 0 && left_ms > 0 && surface_wait_start(s, fd, (int)left_ms) == 0) {
|
||||
s->waiting = st;
|
||||
return;
|
||||
}
|
||||
const int attaches = st->attach;
|
||||
if (was_waiting) {
|
||||
s->waiting = st;
|
||||
surface_wait_end(s, fd >= 0 && left_ms <= 0);
|
||||
} else {
|
||||
surface_state_apply(s, st);
|
||||
free(st);
|
||||
}
|
||||
if (unwaited) g_unwaited = s;
|
||||
else if (attaches && g_unwaited == s) g_unwaited = NULL;
|
||||
}
|
||||
static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {}
|
||||
static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {}
|
||||
static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r,
|
||||
@@ -1516,6 +1738,13 @@ static void surface_resource_destroy(struct wl_resource *r) {
|
||||
child->parent = NULL;
|
||||
}
|
||||
if (s->pending_buffer) wl_list_remove(&s->pending_buffer_destroy.link);
|
||||
if (s->waiting) {
|
||||
surface_wait_stop(s);
|
||||
surface_state_discard(s->waiting);
|
||||
s->waiting = NULL;
|
||||
}
|
||||
if (g_zero_copy_shown == s) g_zero_copy_shown = NULL;
|
||||
if (g_unwaited == s) g_unwaited = NULL;
|
||||
pending_releases_forget_surface(s);
|
||||
drop_dmabuf(s, 0);
|
||||
ahb_swapchain_surface_gone(s);
|
||||
@@ -1579,6 +1808,7 @@ static void compositor_create_surface(struct wl_client *c, struct wl_resource *r
|
||||
wl_list_init(&s->child_link);
|
||||
wl_list_init(&s->toplevel_link);
|
||||
wl_list_init(&s->pending_buffer_destroy.link);
|
||||
s->waiting_fd = -1;
|
||||
wl_list_init(&s->idle_buffer_destroy.link);
|
||||
wl_list_insert(&g_surfaces, &s->link);
|
||||
wl_resource_set_implementation(s->resource, &surface_impl, s, surface_resource_destroy);
|
||||
@@ -2043,6 +2273,69 @@ static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t
|
||||
|
||||
struct draw_list { struct vkp_draw *d; int n, cap; };
|
||||
|
||||
#define ZERO_COPY_FALLBACK_SIGNATURES 32u
|
||||
enum zero_copy_fallback_reason {
|
||||
ZERO_COPY_NO_SURFACE_BUFFER = 1,
|
||||
ZERO_COPY_NO_GRALLOC_AHB = 2,
|
||||
ZERO_COPY_AHB_PRESENT_FAILED = 3
|
||||
};
|
||||
struct zero_copy_fallback_signature {
|
||||
uint32_t reason, format, stride, offset;
|
||||
int width, height;
|
||||
uint64_t modifier;
|
||||
};
|
||||
static struct zero_copy_fallback_signature g_zero_copy_fallbacks[ZERO_COPY_FALLBACK_SIGNATURES];
|
||||
static uint32_t g_zero_copy_fallback_count;
|
||||
static int g_zero_copy_fallback_limit_logged;
|
||||
|
||||
static int zero_copy_fallback_should_log(const struct dmabuf_buffer *b, uint32_t reason) {
|
||||
const struct zero_copy_fallback_signature key = {
|
||||
.reason = reason, .format = b ? b->format : 0,
|
||||
.stride = b && b->n_planes ? b->stride[0] : 0,
|
||||
.offset = b && b->n_planes ? b->offset[0] : 0,
|
||||
.width = b ? b->width : 0, .height = b ? b->height : 0,
|
||||
.modifier = b ? b->modifier : 0};
|
||||
for (uint32_t i = 0; i < g_zero_copy_fallback_count; i++) {
|
||||
const struct zero_copy_fallback_signature *seen = &g_zero_copy_fallbacks[i];
|
||||
if (seen->reason == key.reason && seen->format == key.format && seen->stride == key.stride &&
|
||||
seen->offset == key.offset && seen->width == key.width && seen->height == key.height &&
|
||||
seen->modifier == key.modifier)
|
||||
return 0;
|
||||
}
|
||||
if (g_zero_copy_fallback_count >= ZERO_COPY_FALLBACK_SIGNATURES) {
|
||||
if (!g_zero_copy_fallback_limit_logged) {
|
||||
g_zero_copy_fallback_limit_logged = 1;
|
||||
droiddeck_log("layer", "zero-copy: further fallback diagnostics suppressed after %u distinct buffer signatures",
|
||||
ZERO_COPY_FALLBACK_SIGNATURES);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
g_zero_copy_fallbacks[g_zero_copy_fallback_count++] = key;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void note_zero_copy_fallback(struct surface *s, const struct dmabuf_buffer *b, uint32_t reason,
|
||||
int scene_w, int scene_h, int present_result) {
|
||||
if (!zero_copy_fallback_should_log(b, reason)) return;
|
||||
char name[160] = "unknown surface";
|
||||
if (s) describe(s, name, sizeof(name));
|
||||
if (reason == ZERO_COPY_NO_SURFACE_BUFFER) {
|
||||
droiddeck_log("layer", "zero-copy: layer candidate %s has no associated Wayland surface buffer; using the layer-copy path",
|
||||
name);
|
||||
} else {
|
||||
droiddeck_log("layer", "zero-copy: %s buffer %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx %s; "
|
||||
"scene %dx%d will use the layer-copy path (direct-present result %d)",
|
||||
name, b->format & 0xff, (b->format >> 8) & 0xff, (b->format >> 16) & 0xff,
|
||||
(b->format >> 24) & 0xff, b->width, b->height,
|
||||
b->n_planes ? b->stride[0] : 0, b->n_planes ? b->offset[0] : 0,
|
||||
(unsigned long long)b->modifier,
|
||||
reason == ZERO_COPY_NO_GRALLOC_AHB
|
||||
? "has no registered gralloc AHardwareBuffer"
|
||||
: "has a registered gralloc AHardwareBuffer but direct presentation failed",
|
||||
scene_w, scene_h, present_result);
|
||||
}
|
||||
}
|
||||
|
||||
static int add_cursor(struct draw_list *dl, int scene_w);
|
||||
|
||||
static struct vkp_image *surface_image(struct surface *s) {
|
||||
@@ -2162,17 +2455,53 @@ static int black_fill_below(const struct draw_list *dl, int n) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
#define LAYER_CANDIDATE_DIAGNOSTICS 32u
|
||||
static unsigned g_layer_candidate_diag_count;
|
||||
static int g_layer_candidate_diag_limit;
|
||||
|
||||
static void note_layer_candidate_skip(const struct vkp_draw *d, int index, int reason,
|
||||
int scene_w, int scene_h) {
|
||||
static int seen[LAYER_CANDIDATE_DIAGNOSTICS][8];
|
||||
const int key[8] = {index, reason, scene_w, scene_h, d->dx, d->dy, d->dw, d->dh};
|
||||
for (unsigned i = 0; i < g_layer_candidate_diag_count; i++)
|
||||
if (!memcmp(seen[i], key, sizeof(key))) return;
|
||||
if (g_layer_candidate_diag_count >= LAYER_CANDIDATE_DIAGNOSTICS) {
|
||||
if (!g_layer_candidate_diag_limit++) droiddeck_log("layer", "zero-copy: further candidate-rejection details suppressed after %u signatures",
|
||||
LAYER_CANDIDATE_DIAGNOSTICS);
|
||||
return;
|
||||
}
|
||||
memcpy(seen[g_layer_candidate_diag_count++], key, sizeof(key));
|
||||
const char *why = reason == 1 ? "translucent draw" :
|
||||
reason == 2 ? "image is not DMA-BUF" :
|
||||
reason == 3 ? "source rectangle is outside/invalid" :
|
||||
reason == 4 ? "draw rectangle is outside scene or invalid" :
|
||||
"not fullscreen and no black backing below";
|
||||
droiddeck_log("layer", "zero-copy: candidate draw %d rejected: %s; scene %dx%d, dst %dx%d at %d,%d, src %.2f,%.2f %.2fx%.2f, image %dx%d",
|
||||
index, why, scene_w, scene_h, d->dw, d->dh, d->dx, d->dy,
|
||||
d->sx, d->sy, d->sw, d->sh, vkp_image_width(d->img), vkp_image_height(d->img));
|
||||
}
|
||||
|
||||
static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) {
|
||||
for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) {
|
||||
const struct vkp_draw *d = &dl->d[i];
|
||||
if (d->blend) continue;
|
||||
if (!vkp_image_is_dmabuf(d->img)) continue;
|
||||
if (d->blend) { note_layer_candidate_skip(d, i, 1, scene_w, scene_h); continue; }
|
||||
if (!vkp_image_is_dmabuf(d->img)) { note_layer_candidate_skip(d, i, 2, scene_w, scene_h); continue; }
|
||||
if (d->sx < 0 || d->sy < 0 || d->sw < 1.0f || d->sh < 1.0f ||
|
||||
d->sx + d->sw >= vkp_image_width(d->img) + 1.0f ||
|
||||
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) continue;
|
||||
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) {
|
||||
note_layer_candidate_skip(d, i, 3, scene_w, scene_h);
|
||||
continue;
|
||||
}
|
||||
if (d->dx == 0 && d->dy == 0 && d->dw == scene_w && d->dh == scene_h) return i;
|
||||
if (d->dx < 0 || d->dy < 0 || d->dw <= 0 || d->dh <= 0 || d->dx + d->dw > scene_w ||
|
||||
d->dy + d->dh > scene_h || !black_fill_below(dl, i)) continue;
|
||||
d->dy + d->dh > scene_h) {
|
||||
note_layer_candidate_skip(d, i, 4, scene_w, scene_h);
|
||||
continue;
|
||||
}
|
||||
if (!black_fill_below(dl, i)) {
|
||||
note_layer_candidate_skip(d, i, 5, scene_w, scene_h);
|
||||
continue;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
@@ -2193,6 +2522,56 @@ static void note_copy_scene(const struct draw_list *dl, int scene_w, int scene_h
|
||||
vkp_image_is_dmabuf(t->img) ? "GPU" : "memory", t->blend ? ", translucent" : "");
|
||||
}
|
||||
|
||||
static struct surface *surface_for_image(const struct vkp_image *img);
|
||||
|
||||
static void note_layer_candidate_rejected(const struct draw_list *dl, int scene_w, int scene_h) {
|
||||
static int seen[32][14];
|
||||
static unsigned seen_count;
|
||||
static int limit_logged;
|
||||
static time_t window_start;
|
||||
struct timespec now_ts;
|
||||
const struct vkp_draw *a = dl->n > 0 ? &dl->d[dl->n - 1] : NULL;
|
||||
const struct vkp_draw *b = dl->n > 1 ? &dl->d[dl->n - 2] : NULL;
|
||||
struct surface *sa = a ? surface_for_image(a->img) : NULL;
|
||||
struct surface *sb = b ? surface_for_image(b->img) : NULL;
|
||||
const int signature[14] = {
|
||||
dl->n, scene_w, scene_h,
|
||||
a ? a->dw : 0, a ? a->dh : 0,
|
||||
a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0,
|
||||
a ? vkp_image_is_dmabuf(a->img) : 0, a ? a->blend : 0, sa && sa->dmabuf_buf ? 1 : 0,
|
||||
b ? b->dw : 0, b ? b->dh : 0, b ? vkp_image_is_dmabuf(b->img) : 0, sb && sb->dmabuf_buf ? 1 : 0
|
||||
};
|
||||
clock_gettime(CLOCK_MONOTONIC, &now_ts);
|
||||
if (!window_start || now_ts.tv_sec - window_start >= 30) {
|
||||
seen_count = 0;
|
||||
limit_logged = 0;
|
||||
window_start = now_ts.tv_sec;
|
||||
}
|
||||
for (unsigned i = 0; i < seen_count; i++)
|
||||
if (!memcmp(signature, seen[i], sizeof(signature))) return;
|
||||
if (seen_count >= 32) {
|
||||
if (!limit_logged++) droiddeck_log("layer", "zero-copy: further fullscreen-candidate rejection details suppressed after 32 signatures in 30 seconds");
|
||||
return;
|
||||
}
|
||||
memcpy(seen[seen_count++], signature, sizeof(signature));
|
||||
char below[48];
|
||||
if (b)
|
||||
snprintf(below, sizeof(below), "%s %dx%d",
|
||||
vkp_image_is_dmabuf(b->img) ? "DMA-BUF" : "non-DMA-BUF", b->dw, b->dh);
|
||||
else
|
||||
snprintf(below, sizeof(below), "none");
|
||||
droiddeck_log("layer", "zero-copy: no eligible fullscreen DMA-BUF layer candidate: scene %dx%d, %d draws; "
|
||||
"top draw %dx%d at %d,%d image %dx%d %s%s surface=%s dmabuf=%s; "
|
||||
"draw below %s",
|
||||
scene_w, scene_h, dl->n, a ? a->dw : 0, a ? a->dh : 0, a ? a->dx : 0, a ? a->dy : 0,
|
||||
a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0,
|
||||
a && vkp_image_is_dmabuf(a->img) ? "DMA-BUF" : "non-DMA-BUF",
|
||||
a && a->blend ? " blended" : "",
|
||||
sa ? "associated" : "unassociated",
|
||||
sa && sa->dmabuf_buf ? "yes" : "no",
|
||||
below);
|
||||
}
|
||||
|
||||
static struct surface *surface_for_image(const struct vkp_image *img) {
|
||||
struct surface *s;
|
||||
wl_list_for_each(s, &g_surfaces, link)
|
||||
@@ -2201,16 +2580,56 @@ static struct surface *surface_for_image(const struct vkp_image *img) {
|
||||
}
|
||||
|
||||
static struct surface *ahb_layer_only_candidate(int scene_w, int scene_h) {
|
||||
static struct {
|
||||
const struct surface *surface;
|
||||
int reason, scene_w, scene_h, w, h, buf_w, buf_h, x, y, src_set, dst_set, children;
|
||||
} seen[32];
|
||||
static unsigned seen_count;
|
||||
static int limit_logged;
|
||||
struct surface *s;
|
||||
int w, h;
|
||||
int w = 0, h = 0, reason = 0;
|
||||
if (wl_list_empty(&g_toplevels)) return NULL;
|
||||
s = wl_container_of(g_toplevels.prev, s, toplevel_link);
|
||||
if (!s->dmabuf_buf || s->dmabuf_buf->img || !ahb_swapchain_has_ahb(s->dmabuf_buf)) return NULL;
|
||||
if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) return NULL;
|
||||
if (!wl_list_empty(&s->children)) return NULL;
|
||||
if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) return NULL;
|
||||
if (!s->dmabuf_buf) reason = 1;
|
||||
else if (s->dmabuf_buf->img) reason = 2;
|
||||
else if (!ahb_swapchain_has_ahb(s->dmabuf_buf)) reason = 3;
|
||||
else if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) reason = 4;
|
||||
else if (!wl_list_empty(&s->children)) reason = 5;
|
||||
else if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) reason = 6;
|
||||
surface_size(s, &w, &h);
|
||||
if (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h) return NULL;
|
||||
if (!reason && (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h)) reason = 7;
|
||||
if (reason) {
|
||||
int found = 0;
|
||||
for (unsigned i = 0; i < seen_count; i++) {
|
||||
if (seen[i].surface == s && seen[i].reason == reason && seen[i].scene_w == scene_w &&
|
||||
seen[i].scene_h == scene_h && seen[i].w == w && seen[i].h == h &&
|
||||
seen[i].buf_w == s->buf_w && seen[i].buf_h == s->buf_h && seen[i].x == s->x &&
|
||||
seen[i].y == s->y && seen[i].src_set == s->src_set && seen[i].dst_set == s->dst_set &&
|
||||
seen[i].children == !wl_list_empty(&s->children)) { found = 1; break; }
|
||||
}
|
||||
if (!found && seen_count < 32) {
|
||||
seen[seen_count].surface = s; seen[seen_count].reason = reason;
|
||||
seen[seen_count].scene_w = scene_w; seen[seen_count].scene_h = scene_h;
|
||||
seen[seen_count].w = w; seen[seen_count].h = h; seen[seen_count].buf_w = s->buf_w; seen[seen_count].buf_h = s->buf_h;
|
||||
seen[seen_count].x = s->x; seen[seen_count].y = s->y; seen[seen_count].src_set = s->src_set;
|
||||
seen[seen_count].dst_set = s->dst_set; seen[seen_count].children = !wl_list_empty(&s->children);
|
||||
seen_count++;
|
||||
const char *why = reason == 1 ? "no DMA-BUF buffer" :
|
||||
reason == 2 ? "buffer is already importable by Vulkan" :
|
||||
reason == 3 ? "no registered gralloc AHardwareBuffer" :
|
||||
reason == 4 ? "surface is positioned/cropped/scaled" :
|
||||
reason == 5 ? "surface has child surfaces" :
|
||||
reason == 6 ? "hidden shell surface" : "surface or buffer dimensions differ from scene";
|
||||
char name[160]; describe(s, name, sizeof(name));
|
||||
droiddeck_log("layer", "zero-copy: AHardwareBuffer-only candidate rejected: %s; %s, scene %dx%d, surface %dx%d at %d,%d, buffer %dx%d, crop=%d destination=%d children=%d",
|
||||
why, name, scene_w, scene_h, w, h, s->x, s->y, s->buf_w, s->buf_h,
|
||||
s->src_set, s->dst_set, !wl_list_empty(&s->children));
|
||||
} else if (!found && !limit_logged) {
|
||||
limit_logged = 1;
|
||||
droiddeck_log("layer", "zero-copy: further AHardwareBuffer-only candidate diagnostics suppressed after 32 signatures");
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -2502,7 +2921,13 @@ static int64_t scene_next_due(int64_t now, int64_t due, int limit) {
|
||||
|
||||
static void render_scene(void) {
|
||||
g_scene_due_ns = scene_next_due(now_ns(), g_scene_due_ns, g_fps_limit);
|
||||
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
|
||||
if (atomic_load(&g_stream_on)) {
|
||||
g_dirty_since_ns = 0;
|
||||
g_zero_copy_shown = NULL;
|
||||
settle_unwaited();
|
||||
render_stream();
|
||||
return;
|
||||
}
|
||||
struct draw_list dl = {0};
|
||||
struct surface *s;
|
||||
int w, h;
|
||||
@@ -2576,6 +3001,8 @@ static void render_scene(void) {
|
||||
} else {
|
||||
cursor_hdr_said = 0;
|
||||
}
|
||||
g_zero_copy_shown = NULL;
|
||||
if (hdr_route == 1 || hdr_route == 2) settle_unwaited();
|
||||
if (hdr_route == 1) {
|
||||
static int fell_back;
|
||||
vkp_apply_window_request();
|
||||
@@ -2609,6 +3036,7 @@ static void render_scene(void) {
|
||||
}
|
||||
if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
|
||||
!ahb_only) {
|
||||
settle_unwaited();
|
||||
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
|
||||
} else if (hdr_route == 0 || hdr_route == 3) {
|
||||
const int pass_on = fx_on || framegen;
|
||||
@@ -2644,7 +3072,10 @@ static void render_scene(void) {
|
||||
struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL;
|
||||
const struct vkp_draw *ld = li >= 0 ? &dl.d[li] : NULL;
|
||||
if (li < 0) ls = layer_only;
|
||||
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) note_copy_scene(&dl, w, h, cursor_on);
|
||||
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) {
|
||||
if (!cursor_on && !bfi) note_layer_candidate_rejected(&dl, w, h);
|
||||
note_copy_scene(&dl, w, h, cursor_on);
|
||||
}
|
||||
if (cardboard) ls = NULL;
|
||||
if (cursor_on) ls = NULL;
|
||||
if (bfi) ls = NULL;
|
||||
@@ -2658,6 +3089,7 @@ static void render_scene(void) {
|
||||
vkp_apply_window_request();
|
||||
int r = -1;
|
||||
const int fg_pass = framegen && fx_on && li >= 0;
|
||||
if (framegen && li >= 0) settle_unwaited();
|
||||
const int generated = (framegen && li >= 0)
|
||||
? sc_layer_present_generated(&dl.d[li], 1, NULL, w, h, fg_pass,
|
||||
ls ? droiddeck_surface_color(ls) : NULL) : 0;
|
||||
@@ -2671,16 +3103,34 @@ static void render_scene(void) {
|
||||
r = generated >= 0 ? 0 : -1;
|
||||
else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf))
|
||||
r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld);
|
||||
if (!fg_pass && generated >= 0 && r != 0 && li >= 0)
|
||||
r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h)
|
||||
: sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL);
|
||||
if (!fg_pass && generated >= 0 && !fx_on && !framegen && r != 0) {
|
||||
if (!ls || !ls->dmabuf_buf)
|
||||
note_zero_copy_fallback(ls, NULL, ZERO_COPY_NO_SURFACE_BUFFER, w, h, r);
|
||||
else if (!ahb_swapchain_has_ahb(ls->dmabuf_buf))
|
||||
note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_NO_GRALLOC_AHB, w, h, r);
|
||||
else
|
||||
note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_AHB_PRESENT_FAILED, w, h, r);
|
||||
}
|
||||
if (r == 0 && !fg_pass) g_zero_copy_shown = ls;
|
||||
else settle_unwaited();
|
||||
int ov = 0, ov_done = 0;
|
||||
if (!fg_pass && generated >= 0 && r != 0 && li >= 0) {
|
||||
if (fx_on) {
|
||||
r = sc_layer_present_pass(&dl.d[li], 1, w, h);
|
||||
} else {
|
||||
r = sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL,
|
||||
over == 1 ? &dl.d[li + 1] : NULL, &ov);
|
||||
ov_done = 1;
|
||||
}
|
||||
}
|
||||
if (r == 0) {
|
||||
if (ls) ls->drawn = 1;
|
||||
int go[8], ov = 0;
|
||||
if (over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
|
||||
int go[8];
|
||||
if (!ov_done && over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
|
||||
ov = sc_layer_present_overlay(dl.d[li + 1].img, go, dl.d[li + 1].blend) == 0 ? 1 : -1;
|
||||
if (ov <= 0) sc_layer_hide_overlay();
|
||||
if (ov < 0) {
|
||||
settle_unwaited();
|
||||
sc_layer_hide();
|
||||
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
|
||||
copy = 1;
|
||||
@@ -2690,12 +3140,14 @@ static void render_scene(void) {
|
||||
g_scene_queues = sc_layer_queues();
|
||||
}
|
||||
} else {
|
||||
settle_unwaited();
|
||||
sc_layer_hide();
|
||||
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
|
||||
copy = 1;
|
||||
hdr_copy = "its display layer was unavailable this frame";
|
||||
}
|
||||
} else {
|
||||
settle_unwaited();
|
||||
sc_layer_hide();
|
||||
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
|
||||
copy = 1;
|
||||
@@ -4131,11 +4583,15 @@ static void output_resized(void) {
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
|
||||
static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
static void dispatch_input(int fd, int remaining) {
|
||||
struct input_msg m;
|
||||
int vsync = 0;
|
||||
int64_t vsync_ns = 0;
|
||||
while (read(fd, &m, sizeof(m)) == (ssize_t)sizeof(m)) {
|
||||
while (remaining != 0) {
|
||||
ssize_t n = read(fd, &m, sizeof(m));
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
if (n != (ssize_t)sizeof(m)) break;
|
||||
if (remaining > 0) --remaining;
|
||||
switch (m.type) {
|
||||
case 1: deliver_key(&m); break;
|
||||
case 2: pointer_event(m.p1, m.p2, 0, 0); break;
|
||||
@@ -4177,9 +4633,27 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
wl_display_flush_clients(g_display);
|
||||
}
|
||||
if (vsync) on_vsync(vsync_ns);
|
||||
}
|
||||
|
||||
static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
dispatch_input(fd, -1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void droiddeck_dispatch_pending_input(void) {
|
||||
int fd = g_input_pipe[0];
|
||||
if (fd < 0) return;
|
||||
|
||||
int bytes;
|
||||
int result;
|
||||
do {
|
||||
result = ioctl(fd, FIONREAD, &bytes);
|
||||
} while (result < 0 && errno == EINTR);
|
||||
if (result == 0 && bytes >= (int)sizeof(struct input_msg)) {
|
||||
dispatch_input(fd, bytes / (int)sizeof(struct input_msg));
|
||||
}
|
||||
}
|
||||
|
||||
void droiddeck_wayland_set_scale_mode(int mode, int alignment) {
|
||||
if (g_input_pipe[1] < 0) {
|
||||
vk_present_set_scale_mode(mode, alignment);
|
||||
@@ -4316,6 +4790,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;
|
||||
@@ -4344,11 +4823,12 @@ static int on_stats_timer(void *data) {
|
||||
unsigned aimed_next, aimed_later, aimed_even;
|
||||
sc_layer_aim_take(&aimed_next, &aimed_later, &aimed_even);
|
||||
#define PERF_MS(sum, n) ((n) ? (double)(sum) / 1e6 / (double)(n) : 0.0)
|
||||
if (g_perf.scenes || vp.presents || g_perf.releases || drops)
|
||||
if (g_perf.scenes || vp.presents || g_perf.releases || drops || g_perf.commit_waits)
|
||||
droiddeck_log("perf", "last 10 s: %u ticks, %u scenes, %u on screen (copy %u, zero-copy %u, layer copy %u) | "
|
||||
"render_scene %.2f/%.2f ms | base %u black kept, %u presented | acquire %.2f/%.2f ms | "
|
||||
"present %.2f/%.2f ms (%u) | fence wait %.2f/%.2f ms (%u, %u GPU release waits) | "
|
||||
"release %.2f/%.2f ms (%u, %u held) | %u pool drops | layer frames timed for the next refresh %u, "
|
||||
"release %.2f/%.2f ms (%u, %u held) | commits held for client writes %.2f/%.2f ms (%u, %u past the limit) | "
|
||||
"%u pool drops | layer frames timed for the next refresh %u, "
|
||||
"the one after %u, held to an even step %u",
|
||||
g_perf.ticks, g_perf.scenes, g_stat_frames, g_perf.copy_scenes, zero_copy, layer_frames,
|
||||
PERF_MS(g_perf.scene_ns, g_perf.scenes), (double)g_perf.scene_max_ns / 1e6,
|
||||
@@ -4357,7 +4837,9 @@ static int on_stats_timer(void *data) {
|
||||
PERF_MS(vp.present_ns, vp.presents), (double)vp.present_max_ns / 1e6, vp.presents,
|
||||
PERF_MS(vp.wait_ns, vp.waits), (double)vp.wait_max_ns / 1e6, vp.waits, vp.gpu_release_waits,
|
||||
PERF_MS(g_perf.release_ns, g_perf.releases), (double)g_perf.release_max_ns / 1e6,
|
||||
g_perf.releases, g_perf.releases_held, drops, aimed_next, aimed_later, aimed_even);
|
||||
g_perf.releases, g_perf.releases_held,
|
||||
PERF_MS(g_perf.commit_wait_ns, g_perf.commit_waits), (double)g_perf.commit_wait_max_ns / 1e6,
|
||||
g_perf.commit_waits, g_perf.commit_wait_limits, drops, aimed_next, aimed_later, aimed_even);
|
||||
#undef PERF_MS
|
||||
memset(&g_perf, 0, sizeof(g_perf));
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <limits.h>
|
||||
#include <linux/input-event-codes.h>
|
||||
#include <android/log.h>
|
||||
#include "droiddeck_ext.h"
|
||||
#include "ahb_swapchain.h"
|
||||
#include "droiddeck_color.h"
|
||||
|
||||
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT };
|
||||
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD };
|
||||
|
||||
struct host_msg {
|
||||
enum host_kind kind;
|
||||
@@ -23,6 +25,32 @@ static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct host_msg *g_head, *g_tail;
|
||||
static int g_wake[2] = {-1, -1};
|
||||
|
||||
/* Compositor-thread-only fallback ordering state. */
|
||||
static int g_pending_token, g_pending_submit;
|
||||
static int g_fallback_failed;
|
||||
static int g_next_token = 1;
|
||||
static struct host_msg *g_deferred_head, *g_deferred_tail;
|
||||
static size_t g_deferred_count, g_deferred_bytes;
|
||||
static int g_deferred_overflow;
|
||||
static int g_completed_token, g_completed_result;
|
||||
|
||||
#define DROIDDECK_EVDEV_KEY_MAX 768
|
||||
#define DROIDDECK_TEXT_DEFERRED_LIMIT 256
|
||||
#define DROIDDECK_TEXT_DEFERRED_BYTES (256 * 1024)
|
||||
static unsigned char g_ordered_key_down[DROIDDECK_EVDEV_KEY_MAX];
|
||||
|
||||
void droiddeck_host_text_input_fallback_complete(int token, int result) {
|
||||
pthread_mutex_lock(&g_mu);
|
||||
g_completed_token = token;
|
||||
g_completed_result = result;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (g_wake[1] >= 0) {
|
||||
char c = 1;
|
||||
ssize_t n = write(g_wake[1], &c, 1);
|
||||
(void)n;
|
||||
}
|
||||
}
|
||||
|
||||
static void host_post(enum host_kind kind, const char *text, size_t len, int a, int b) {
|
||||
struct host_msg *m = calloc(1, sizeof(*m));
|
||||
if (!m) return;
|
||||
@@ -51,6 +79,9 @@ void droiddeck_host_clipboard_text(const char *utf8, int len) {
|
||||
void droiddeck_host_text_commit(const char *utf8, int len) {
|
||||
host_post(HOST_TEXT_COMMIT, utf8, len > 0 ? (size_t)len : 0, 0, 0);
|
||||
}
|
||||
void droiddeck_host_text_commit_and_submit(const char *utf8, int len) {
|
||||
if (len > 0) host_post(HOST_TEXT_COMMIT, utf8, (size_t)len, 1, 0);
|
||||
}
|
||||
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end) {
|
||||
host_post(HOST_TEXT_PREEDIT, utf8, len > 0 ? (size_t)len : 0, cursor_begin, cursor_end);
|
||||
}
|
||||
@@ -63,23 +94,173 @@ void droiddeck_host_zero_copy(int on, int live) {
|
||||
void droiddeck_host_hdr_output(int on) {
|
||||
host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0);
|
||||
}
|
||||
void droiddeck_host_key(int evdev, int state) {
|
||||
host_post(HOST_KEY, NULL, 0, evdev, state);
|
||||
}
|
||||
|
||||
void droiddeck_host_select_game_field(int copy) {
|
||||
host_post(HOST_SELECT_GAME_FIELD, NULL, 0, copy, 0);
|
||||
}
|
||||
|
||||
static void tap_unheld_key(uint32_t key) {
|
||||
if (droiddeck_key_is_down(key)) return;
|
||||
droiddeck_inject_key(key, 1);
|
||||
droiddeck_inject_key(key, 0);
|
||||
}
|
||||
|
||||
static void select_game_field(int copy) {
|
||||
/* Apply pending raw releases before using the compositor's held-key state. */
|
||||
droiddeck_dispatch_pending_input();
|
||||
int temporary_ctrl = !droiddeck_key_is_down(KEY_LEFTCTRL) && !droiddeck_key_is_down(KEY_RIGHTCTRL);
|
||||
if (temporary_ctrl) droiddeck_inject_key(KEY_LEFTCTRL, 1);
|
||||
tap_unheld_key(KEY_A);
|
||||
if (copy) tap_unheld_key(KEY_C);
|
||||
if (temporary_ctrl) droiddeck_inject_key(KEY_LEFTCTRL, 0);
|
||||
}
|
||||
|
||||
static void restore_deferred_to_front(void) {
|
||||
if (g_deferred_head) {
|
||||
g_deferred_tail->next = g_head;
|
||||
if (!g_head) g_tail = g_deferred_tail;
|
||||
g_head = g_deferred_head;
|
||||
g_deferred_head = g_deferred_tail = NULL;
|
||||
g_deferred_count = g_deferred_bytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Only suppress the queued submit for this commit, not a later commit or a held-key release. */
|
||||
static void discard_queued_submit(void) {
|
||||
struct host_msg *prev = NULL;
|
||||
struct host_msg *m = g_head;
|
||||
int enter_held = g_ordered_key_down[KEY_ENTER];
|
||||
int key_pad_enter_held = g_ordered_key_down[KEY_KPENTER];
|
||||
while (m) {
|
||||
int soft_submit = 0;
|
||||
if (m->kind == HOST_TEXT_COMMIT) {
|
||||
if (m->a || m->len == 0) break;
|
||||
soft_submit = 1;
|
||||
size_t i = 0;
|
||||
for (; i < m->len; i++) {
|
||||
char c = m->text[i];
|
||||
if (c != '\r' && c != '\n') soft_submit = 0;
|
||||
if (c != '\r' && c != '\n' && c != '\b' && c != '\t' && c != 0x7f) break;
|
||||
}
|
||||
if (i != m->len) break;
|
||||
}
|
||||
struct host_msg *next = m->next;
|
||||
int *held = m->a == KEY_ENTER ? &enter_held : m->a == KEY_KPENTER ? &key_pad_enter_held : NULL;
|
||||
if (soft_submit || (m->kind == HOST_KEY && held && (m->b != 0 || !*held))) {
|
||||
if (prev) prev->next = next; else g_head = next;
|
||||
if (g_tail == m) g_tail = prev;
|
||||
free(m->text);
|
||||
free(m);
|
||||
} else {
|
||||
if (m->kind == HOST_KEY && held) *held = 0;
|
||||
prev = m;
|
||||
}
|
||||
m = next;
|
||||
}
|
||||
}
|
||||
|
||||
static int release_held_key(const struct host_msg *m) {
|
||||
int k = m->a;
|
||||
if (m->kind != HOST_KEY || m->b != 0 || k < 0 || k >= DROIDDECK_EVDEV_KEY_MAX ||
|
||||
!g_ordered_key_down[k]) return 0;
|
||||
g_ordered_key_down[k] = 0;
|
||||
droiddeck_inject_key((uint32_t)k, 0);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void discard_deferred_input(void) {
|
||||
struct host_msg *m = g_deferred_head;
|
||||
while (m) {
|
||||
struct host_msg *next = m->next;
|
||||
release_held_key(m);
|
||||
free(m->text);
|
||||
free(m);
|
||||
m = next;
|
||||
}
|
||||
g_deferred_head = g_deferred_tail = NULL;
|
||||
g_deferred_count = g_deferred_bytes = 0;
|
||||
}
|
||||
|
||||
static int on_wake(int fd, uint32_t mask, void *data) {
|
||||
char buf[64];
|
||||
while (read(fd, buf, sizeof(buf)) > 0) {}
|
||||
for (;;) {
|
||||
int deferred = 0, submit = 0;
|
||||
pthread_mutex_lock(&g_mu);
|
||||
if (g_pending_token != 0 && g_completed_token == g_pending_token) {
|
||||
int result = g_completed_result;
|
||||
g_completed_token = 0;
|
||||
restore_deferred_to_front();
|
||||
if (result != DROIDDECK_TEXT_DELIVERED) discard_queued_submit();
|
||||
if (result == DROIDDECK_TEXT_UNRESOLVED) {
|
||||
g_fallback_failed = 1;
|
||||
} else {
|
||||
if (result == DROIDDECK_TEXT_DELIVERED) submit = g_pending_submit;
|
||||
g_pending_submit = 0;
|
||||
g_pending_token = 0;
|
||||
g_fallback_failed = 0;
|
||||
g_deferred_overflow = 0;
|
||||
}
|
||||
}
|
||||
struct host_msg *m = g_head;
|
||||
if (m) { g_head = m->next; if (!g_head) g_tail = NULL; }
|
||||
if (m) { g_head = m->next; if (!g_head) g_tail = NULL; m->next = NULL; }
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (submit) tap_unheld_key(KEY_ENTER);
|
||||
if (!m) break;
|
||||
if (g_pending_token != 0 &&
|
||||
(m->kind == HOST_TEXT_COMMIT || m->kind == HOST_TEXT_PREEDIT ||
|
||||
m->kind == HOST_TEXT_DELETE || m->kind == HOST_KEY ||
|
||||
m->kind == HOST_SELECT_GAME_FIELD)) {
|
||||
int released_during_recovery = g_fallback_failed && release_held_key(m);
|
||||
if (released_during_recovery || g_deferred_overflow ||
|
||||
g_deferred_count == DROIDDECK_TEXT_DEFERRED_LIMIT ||
|
||||
m->len > DROIDDECK_TEXT_DEFERRED_BYTES - g_deferred_bytes) {
|
||||
if (!released_during_recovery) {
|
||||
/* An incomplete queue could replay a submit or lose a paired release. */
|
||||
if (!g_deferred_overflow)
|
||||
droiddeck_log("text-input", "deferred input exceeded the recovery queue limit");
|
||||
discard_deferred_input();
|
||||
release_held_key(m);
|
||||
g_deferred_overflow = 1;
|
||||
}
|
||||
free(m->text);
|
||||
free(m);
|
||||
continue;
|
||||
}
|
||||
if (g_deferred_tail) g_deferred_tail->next = m; else g_deferred_head = m;
|
||||
g_deferred_tail = m;
|
||||
g_deferred_count++;
|
||||
g_deferred_bytes += m->len;
|
||||
deferred = 1;
|
||||
}
|
||||
if (deferred) continue;
|
||||
switch (m->kind) {
|
||||
case HOST_CLIPBOARD:
|
||||
clipboard_host_text(m->text, m->len);
|
||||
m->text = NULL;
|
||||
break;
|
||||
case HOST_TEXT_COMMIT:
|
||||
text_input_host_commit(m->text ? m->text : "", m->len);
|
||||
if (!text_input_host_commit(m->text ? m->text : "", m->len)) {
|
||||
int token = 0;
|
||||
if (g_next_token == INT_MAX) g_next_token = 1;
|
||||
else g_next_token++;
|
||||
token = g_next_token;
|
||||
g_pending_token = 0;
|
||||
if (droiddeck_on_text_input_fallback(m->text ? m->text : "", (int)m->len, token)) {
|
||||
g_pending_token = token;
|
||||
g_pending_submit = m->a;
|
||||
} else {
|
||||
droiddeck_log("text-input", "fallback had no accepting Android listener");
|
||||
pthread_mutex_lock(&g_mu);
|
||||
discard_queued_submit();
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
}
|
||||
} else if (m->a) {
|
||||
tap_unheld_key(KEY_ENTER);
|
||||
}
|
||||
break;
|
||||
case HOST_TEXT_PREEDIT:
|
||||
text_input_host_preedit(m->text ? m->text : "", m->len, m->a, m->b);
|
||||
@@ -93,6 +274,19 @@ static int on_wake(int fd, uint32_t mask, void *data) {
|
||||
case HOST_HDR_OUTPUT:
|
||||
droiddeck_color_set_output(m->a);
|
||||
break;
|
||||
case HOST_SELECT_GAME_FIELD:
|
||||
select_game_field(m->a);
|
||||
break;
|
||||
case HOST_KEY:
|
||||
if (m->b == 1) {
|
||||
int k = m->a;
|
||||
if (k >= 0 && k < DROIDDECK_EVDEV_KEY_MAX) g_ordered_key_down[k] = 1;
|
||||
} else if (m->b == 0) {
|
||||
int k = m->a;
|
||||
if (k >= 0 && k < DROIDDECK_EVDEV_KEY_MAX) g_ordered_key_down[k] = 0;
|
||||
}
|
||||
droiddeck_inject_key((uint32_t)m->a, m->b);
|
||||
break;
|
||||
}
|
||||
free(m->text);
|
||||
free(m);
|
||||
|
||||
@@ -15,22 +15,34 @@ struct wl_display *droiddeck_get_display(void);
|
||||
struct wl_resource *droiddeck_ime_target(void);
|
||||
void droiddeck_surface_scene_origin(struct wl_resource *surface, int *x, int *y);
|
||||
void droiddeck_inject_key(uint32_t evdev, int pressed);
|
||||
int droiddeck_key_is_down(uint32_t evdev);
|
||||
void droiddeck_dispatch_pending_input(void);
|
||||
|
||||
void droiddeck_on_clipboard_text(const char *utf8, int len);
|
||||
int droiddeck_on_text_input_fallback(const char *utf8, int len, int token);
|
||||
void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h);
|
||||
|
||||
|
||||
void droiddeck_host_clipboard_text(const char *utf8, int len);
|
||||
void droiddeck_host_text_commit(const char *utf8, int len);
|
||||
void droiddeck_host_text_commit_and_submit(const char *utf8, int len);
|
||||
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end);
|
||||
void droiddeck_host_text_delete(int before, int after);
|
||||
void droiddeck_host_zero_copy(int on, int live);
|
||||
void droiddeck_host_hdr_output(int on);
|
||||
void droiddeck_host_key(int evdev, int state);
|
||||
void droiddeck_host_select_game_field(int copy);
|
||||
enum droiddeck_text_input_result {
|
||||
DROIDDECK_TEXT_NOT_DELIVERED = 0,
|
||||
DROIDDECK_TEXT_DELIVERED = 1,
|
||||
DROIDDECK_TEXT_UNRESOLVED = 2,
|
||||
};
|
||||
void droiddeck_host_text_input_fallback_complete(int token, int result);
|
||||
|
||||
void clipboard_init(struct wl_display *display);
|
||||
void clipboard_host_text(char *utf8, size_t len);
|
||||
void text_input_init(struct wl_display *display);
|
||||
void text_input_host_commit(const char *utf8, size_t len);
|
||||
int text_input_host_commit(const char *utf8, size_t len);
|
||||
void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end);
|
||||
void text_input_host_delete(int before, int after);
|
||||
void toplevel_icon_init(struct wl_display *display);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "blend_pass.h"
|
||||
#include "vk_loader.h"
|
||||
#include "vk_present.h"
|
||||
#include "framegen_bridge.h"
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -69,6 +70,7 @@ static struct fx_settings g_set = {
|
||||
.gamma = 1.0f, .saturation = 1.0f, .s_raw = 100.0f, .look = "Off"};
|
||||
static volatile int g_changed;
|
||||
static struct fx_settings g_cur;
|
||||
static struct fx_settings g_generated_settings;
|
||||
static int g_cur_valid;
|
||||
|
||||
static void set_begin(void) { pthread_mutex_lock(&g_lock); }
|
||||
@@ -235,13 +237,24 @@ static VkDescriptorPool g_dpool;
|
||||
static VkSampler g_sampler;
|
||||
enum { P_SGSR, P_SGSR_HQ, P_NIS, P_EASU, P_RCAS, P_CAS, P_COLOR, P_FXAA, P_FXAA_TOON, P_SMAA_EDGE, P_SMAA_WEIGHTS, P_SMAA_BLEND, P_TOON, P_TOON_COLOR, P_HDR, P_NTSC, P_CRT, P_DEBAND, P_NIS_LUMA, P_COUNT };
|
||||
static VkPipeline g_pipe[P_COUNT];
|
||||
static struct fx_target g_t[2], g_mid, g_smaa_edges, g_smaa_weights;
|
||||
struct fx_context {
|
||||
struct fx_target targets[2], mid, nissrc;
|
||||
struct { VkImage img; VkImageView view; VkDescriptorSet ds; int w, h; } scene;
|
||||
};
|
||||
#define FX_CONTEXTS (VKP_FG_MAX_GENERATIONS + 2)
|
||||
static struct fx_context g_contexts[FX_CONTEXTS];
|
||||
static int g_context;
|
||||
#define g_t (g_contexts[g_context].targets)
|
||||
#define g_mid (g_contexts[g_context].mid)
|
||||
#define g_nissrc (g_contexts[g_context].nissrc)
|
||||
static struct fx_target g_smaa_edges, g_smaa_weights;
|
||||
/* Half set: NIS = nis_luma prepass (scene rgb + luma in alpha, scene size) into g_nissrc, then
|
||||
* nis3 gathers its luma from that alpha, its coefficient banks (nis_coef.h) in a uniform buffer
|
||||
* at descriptor set 1 (g_pl_nis = {g_dsl, g_coef_dsl}, same push-constant range as g_pl).
|
||||
* Old set (or no buffer): nis.frag on the scene, P_NIS_LUMA unused. */
|
||||
static struct fx_target g_nissrc;
|
||||
static int g_nis_fast;
|
||||
static int g_nis_attempted;
|
||||
static int g_upscale_half;
|
||||
static VkDescriptorSetLayout g_coef_dsl;
|
||||
static VkPipelineLayout g_pl_nis;
|
||||
static VkDescriptorPool g_coef_pool;
|
||||
@@ -249,7 +262,7 @@ static VkDescriptorSet g_coef_ds;
|
||||
static VkBuffer g_coef_buf;
|
||||
static VkDeviceMemory g_coef_mem;
|
||||
|
||||
static struct { VkImage img; VkImageView view; VkDescriptorSet ds; int w, h; } g_scene;
|
||||
#define g_scene (g_contexts[g_context].scene)
|
||||
|
||||
void vkp_effects_bind_device(VkDevice dev, VkPhysicalDevice pd,
|
||||
const VkPhysicalDeviceMemoryProperties *memprops) {
|
||||
@@ -347,7 +360,15 @@ 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;
|
||||
}
|
||||
|
||||
void vkp_effects_release_generated_sources(void) {
|
||||
for (g_context = 1; g_context < FX_CONTEXTS; g_context++) scene_release();
|
||||
g_context = 0;
|
||||
}
|
||||
|
||||
static int scene_ensure(VkImage img, int w, int h) {
|
||||
@@ -473,9 +494,14 @@ static int upscale_half_set(void) {
|
||||
|
||||
static void objects_destroy(void) {
|
||||
if (!g_dev) return;
|
||||
scene_release();
|
||||
target_destroy(&g_t[0]); target_destroy(&g_t[1]); target_destroy(&g_mid);
|
||||
target_destroy(&g_smaa_edges); target_destroy(&g_smaa_weights); target_destroy(&g_nissrc);
|
||||
int saved = g_context;
|
||||
for (g_context = 0; g_context < FX_CONTEXTS; g_context++) {
|
||||
scene_release();
|
||||
target_destroy(&g_t[0]); target_destroy(&g_t[1]); target_destroy(&g_mid);
|
||||
target_destroy(&g_nissrc);
|
||||
}
|
||||
g_context = saved;
|
||||
target_destroy(&g_smaa_edges); target_destroy(&g_smaa_weights);
|
||||
for (int i = 0; i < P_COUNT; i++) { if (g_pipe[i]) g_vk.DestroyPipeline(g_dev, g_pipe[i], NULL); g_pipe[i] = VK_NULL_HANDLE; }
|
||||
if (g_dpool) g_vk.DestroyDescriptorPool(g_dev, g_dpool, NULL);
|
||||
if (g_pl) g_vk.DestroyPipelineLayout(g_dev, g_pl, NULL);
|
||||
@@ -486,6 +512,7 @@ static void objects_destroy(void) {
|
||||
if (g_rp) g_vk.DestroyRenderPass(g_dev, g_rp, NULL);
|
||||
g_dpool = VK_NULL_HANDLE; g_pl = VK_NULL_HANDLE; g_dsl = VK_NULL_HANDLE;
|
||||
g_sampler = VK_NULL_HANDLE; g_rp = VK_NULL_HANDLE; g_smaa_rp = VK_NULL_HANDLE;
|
||||
g_nis_fast = 0; g_nis_attempted = 0; g_upscale_half = 0;
|
||||
g_ready = 0;
|
||||
}
|
||||
|
||||
@@ -505,7 +532,9 @@ void vkp_effects_set_formats(VkFormat scene_fmt, VkFormat target_fmt, int scene_
|
||||
: target_fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? "the HDR picture for frame generation"
|
||||
: "the HDR composition's picture: PQ, or tone-mapped SDR with HDR output off");
|
||||
} else if (scene_fmt != g_scene_fmt) {
|
||||
scene_release();
|
||||
int saved = g_context;
|
||||
for (g_context = 0; g_context < FX_CONTEXTS; g_context++) scene_release();
|
||||
g_context = saved;
|
||||
g_scene_fmt = scene_fmt;
|
||||
}
|
||||
}
|
||||
@@ -556,75 +585,17 @@ static int objects_ensure(void) {
|
||||
VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 2, .pSetLayouts = set_layouts,
|
||||
.pushConstantRangeCount = 1, .pPushConstantRanges = &pcr};
|
||||
if (g_vk.CreatePipelineLayout(g_dev, &pli, NULL, &g_pl) != VK_SUCCESS) goto fail;
|
||||
VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 10};
|
||||
VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, FX_CONTEXTS * 5 + 2};
|
||||
VkDescriptorPoolCreateInfo dpi = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
|
||||
.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, .maxSets = 10,
|
||||
.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, .maxSets = FX_CONTEXTS * 5 + 2,
|
||||
.poolSizeCount = 1, .pPoolSizes = &ps};
|
||||
if (g_vk.CreateDescriptorPool(g_dev, &dpi, NULL, &g_dpool) != VK_SUCCESS) goto fail;
|
||||
|
||||
VkShaderModule vert = shader(upscale_vert_code, sizeof(upscale_vert_code));
|
||||
if (!vert) goto fail;
|
||||
#define MKL(slot, code, name, layout) do { g_pipe[slot] = post_pipeline_for_renderpass(vert, code, sizeof(code), g_rp, name, layout); if (!g_pipe[slot]) { g_vk.DestroyShaderModule(g_dev, vert, NULL); goto fail; } } while (0)
|
||||
#define MK(slot, code, name) MKL(slot, code, name, g_pl)
|
||||
const int half = upscale_half_set();
|
||||
g_upscale_half = upscale_half_set();
|
||||
g_nis_fast = 0;
|
||||
if (half && !fx_alpha_holds_luma(g_fx_fmt))
|
||||
droiddeck_log("effects", "NIS uses nis.frag: the chain format has no 8-bit alpha for the luma prepass");
|
||||
else if (half && coef_create() != 0)
|
||||
droiddeck_log("effects", "NIS coefficient buffer unavailable; NIS uses nis.frag");
|
||||
else if (half)
|
||||
g_nis_fast = 1;
|
||||
if (half) {
|
||||
MK(P_SGSR, sgsr_half_code, "sgsr_half");
|
||||
MK(P_SGSR_HQ, sgsr_quality_half_code, "sgsr_quality_half");
|
||||
if (g_nis_fast) {
|
||||
/* optional: a driver that rejects either fast NIS pipeline gets nis.frag, not a dead chain */
|
||||
g_pipe[P_NIS] = post_pipeline_for_renderpass(vert, nis3_half_code, sizeof(nis3_half_code), g_rp, "nis3_half", g_pl_nis);
|
||||
g_pipe[P_NIS_LUMA] = g_pipe[P_NIS]
|
||||
? post_pipeline_for_renderpass(vert, nis_luma_half_code, sizeof(nis_luma_half_code), g_rp, "nis_luma_half", g_pl)
|
||||
: VK_NULL_HANDLE;
|
||||
if (!g_pipe[P_NIS] || !g_pipe[P_NIS_LUMA]) {
|
||||
if (g_pipe[P_NIS]) g_vk.DestroyPipeline(g_dev, g_pipe[P_NIS], NULL);
|
||||
g_pipe[P_NIS] = VK_NULL_HANDLE;
|
||||
coef_destroy();
|
||||
g_nis_fast = 0;
|
||||
droiddeck_log("effects", "fast NIS pipelines failed to build; NIS uses nis.frag");
|
||||
}
|
||||
}
|
||||
if (!g_nis_fast) MK(P_NIS, nis_code, "nis");
|
||||
MK(P_EASU, fsr_easu_half_code, "fsr_easu_half");
|
||||
MK(P_RCAS, fsr_rcas_half_code, "fsr_rcas_half");
|
||||
MK(P_CAS, cas_ffx_half_code, "cas_ffx_half");
|
||||
} else {
|
||||
MK(P_SGSR, sgsr_code, "sgsr");
|
||||
MK(P_SGSR_HQ, sgsr_quality_code, "sgsr_quality");
|
||||
MK(P_NIS, nis_code, "nis");
|
||||
MK(P_EASU, fsr_easu_code, "fsr_easu");
|
||||
MK(P_RCAS, fsr_rcas_code, "fsr_rcas");
|
||||
MK(P_CAS, cas_code, "cas");
|
||||
}
|
||||
MK(P_COLOR, color_code, "color");
|
||||
MK(P_FXAA, fxaa_code, "fxaa");
|
||||
MK(P_FXAA_TOON, fxaa_toon_code, "fxaa_toon");
|
||||
g_pipe[P_SMAA_EDGE] = post_pipeline_for_renderpass(
|
||||
vert, smaa_edge_code, sizeof(smaa_edge_code), g_smaa_rp, "smaa_edge", g_pl);
|
||||
if (!g_pipe[P_SMAA_EDGE]) { g_vk.DestroyShaderModule(g_dev, vert, NULL); goto fail; }
|
||||
g_pipe[P_SMAA_WEIGHTS] = post_pipeline_for_renderpass(
|
||||
vert, smaa_weights_code, sizeof(smaa_weights_code), g_smaa_rp, "smaa_weights", g_pl);
|
||||
if (!g_pipe[P_SMAA_WEIGHTS]) { g_vk.DestroyShaderModule(g_dev, vert, NULL); goto fail; }
|
||||
MK(P_SMAA_BLEND, smaa_blend_code, "smaa_blend");
|
||||
MK(P_TOON, toon_code, "toon");
|
||||
MK(P_TOON_COLOR, toon_color_code, "toon_color");
|
||||
MK(P_HDR, hdr_code, "hdr");
|
||||
MK(P_NTSC, ntsc_code, "ntsc");
|
||||
MK(P_CRT, crt_code, "crt");
|
||||
MK(P_DEBAND, deband_code, "deband");
|
||||
#undef MK
|
||||
#undef MKL
|
||||
g_vk.DestroyShaderModule(g_dev, vert, NULL);
|
||||
g_nis_attempted = 0;
|
||||
g_ready = 1;
|
||||
droiddeck_log("effects", "chain ready: 16 pipelines (SGSR, SGSR HQ, NIS, FSR EASU+RCAS, CAS, colour, FXAA, SMAA edge/weights/blend, Toon, HDR, NTSC, CRT, deband), %s upscalers%s, on %s",
|
||||
half ? "half-precision" : "old fp32", g_nis_fast ? " + NIS luma prepass" : "", vkp_gpu_name());
|
||||
droiddeck_log("effects", "shared resources ready on %s; effect pipelines are created when needed", vkp_gpu_name());
|
||||
return 0;
|
||||
fail:
|
||||
objects_destroy();
|
||||
@@ -633,6 +604,95 @@ fail:
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int chain_failed(void) {
|
||||
objects_destroy();
|
||||
g_ready = -1;
|
||||
droiddeck_log("error", "effects: the screen-effect chain could not be built on this driver; effects are off for this session");
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int pipelines_ensure(int spatial, const struct fx_settings *s) {
|
||||
VkShaderModule vert = VK_NULL_HANDLE;
|
||||
#define MKL(needed, slot, code, name, render_pass, layout) do { \
|
||||
if ((needed) && !g_pipe[slot]) { \
|
||||
if (!vert && !(vert = shader(upscale_vert_code, sizeof(upscale_vert_code)))) goto fail; \
|
||||
g_pipe[slot] = post_pipeline_for_renderpass(vert, code, sizeof(code), render_pass, name, layout); \
|
||||
if (!g_pipe[slot]) goto fail; \
|
||||
} \
|
||||
} while (0)
|
||||
#define MK(needed, slot, code, name) MKL(needed, slot, code, name, g_rp, g_pl)
|
||||
if (spatial == 3) {
|
||||
if (g_upscale_half) MK(1, P_SGSR, sgsr_half_code, "sgsr_half");
|
||||
else MK(1, P_SGSR, sgsr_code, "sgsr");
|
||||
}
|
||||
if (spatial == 8) {
|
||||
if (g_upscale_half) MK(1, P_SGSR_HQ, sgsr_quality_half_code, "sgsr_quality_half");
|
||||
else MK(1, P_SGSR_HQ, sgsr_quality_code, "sgsr_quality");
|
||||
}
|
||||
if (spatial == 4 || spatial == 5) {
|
||||
if (g_upscale_half) MK(1, P_EASU, fsr_easu_half_code, "fsr_easu_half");
|
||||
else MK(1, P_EASU, fsr_easu_code, "fsr_easu");
|
||||
if (s->sharp_pct != 0) {
|
||||
if (g_upscale_half) MK(1, P_RCAS, fsr_rcas_half_code, "fsr_rcas_half");
|
||||
else MK(1, P_RCAS, fsr_rcas_code, "fsr_rcas");
|
||||
}
|
||||
}
|
||||
if (spatial == 6) {
|
||||
if (g_upscale_half) MK(1, P_RCAS, fsr_rcas_half_code, "fsr_rcas_half");
|
||||
else MK(1, P_RCAS, fsr_rcas_code, "fsr_rcas");
|
||||
}
|
||||
if (spatial == 7) {
|
||||
if (g_upscale_half && !g_nis_attempted) {
|
||||
g_nis_attempted = 1;
|
||||
if (!fx_alpha_holds_luma(g_fx_fmt))
|
||||
droiddeck_log("effects", "NIS uses nis.frag: the chain format has no 8-bit alpha for the luma prepass");
|
||||
else if (coef_create() != 0)
|
||||
droiddeck_log("effects", "NIS coefficient buffer unavailable; NIS uses nis.frag");
|
||||
else {
|
||||
if (!vert && !(vert = shader(upscale_vert_code, sizeof(upscale_vert_code)))) goto fail;
|
||||
g_pipe[P_NIS] = post_pipeline_for_renderpass(vert, nis3_half_code, sizeof(nis3_half_code), g_rp, "nis3_half", g_pl_nis);
|
||||
if (g_pipe[P_NIS])
|
||||
g_pipe[P_NIS_LUMA] = post_pipeline_for_renderpass(vert, nis_luma_half_code, sizeof(nis_luma_half_code), g_rp, "nis_luma_half", g_pl);
|
||||
if (g_pipe[P_NIS] && g_pipe[P_NIS_LUMA]) g_nis_fast = 1;
|
||||
else {
|
||||
if (g_pipe[P_NIS]) g_vk.DestroyPipeline(g_dev, g_pipe[P_NIS], NULL);
|
||||
if (g_pipe[P_NIS_LUMA]) g_vk.DestroyPipeline(g_dev, g_pipe[P_NIS_LUMA], NULL);
|
||||
g_pipe[P_NIS] = VK_NULL_HANDLE;
|
||||
g_pipe[P_NIS_LUMA] = VK_NULL_HANDLE;
|
||||
coef_destroy();
|
||||
droiddeck_log("effects", "fast NIS pipelines failed to build; NIS uses nis.frag");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!g_nis_fast) MK(1, P_NIS, nis_code, "nis");
|
||||
else if (g_upscale_half) MK(1, P_SGSR, sgsr_half_code, "sgsr_half");
|
||||
}
|
||||
if (cas_active(s)) {
|
||||
if (g_upscale_half) MK(1, P_CAS, cas_ffx_half_code, "cas_ffx_half");
|
||||
else MK(1, P_CAS, cas_code, "cas");
|
||||
}
|
||||
if (s->color_on && !(s->toon && g_fx_fmt == FX_FORMAT)) MK(1, P_COLOR, color_code, "color");
|
||||
if (s->aa_mode == 1 || s->aa_mode == 2) MK(1, P_FXAA, fxaa_code, "fxaa");
|
||||
if (s->aa_mode == 2) {
|
||||
MKL(1, P_SMAA_EDGE, smaa_edge_code, "smaa_edge", g_smaa_rp, g_pl);
|
||||
MKL(1, P_SMAA_WEIGHTS, smaa_weights_code, "smaa_weights", g_smaa_rp, g_pl);
|
||||
MK(1, P_SMAA_BLEND, smaa_blend_code, "smaa_blend");
|
||||
}
|
||||
if (s->toon && s->color_on && g_fx_fmt == FX_FORMAT) MK(1, P_TOON_COLOR, toon_color_code, "toon_color");
|
||||
else if (s->toon) MK(1, P_TOON, toon_code, "toon");
|
||||
if (s->hdr_on) MK(1, P_HDR, hdr_code, "hdr");
|
||||
if (s->ntsc) MK(1, P_NTSC, ntsc_code, "ntsc");
|
||||
if (s->crt) MK(1, P_CRT, crt_code, "crt");
|
||||
if (deband_active(s)) MK(1, P_DEBAND, deband_code, "deband");
|
||||
#undef MK
|
||||
#undef MKL
|
||||
if (vert) g_vk.DestroyShaderModule(g_dev, vert, NULL);
|
||||
return 0;
|
||||
fail:
|
||||
if (vert) g_vk.DestroyShaderModule(g_dev, vert, NULL);
|
||||
return chain_failed();
|
||||
}
|
||||
|
||||
|
||||
static void barrier(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkImageLayout to,
|
||||
VkPipelineStageFlags src_stage, VkAccessFlags src_access,
|
||||
@@ -681,14 +741,26 @@ static void pass_dual(VkCommandBuffer cmd, VkPipeline p, struct fx_target *dst,
|
||||
static const float FULL_NDC[4] = {-1.0f, -1.0f, 1.0f, 1.0f};
|
||||
#define SET_NDC(pc) memcpy((pc).ndc, FULL_NDC, sizeof(FULL_NDC))
|
||||
|
||||
VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
|
||||
int out_w, int out_h, int *res_w, int *res_h) {
|
||||
struct fx_source_state {
|
||||
VkImageLayout layout;
|
||||
VkPipelineStageFlags stage;
|
||||
VkAccessFlags access;
|
||||
};
|
||||
|
||||
static VkImage effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
|
||||
int out_w, int out_h, int *res_w, int *res_h,
|
||||
VkImageLayout input_layout, const struct fx_settings *frozen,
|
||||
struct fx_source_state *source_state) {
|
||||
struct fx_settings snapshot;
|
||||
const struct fx_settings *s;
|
||||
vkp_effects_sync();
|
||||
pthread_mutex_lock(&g_lock);
|
||||
snapshot = g_cur;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
if (frozen) {
|
||||
snapshot = *frozen;
|
||||
} else {
|
||||
vkp_effects_sync();
|
||||
pthread_mutex_lock(&g_lock);
|
||||
snapshot = g_cur;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
s = &snapshot;
|
||||
*res_w = scene_w; *res_h = scene_h;
|
||||
|
||||
@@ -723,7 +795,7 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
|
||||
effect_count(s) - (fuse_toon_color ? 1 : 0) -
|
||||
(fuse_fxaa_toon ? 1 : 0);
|
||||
|
||||
if ((spatial || nfx) && objects_ensure() == 0 && scene_ensure(scene, scene_w, scene_h) == 0 &&
|
||||
if ((spatial || nfx) && objects_ensure() == 0 && pipelines_ensure(spatial, s) == 0 && scene_ensure(scene, scene_w, scene_h) == 0 &&
|
||||
target_ensure(&g_t[0], cw, ch, FX_TARGET_USAGE, "chain") == 0 && (chain_passes < 2 || target_ensure(&g_t[1], cw, ch, FX_TARGET_USAGE, "chain") == 0) &&
|
||||
(!(spatial == 4 || spatial == 5) || s->sharp_pct == 0 ||
|
||||
target_ensure(&g_mid, cw, ch, FX_SCRATCH_USAGE, "EASU") == 0)) {
|
||||
@@ -748,8 +820,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 +883,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 +899,10 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
|
||||
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT);
|
||||
cur = dst; cur_ds = dst->ds;
|
||||
} else {
|
||||
barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
|
||||
if (source_state) *source_state = (struct fx_source_state){VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT};
|
||||
barrier(cmd, scene, input_layout, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_WRITE_BIT,
|
||||
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT);
|
||||
cur = NULL; cur_ds = g_scene.ds;
|
||||
}
|
||||
@@ -907,8 +985,54 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
|
||||
return scene;
|
||||
}
|
||||
|
||||
barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
|
||||
if (source_state) *source_state = (struct fx_source_state){VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT};
|
||||
barrier(cmd, scene, input_layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_WRITE_BIT,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);
|
||||
return scene;
|
||||
}
|
||||
|
||||
VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
|
||||
int out_w, int out_h, int *res_w, int *res_h) {
|
||||
return effects_run(cmd, scene, scene_w, scene_h, out_w, out_h, res_w, res_h,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, NULL, NULL);
|
||||
}
|
||||
|
||||
int vkp_effects_prepare_generated(void) {
|
||||
vkp_effects_sync();
|
||||
pthread_mutex_lock(&g_lock);
|
||||
g_generated_settings = g_cur;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
return spatial_mode(g_generated_settings.scaling) && g_generated_settings.scaling != 6 &&
|
||||
effect_count(&g_generated_settings) == 0;
|
||||
}
|
||||
|
||||
VkImage vkp_effects_run_before_generated(VkCommandBuffer cmd, VkImage scene, int w, int h,
|
||||
int *res_w, int *res_h) {
|
||||
struct fx_settings settings = g_generated_settings;
|
||||
settings.scaling = 0;
|
||||
return effects_run(cmd, scene, w, h, w, h, res_w, res_h,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &settings, NULL);
|
||||
}
|
||||
|
||||
VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
|
||||
int out_w, int out_h, int slot, int *res_w, int *res_h) {
|
||||
if (slot < 0 || slot > VKP_FG_MAX_GENERATIONS) {
|
||||
*res_w = scene_w; *res_h = scene_h;
|
||||
return scene;
|
||||
}
|
||||
g_context = slot + 1;
|
||||
struct fx_source_state source_state = {0};
|
||||
VkImage result = effects_run(cmd, scene, scene_w, scene_h, out_w, out_h, res_w, res_h,
|
||||
VK_IMAGE_LAYOUT_GENERAL, &g_generated_settings, &source_state);
|
||||
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);
|
||||
if (result != scene)
|
||||
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);
|
||||
g_context = 0;
|
||||
return result;
|
||||
}
|
||||
@@ -18,6 +18,12 @@ VkFilter vkp_effects_blit_filter(void);
|
||||
|
||||
VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
|
||||
int out_w, int out_h, int *res_w, int *res_h);
|
||||
int vkp_effects_prepare_generated(void);
|
||||
void vkp_effects_release_generated_sources(void);
|
||||
VkImage vkp_effects_run_before_generated(VkCommandBuffer cmd, VkImage scene, int w, int h,
|
||||
int *res_w, int *res_h);
|
||||
VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
|
||||
int out_w, int out_h, int slot, int *res_w, int *res_h);
|
||||
|
||||
void vkp_effects_destroy(void);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "framegen_bridge.h"
|
||||
#include "framegen_engine.h"
|
||||
#include "effects_chain.h"
|
||||
#include "vk_loader.h"
|
||||
#include <pthread.h>
|
||||
#include <stdatomic.h>
|
||||
@@ -226,7 +227,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]));
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ bool g_probed = false, g_ready = false;
|
||||
|
||||
std::unique_ptr<lsfg::Engine> g_lsfg;
|
||||
std::unique_ptr<ddfg::Engine> g_ddfg;
|
||||
std::vector<std::unique_ptr<ddfg::Engine>> g_retained_ddfg;
|
||||
int g_kind = -1;
|
||||
char g_build[96] = "";
|
||||
|
||||
@@ -128,7 +129,14 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica
|
||||
|
||||
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;
|
||||
@@ -193,9 +201,21 @@ 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);
|
||||
g_lsfg.reset();
|
||||
g_ddfg.reset();
|
||||
if (g_lsfg) {
|
||||
if (g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev);
|
||||
g_lsfg.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));
|
||||
}
|
||||
}
|
||||
g_kind = -1;
|
||||
}
|
||||
|
||||
|
||||
@@ -187,6 +187,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;
|
||||
@@ -721,9 +723,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;
|
||||
@@ -998,19 +1006,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 +1049,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;
|
||||
}
|
||||
|
||||
@@ -1209,17 +1239,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 +1260,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();
|
||||
|
||||
@@ -22,7 +22,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,
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
#include <linux/sync_file.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <time.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
@@ -2759,6 +2761,21 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
pass_n = 1;
|
||||
overlay_start = source_end;
|
||||
}
|
||||
const int upscale_w = (int)(scene_w * g_map.kx + 0.5f);
|
||||
const int upscale_h = (int)(scene_h * g_map.ky + 0.5f);
|
||||
const int post_upscale = fx && fg && !hf && !cb && vkp_effects_upscaling() &&
|
||||
vkp_effects_prepare_generated() &&
|
||||
(upscale_w > input_w || upscale_h > input_h);
|
||||
if (post_upscale) {
|
||||
static int last_input_w, last_input_h, last_output_w, last_output_h;
|
||||
if (input_w != last_input_w || input_h != last_input_h ||
|
||||
upscale_w != last_output_w || upscale_h != last_output_h) {
|
||||
droiddeck_log("framegen", "post-upscale: interpolate %dx%d, spatial filter each present to %dx%d",
|
||||
input_w, input_h, upscale_w, upscale_h);
|
||||
last_input_w = input_w; last_input_h = input_h;
|
||||
last_output_w = upscale_w; last_output_h = upscale_h;
|
||||
}
|
||||
}
|
||||
const int deep = hf && n > 0 && fg && g_swap_is_hdr && !hf->tonemap && vkp_framegen_format_ok(FG_HDR_FMT) &&
|
||||
ensure_img(&g_fgscene, scene_w, scene_h, FG_HDR_FMT,
|
||||
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
|
||||
@@ -2894,8 +2911,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);
|
||||
@@ -2918,7 +2938,12 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
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);
|
||||
|
||||
@@ -2942,7 +2967,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);
|
||||
@@ -2988,6 +3018,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
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;
|
||||
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 +3164,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 +3208,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;
|
||||
|
||||
@@ -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]);
|
||||
|
||||
@@ -68,6 +68,7 @@ static jmethodID g_on_compositor_frame;
|
||||
static jmethodID g_on_game_program;
|
||||
static jmethodID g_on_pointer_lock;
|
||||
static jmethodID g_on_clipboard;
|
||||
static jmethodID g_on_text_input_fallback;
|
||||
static jmethodID g_on_text_input;
|
||||
static jmethodID g_on_overlay_planes;
|
||||
static jmethodID g_on_refresh_target;
|
||||
@@ -92,6 +93,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
|
||||
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; }
|
||||
g_on_pointer_lock = (*env)->GetStaticMethodID(env, g_compositor_cls, "onPointerLock", "(ZII)V");
|
||||
g_on_clipboard = (*env)->GetStaticMethodID(env, g_compositor_cls, "onClipboardText", "([B)V");
|
||||
g_on_text_input_fallback = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInputFallback",
|
||||
"([BI)Z");
|
||||
g_on_text_input = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInput",
|
||||
"(ZLjava/lang/String;IIII)V");
|
||||
g_on_overlay_planes = (*env)->GetStaticMethodID(env, g_compositor_cls, "onOverlayPlanes", "(I)V");
|
||||
@@ -203,6 +206,20 @@ void droiddeck_on_clipboard_text(const char *utf8, int len) {
|
||||
(*env)->DeleteLocalRef(env, arr);
|
||||
}
|
||||
|
||||
int droiddeck_on_text_input_fallback(const char *utf8, int len, int token) {
|
||||
JNIEnv *env;
|
||||
if (len <= 0 || token <= 0 || !utf8 || !g_compositor_cls || !g_on_text_input_fallback || !(env = thread_env()))
|
||||
return 0;
|
||||
jbyteArray arr = (*env)->NewByteArray(env, len);
|
||||
if (!arr) { (*env)->ExceptionClear(env); return 0; }
|
||||
(*env)->SetByteArrayRegion(env, arr, 0, len, (const jbyte *)utf8);
|
||||
jboolean accepted = (*env)->CallStaticBooleanMethod(env, g_compositor_cls, g_on_text_input_fallback, arr,
|
||||
(jint)token);
|
||||
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); accepted = JNI_FALSE; }
|
||||
(*env)->DeleteLocalRef(env, arr);
|
||||
return accepted == JNI_TRUE ? 1 : 0;
|
||||
}
|
||||
|
||||
void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h) {
|
||||
JNIEnv *env;
|
||||
if (!g_compositor_cls || !g_on_text_input || !(env = thread_env())) return;
|
||||
@@ -376,6 +393,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey(
|
||||
droiddeck_wayland_send_key(evdev, state);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKeyOrdered(
|
||||
JNIEnv *env, jclass clazz, jint evdev, jint state) {
|
||||
droiddeck_host_key(evdev, state);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSelectGameField(
|
||||
JNIEnv *env, jclass clazz, jboolean copy) {
|
||||
droiddeck_host_select_game_field(copy);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFocusTakesTouch(
|
||||
JNIEnv *env, jclass clazz) {
|
||||
@@ -807,6 +836,15 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommit(JNIE
|
||||
free(buf);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommitAndSubmit(
|
||||
JNIEnv *env, jclass clazz, jbyteArray utf8) {
|
||||
int len;
|
||||
char *buf = dup_bytes(env, utf8, &len);
|
||||
if (buf && len) droiddeck_host_text_commit_and_submit(buf, len);
|
||||
free(buf);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputPreedit(JNIEnv *env, jclass clazz, jbyteArray utf8,
|
||||
jint cursorBegin, jint cursorEnd) {
|
||||
@@ -821,6 +859,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIE
|
||||
droiddeck_host_text_delete(before, after);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompleteTextInputFallback(
|
||||
JNIEnv *env, jclass clazz, jint token, jint result) {
|
||||
droiddeck_host_text_input_fallback_complete(token, result);
|
||||
}
|
||||
|
||||
extern void adrenotools_set_turbo(bool turbo);
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,6 +193,7 @@ 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<String?>(null)
|
||||
@@ -206,6 +208,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("")
|
||||
@@ -1371,6 +1379,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 +1411,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 +1494,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,
|
||||
@@ -1807,6 +1835,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 +2163,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 +2247,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 +2256,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<Int, Boolean>()
|
||||
private val rightStickScrollHandler = android.os.Handler(android.os.Looper.getMainLooper())
|
||||
private var rightStickScrollDeviceId = -1
|
||||
@@ -2264,7 +2320,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) {
|
||||
@@ -2457,6 +2516,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
launchCoordinator.cancelAll()
|
||||
cancelCompatLaunch()
|
||||
updates.unregister()
|
||||
frost.stop()
|
||||
runCatching { unregisterReceiver(shortcutsInstallStatus) }
|
||||
super.onDestroy()
|
||||
}
|
||||
@@ -3046,7 +3106,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 +3123,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 ->
|
||||
@@ -3381,6 +3442,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()
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -76,6 +76,7 @@ import com.droiddeck.launcher.input.InputSpace
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.input.SessionClipboard
|
||||
import com.droiddeck.launcher.input.SessionTextInput
|
||||
import com.droiddeck.launcher.input.OnScreenControls
|
||||
import com.droiddeck.launcher.input.OnScreenLayout
|
||||
import com.droiddeck.launcher.input.InputRouter
|
||||
@@ -162,7 +163,8 @@ import kotlin.math.abs
|
||||
private const val SCREEN_EFFECTS_TARGET_AUTO = "auto"
|
||||
private const val SCREEN_EFFECTS_TARGET_GLOBAL = "global"
|
||||
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost {
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost,
|
||||
com.droiddeck.launcher.session.xr.XrMenuHost {
|
||||
override fun attachBaseContext(newBase: android.content.Context) {
|
||||
super.attachBaseContext(newBase)
|
||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||
@@ -348,6 +350,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 +553,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 +572,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)
|
||||
@@ -807,6 +821,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
private var isHomeApp by mutableStateOf(false)
|
||||
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
|
||||
private var padConnected by mutableStateOf(false)
|
||||
|
||||
private val deviceListener = object : InputManager.InputDeviceListener {
|
||||
override fun onInputDeviceAdded(deviceId: Int) {
|
||||
@@ -849,6 +864,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() ||
|
||||
@@ -987,7 +1003,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
root.addView(controls)
|
||||
}
|
||||
keyboard = KeyboardHost(this).also { host ->
|
||||
keyboard = KeyboardHost(this, sendKeyEvent = ::dispatchImeKeyEvent, sendText = WaylandCompositor::textInputCommit).also { host ->
|
||||
host.onImeChanged = ::onPrimaryImeChanged
|
||||
root.addView(host)
|
||||
}
|
||||
@@ -1192,7 +1208,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 +1278,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
glasses.usesSpatialControllers(glassesSettings) && glassesSettings.joyConTracking)
|
||||
joyConVr?.let { { it.recenter() } } else null,
|
||||
) { headTracker?.recenter() }
|
||||
if (!phonePanel && glasses.present && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot,
|
||||
val showGlassesShortcut = com.droiddeck.launcher.ui.rememberShowGlassesShortcut()
|
||||
if (!phonePanel && glasses.present && showGlassesShortcut && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot,
|
||||
controllerSettings?.tint ?: android.graphics.Color.rgb(90, 160, 255), controllerSettings?.opacity ?: 100) {
|
||||
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.GLASSES
|
||||
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.VR
|
||||
drawerOpen = true
|
||||
}
|
||||
if (!drawerOpen && !pcKeyboardOpen && !loading.visible) {
|
||||
com.droiddeck.launcher.ui.DrawerEntryHint(SessionState.mode == SessionService.MODE_STEAM, backActionsInverted) { drawerOpen = true }
|
||||
if (cornerTap) com.droiddeck.launcher.ui.DrawerCornerTap { drawerOpen = true }
|
||||
if (com.droiddeck.launcher.session.QuestExperimental.isSupported())
|
||||
com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() }
|
||||
}
|
||||
if (loading.visible) LoadingOverlay(
|
||||
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
|
||||
@@ -1451,7 +1470,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 +1492,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 +1547,70 @@ 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<Int, Int>? = 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 {
|
||||
com.droiddeck.launcher.input.KeyboardHost(this) { event ->
|
||||
CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) &&
|
||||
com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) }
|
||||
}
|
||||
}
|
||||
|
||||
@androidx.compose.runtime.Composable
|
||||
private fun SessionMenu(
|
||||
docked: Boolean,
|
||||
@@ -1787,7 +1875,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
onBlackFrameInsertion = { on ->
|
||||
SessionPrefs.setBlackFrameInsertion(this@SessionActivity, on)
|
||||
blackFrameInsertion = on
|
||||
CompositorHost.setBlackFrameInsertion(on, refreshHz(), outputFpsLimit())
|
||||
CompositorHost.setBlackFrameInsertion(on, refreshHz(), compositorFpsLimit())
|
||||
},
|
||||
hdr = hdrWanted,
|
||||
hdrAvailable = hdrAvailable,
|
||||
@@ -1824,7 +1912,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
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 +1989,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 +2035,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)
|
||||
},
|
||||
@@ -1992,18 +2088,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 +2185,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 +2224,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 +2234,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()
|
||||
}
|
||||
|
||||
@@ -2724,7 +2831,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)
|
||||
@@ -2987,12 +3094,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
|
||||
}
|
||||
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId")
|
||||
val outputRefresh = refreshHz(holder)
|
||||
CompositorHost.startOrAttach(
|
||||
this, holder.surface, runtimeDir.path,
|
||||
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
|
||||
applicationInfo.nativeLibraryDir, size.first, size.second, outputRefresh, outputFpsLimit(),
|
||||
outputFrameRateVote(outputRefresh),
|
||||
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), compositorFpsLimit(),
|
||||
)
|
||||
onOutputAttached(holder)
|
||||
if (SessionState.running && size != previous) {
|
||||
@@ -3034,6 +3139,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
|
||||
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 ->
|
||||
@@ -3047,9 +3156,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<Int, Int>): Pair<Int, Int> {
|
||||
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<Int, Int>) {
|
||||
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
|
||||
@@ -3058,7 +3196,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 }
|
||||
@@ -3067,7 +3205,7 @@ 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
|
||||
}
|
||||
|
||||
@@ -3130,13 +3268,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<Int, Int> =
|
||||
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 &&
|
||||
@@ -3183,6 +3321,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)
|
||||
|
||||
@@ -3202,9 +3352,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
}
|
||||
|
||||
private fun outputFrameRateVote(hz: Float): Float =
|
||||
if (glassesScreen == null && !bottomOutputActive && !panelHeld) PerfMode.frameRateVote(this, hz) else hz
|
||||
|
||||
private fun applyOutputPacing() {
|
||||
val frameGen = appliedFrameGenMode
|
||||
pacedFrameGenMode = frameGen
|
||||
@@ -3223,7 +3370,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(), outputFrameRateVote(hz))
|
||||
CompositorHost.updatePacing(hz, compositorFpsLimit())
|
||||
pushCardboard(activeCardboard)
|
||||
if (changed && ::surfaceView.isInitialized) applyFrameGen()
|
||||
}
|
||||
@@ -3660,16 +3807,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
internal fun dispatchImeKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = true)
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = false)
|
||||
|
||||
private fun dispatchKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
|
||||
val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event)
|
||||
if (normalized === event) return dispatchSessionKeyEvent(event)
|
||||
if (normalized === event) return dispatchSessionKeyEvent(event, orderedImeKey)
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}")
|
||||
}
|
||||
return dispatchSessionKeyEvent(normalized)
|
||||
return dispatchSessionKeyEvent(normalized, orderedImeKey)
|
||||
}
|
||||
|
||||
private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean {
|
||||
private fun dispatchSessionKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
|
||||
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
|
||||
@@ -3752,7 +3903,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)
|
||||
@@ -3794,7 +3945,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()
|
||||
}
|
||||
@@ -3835,7 +3986,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)
|
||||
}
|
||||
@@ -4950,6 +5101,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
private fun refreshControls() {
|
||||
padConnected = controllerConnected()
|
||||
applyUnfoldedControls()
|
||||
updateOnScreenControls()
|
||||
}
|
||||
@@ -5128,27 +5280,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
|
||||
@@ -5157,7 +5301,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (text != null && stillOpen()) endGameField()
|
||||
done(text)
|
||||
}
|
||||
selectGameField(KEY_C)
|
||||
selectGameField(copy = true)
|
||||
}
|
||||
|
||||
private fun cancelWowChat() {
|
||||
@@ -6060,11 +6204,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 = {}) {
|
||||
@@ -6132,7 +6281,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)
|
||||
@@ -6247,6 +6396,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
heldButtons.clear()
|
||||
hidePrimaryKeyboard()
|
||||
sessionClipboard.stop()
|
||||
sessionTextInput.stop()
|
||||
padMotion?.stop()
|
||||
cursorVisible = false
|
||||
closeSecondScreen(reset = false)
|
||||
@@ -6262,7 +6412,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()
|
||||
@@ -6333,6 +6483,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
|
||||
contentResolver.unregisterContentObserver(refreshSettingObserver)
|
||||
if (!screenIsOff()) closeSecondScreen(reset = false)
|
||||
sessionTextInput.stop()
|
||||
startedScreens = (startedScreens - 1).coerceAtLeast(0)
|
||||
updateGlassesScreen()
|
||||
updateBottomGame()
|
||||
@@ -6390,6 +6541,7 @@ 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()
|
||||
@@ -6411,7 +6563,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)
|
||||
@@ -7128,6 +7280,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) {
|
||||
@@ -7140,6 +7294,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)
|
||||
@@ -7252,6 +7407,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"
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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<Pair<Step, List<String>>>()
|
||||
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))
|
||||
|
||||
@@ -216,7 +240,7 @@ object AgentSetup {
|
||||
detail.clear()
|
||||
}
|
||||
|
||||
private fun probe(app: Context, harness: AgentHarness, step: Step, command: List<String>) {
|
||||
private fun probe(app: Context, harness: AgentHarness, step: Step, command: List<String>, generation: Int) {
|
||||
var output = ""
|
||||
val ok = runCatching {
|
||||
val child = AgentHost.guest(app, command, connectAdb = step == Step.CONNECTION).start()
|
||||
@@ -232,11 +256,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()
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<String> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +61,19 @@ object GameEnvironment {
|
||||
}
|
||||
|
||||
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
|
||||
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
|
||||
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else knownGames[scope].orEmpty() + config.games[scope].orEmpty()
|
||||
|
||||
/**
|
||||
* What some Steam games need here whatever the shared settings say; the game's own settings still win.
|
||||
* GTA III dies at 0042A703 when a new game starts with FEX's reduced x87 precision, as the Rockstar store copy does.
|
||||
*/
|
||||
val knownGames: Map<String, Map<String, String?>> = mapOf(
|
||||
"12100" to mapOf("FEX_X87REDUCEDPRECISION" to "0"),
|
||||
)
|
||||
|
||||
/** [config] with [knownGames] folded under each game's own settings, for the guest to read. */
|
||||
fun withKnownGames(config: Config): Config =
|
||||
config.copy(games = config.games + knownGames.mapValues { (scope, known) -> known + config.games[scope].orEmpty() })
|
||||
|
||||
fun hasOverride(config: Config, scope: String, name: String): Boolean =
|
||||
scope.isNotEmpty() && config.entries(scope).containsKey(name)
|
||||
@@ -78,7 +90,7 @@ object GameEnvironment {
|
||||
val entries = config.games[scope].orEmpty()
|
||||
if (FexPreset.environmentKeys.none(entries::containsKey)) return null
|
||||
return FexPreset.all.firstOrNull { preset ->
|
||||
val expected = FexPreset.environment(preset.id)
|
||||
val expected = presetFor(scope, preset.id)
|
||||
FexPreset.environmentKeys.all { key -> entries.containsKey(key) && entries[key] == expected[key] }
|
||||
}?.id ?: CUSTOM_FEX_PRESET
|
||||
}
|
||||
@@ -88,12 +100,16 @@ object GameEnvironment {
|
||||
require(preset == null || FexPreset.all.any { it.id == preset })
|
||||
val entries = config.entries(scope).filterKeys { it !in FexPreset.environmentKeys }.toMutableMap()
|
||||
if (preset != null) {
|
||||
val values = FexPreset.environment(preset)
|
||||
val values = presetFor(scope, preset)
|
||||
FexPreset.environmentKeys.forEach { key -> entries[key] = values[key] }
|
||||
}
|
||||
return config.withEntries(scope, entries)
|
||||
}
|
||||
|
||||
/** A FEX preset as a game gets it: picking one never undoes a fix the game is known to need. */
|
||||
private fun presetFor(scope: String, preset: String): Map<String, String?> =
|
||||
FexPreset.environment(preset) + knownGames[scope].orEmpty().filterKeys { it in FexPreset.environmentKeys }
|
||||
|
||||
const val CUSTOM_FEX_PRESET = "__custom__"
|
||||
|
||||
val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?,
|
||||
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")
|
||||
|
||||
@@ -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)"
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Int, Boolean>()
|
||||
|
||||
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'
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,986 @@
|
||||
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 com.droiddeck.launcher.core.DeviceReport
|
||||
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()
|
||||
reply?.writeInt(Process.myPid())
|
||||
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<String>, env: Array<String>, fds: List<ParcelFileDescriptor?>, 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<Int, Int> {
|
||||
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<ParcelFileDescriptor>()
|
||||
|
||||
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<Class<out GuestWorker>> = 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<Slot>(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<Slot>()
|
||||
@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 =
|
||||
android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.session.SessionPrefs.childProcessHandoff(context) &&
|
||||
NativeGuest.enabled(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 && enabled(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<String>, env: List<String>, stdio: List<ParcelFileDescriptor>, 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<String>, env: List<String>, fds: List<ParcelFileDescriptor>, 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<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
|
||||
guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true },
|
||||
confirmed: () -> Boolean = { true }, owner: Int = session,
|
||||
nice: Int = Process.getThreadPriority(Process.myTid())): 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<ParcelFileDescriptor>? = 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)
|
||||
slot.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()
|
||||
// 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) {
|
||||
!stopping() && confirmed() && 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, slot.session > stopped)) }, "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, running: Boolean): Int {
|
||||
if (pid <= 0 || android.os.Build.VERSION.SDK_INT < 30) return -1
|
||||
val am = app.getSystemService(ActivityManager::class.java)
|
||||
var record: android.app.ApplicationExitInfo? = null
|
||||
fun killed(status: Int): Int {
|
||||
if (running) record?.let {
|
||||
Log.w(TAG, "worker pid $pid ended: " + DeviceReport.exitSummary(it.processName, it.reason, it.status, it.description))
|
||||
}
|
||||
return status
|
||||
}
|
||||
repeat(20) {
|
||||
am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let {
|
||||
record = it
|
||||
// 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 killed(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 killed(OsConstants.SIGKILL)
|
||||
}
|
||||
Thread.sleep(50)
|
||||
}
|
||||
// killed by Android with no signal recorded, not a clean exit
|
||||
return if (record != null) killed(OsConstants.SIGKILL) else -1
|
||||
}
|
||||
|
||||
/** The pids of session [of]'s guest programs running in workers. */
|
||||
fun guestPids(of: Int = session): List<Int> =
|
||||
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) } }
|
||||
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<ParcelFileDescriptor>()
|
||||
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<String, String>()
|
||||
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 pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, nice = nice, onExit = { code ->
|
||||
status = code
|
||||
if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker)
|
||||
exited.countDown()
|
||||
}, confirmed = {
|
||||
!ack || runCatching {
|
||||
out.write("ok\n".toByteArray())
|
||||
out.flush()
|
||||
confirmedToHook = true
|
||||
}.isSuccess
|
||||
}, 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)
|
||||
})
|
||||
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() }
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -112,8 +112,9 @@ object NativeGuest {
|
||||
File(BwrapSpawner.hostPath(binds.map { BwrapSpawner.Bind.parse(it) }, root.path, cwd)).takeIf { it.isDirectory } ?: root
|
||||
|
||||
/** A process for [guest] (argv) started as proot would with [binds], in guest directory [cwd]. */
|
||||
fun processBuilder(context: Context, root: File, binds: List<String>, guest: List<String>, cwd: String = "/root"): ProcessBuilder =
|
||||
ProcessBuilder(command(root, guest.first(), guest.drop(1)))
|
||||
fun processBuilder(context: Context, root: File, binds: List<String>, guest: List<String>, cwd: String = "/root"): ProcessBuilder {
|
||||
if (sessionMode == null) prepare(context, root)
|
||||
return ProcessBuilder(command(root, guest.first(), guest.drop(1)))
|
||||
.directory(workingDirectory(root, binds, cwd))
|
||||
.also { builder ->
|
||||
builder.environment().apply {
|
||||
@@ -121,6 +122,7 @@ object NativeGuest {
|
||||
putAll(sessionEnvironment(root, binds, guest.first(), SessionPrefs.guestHostname(context)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val RUNPATH_CONF = "etc/ld.so.conf.d/zz-droiddeck-native.conf"
|
||||
private val SCAN_DIRS = listOf("usr/lib", "usr/local/lib", "opt")
|
||||
@@ -149,6 +151,7 @@ object NativeGuest {
|
||||
}
|
||||
|
||||
/** What a rootfs needs before anything runs in it natively; cheap once done. */
|
||||
@Synchronized
|
||||
fun prepare(context: Context, root: File) {
|
||||
val relinked = relinkAbsoluteSymlinks(context, root)
|
||||
if (relinked > 0) android.util.Log.i(TAG, "native userland: $relinked absolute symlinks made relative")
|
||||
|
||||
@@ -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) } })
|
||||
}
|
||||
|
||||
|
||||
@@ -114,7 +114,7 @@ object GameEnvironmentStore {
|
||||
) {
|
||||
publishGameCores(context)
|
||||
val stored = config ?: read(context)
|
||||
val resolved = stored.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
|
||||
val resolved = GameEnvironment.withKnownGames(stored).copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
|
||||
val json = encode(resolved)
|
||||
val dxvk = TextureFiltering.dxvkOptions(
|
||||
SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context),
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -82,16 +82,6 @@ object PerfMode {
|
||||
internal fun panelHeld(requestedHz: Float, activeHz: Float): Boolean =
|
||||
requestedHz > 1f && activeHz > 1f && Math.abs(requestedHz - activeHz) > 0.5f
|
||||
|
||||
fun frameRateVote(a: Activity, activeHz: Float): Float = try {
|
||||
val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay
|
||||
val wanted = a.window.attributes.preferredDisplayModeId
|
||||
val requested = display?.supportedModes?.firstOrNull { wanted != 0 && it.modeId == wanted }
|
||||
frameRateVote(requested?.refreshRate ?: 0f, activeHz)
|
||||
} catch (t: Throwable) { Log.w(TAG, "frame rate vote", t); activeHz }
|
||||
|
||||
internal fun frameRateVote(requestedHz: Float, activeHz: Float): Float =
|
||||
requestedHz.takeIf { it > 1f } ?: activeHz
|
||||
|
||||
fun pacedRate(ownLimit: Int, limiterRate: Int, limiterRefresh: Int, steadyRate: Int): Int = when {
|
||||
ownLimit > 0 -> ownLimit
|
||||
limiterRate <= 0 -> steadyRate
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
import com.droiddeck.launcher.runtime.LegacyNames
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
object SessionFiles {
|
||||
@@ -21,6 +22,8 @@ object SessionFiles {
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
|
||||
private const val STAGED_LEDGER = "usr/local/.droiddeck-staged"
|
||||
private const val IME_MANIFEST = "usr/local/share/droiddeck/ime-files.json"
|
||||
private const val IME_DEFAULT_MODE = 420
|
||||
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
|
||||
|
||||
internal val DESKTOP_FILES = arrayOf(
|
||||
@@ -35,6 +38,7 @@ object SessionFiles {
|
||||
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
|
||||
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
|
||||
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
|
||||
"usr/share/applications/droiddeck-return-gaming.desktop" to "usr/share/applications/droiddeck-return-gaming.desktop",
|
||||
"etc/xdg/fastfetch/config.jsonc" to "etc/xdg/fastfetch/config.jsonc",
|
||||
)
|
||||
|
||||
@@ -129,7 +133,11 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-agent" to "usr/local/bin/droiddeck-agent",
|
||||
"usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility",
|
||||
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
|
||||
"usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn",
|
||||
"usr/local/bin/droiddeck-log-writer" to "usr/local/bin/droiddeck-log-writer",
|
||||
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
|
||||
"usr/local/bin/droiddeck-text-input" to "usr/local/bin/droiddeck-text-input",
|
||||
"usr/local/bin/droiddeck-steam-ime" to "usr/local/bin/droiddeck-steam-ime",
|
||||
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
|
||||
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
|
||||
"usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply",
|
||||
@@ -153,6 +161,7 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
|
||||
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
|
||||
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
|
||||
"usr/local/bin/droiddeck-user" to "usr/local/bin/droiddeck-user",
|
||||
"usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text",
|
||||
"usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd",
|
||||
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
|
||||
@@ -331,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")
|
||||
@@ -357,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")
|
||||
@@ -416,6 +427,42 @@ object SessionFiles {
|
||||
seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
|
||||
}
|
||||
|
||||
private fun stageImeFiles(context: Context, root: File, ledger: StageLedger) {
|
||||
val entries = LinkedHashMap<String, Int>()
|
||||
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
|
||||
@@ -879,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 = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<policy context="default">
|
||||
<allow user="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
"""
|
||||
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() }
|
||||
|
||||
@@ -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) {
|
||||
@@ -493,6 +552,17 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply()
|
||||
}
|
||||
|
||||
fun drawerSections(context: Context): Map<String, Boolean> =
|
||||
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<String, Boolean>) {
|
||||
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<String>) {
|
||||
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
|
||||
}
|
||||
@@ -1100,10 +1170,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) {
|
||||
@@ -1794,10 +1874,10 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean(hdrKey(mode), on).apply()
|
||||
}
|
||||
|
||||
fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.$mode", true)
|
||||
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 +1887,15 @@ object SessionPrefs {
|
||||
|
||||
const val PIP_FPS = 30
|
||||
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false): Int {
|
||||
val limit = when {
|
||||
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
|
||||
mirrorRefreshLimit <= 0 -> sessionLimit
|
||||
sessionLimit <= 0 -> mirrorRefreshLimit
|
||||
else -> minOf(mirrorRefreshLimit, sessionLimit)
|
||||
}
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false, hostCap: Int = 0): Int {
|
||||
val limit = listOf(mirrorRefreshLimit, sessionLimit, hostCap).filter { it > 0 }.minOrNull() ?: FPS_UNPACED
|
||||
return if (pip && mirrorRefreshLimit <= 0 && (limit <= 0 || limit > PIP_FPS)) PIP_FPS else limit
|
||||
}
|
||||
|
||||
/** The per-app rate Android holds this window to (Game Mode's FPS override), or 0 when the panel's rate applies. */
|
||||
fun hostFrameCap(overrideHz: Float, panelHz: Float): Int =
|
||||
if (overrideHz > 1f && panelHz - overrideHz > 1f) Math.round(overrideHz) else 0
|
||||
|
||||
val upscalerChoices = listOf(
|
||||
2 to "Nearest", 0 to "Linear", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
|
||||
8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only",
|
||||
@@ -2117,6 +2196,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) {
|
||||
|
||||
@@ -661,7 +661,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 +705,25 @@ 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)) {
|
||||
// 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 (ownWorkers > 0) {
|
||||
guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
|
||||
guest.add("DD_SPAWN_SESSION=$ownWorkers")
|
||||
}
|
||||
}
|
||||
// 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")
|
||||
@@ -863,10 +878,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 +897,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)
|
||||
@@ -1535,10 +1559,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)
|
||||
@@ -1555,6 +1584,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() {
|
||||
@@ -1729,6 +1759,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(
|
||||
@@ -2325,12 +2356,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))
|
||||
@@ -2391,7 +2426,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)
|
||||
@@ -2400,6 +2436,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()
|
||||
|
||||
@@ -12,13 +12,13 @@ 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", "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",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<XrHand>) {
|
||||
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<XrHaptic>(2)
|
||||
var orb: Orb? = null
|
||||
val layers = mutableListOf<XrLayerOut>()
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<XrPointerEvent>()
|
||||
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<XrPanelState, MutableList<Pair<Float, Float>>>()
|
||||
|
||||
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>(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<XrHand>, panels: List<XrPanelState>, 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<XrPanelState>, 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
|
||||
}
|
||||
}
|
||||
@@ -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<EditCommand>) -> 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<String> =
|
||||
(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<Int>()
|
||||
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) }
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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<List<Pair<Float, Float>>>,
|
||||
buttons: List<XrPanelButton>,
|
||||
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<State<List<Pair<Float, Float>>>?> { 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<Modifier, State<Boolean>> {
|
||||
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
|
||||
@@ -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<Int, Pair<Float, Float>>()
|
||||
private var hovering: View? = null
|
||||
private var hoverAt = 0f to 0f
|
||||
private var cursor: Pair<Float, Float>? = 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<Float, Float>?) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<XrMenuHost>? = null
|
||||
private var scope: CoroutineScope? = null
|
||||
|
||||
private class Panel(val state: XrPanelState, val content: @Composable (State<List<Pair<Float, Float>>>) -> Unit) {
|
||||
val cursorState = mutableStateOf<List<Pair<Float, Float>>>(emptyList())
|
||||
var layerId = -1
|
||||
var window: XrPanelWindow? = null
|
||||
var openedMs = 0L
|
||||
var closingMs = 0L
|
||||
var resizing = false
|
||||
var cursor: List<Pair<Float, Float>> = emptyList()
|
||||
}
|
||||
|
||||
private val panels = mutableListOf<Panel>()
|
||||
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<TypingRequest?>(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<List<Pair<Float, Float>>>) -> 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<Panel>()
|
||||
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<Float, Float, Float> {
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -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<Long>?): Boolean {
|
||||
val apps = (listOfNotNull(focusedApp) + focusableApps.orEmpty()).filter { it > 0 }
|
||||
return apps.isNotEmpty() && apps.all { it in STEAM_APPS }
|
||||
}
|
||||
}
|
||||
@@ -121,6 +121,8 @@ object StoresState {
|
||||
var unfinished by mutableStateOf<List<StoreInstallRoot.Unfinished>>(emptyList())
|
||||
internal set
|
||||
|
||||
var steamPicking by mutableStateOf<CatalogItem?>(null)
|
||||
|
||||
fun isUnfinished(item: CatalogItem): Boolean = unfinished.any {
|
||||
it.store == item.store && (it.id == item.id || (it.id == null && it.folder.name == StoreInstallRoot.folderName(item.title, item.id)))
|
||||
}
|
||||
|
||||
@@ -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<String> =
|
||||
AddedGames.guestPath(context, StoreInstallRoot.storeDir(root, Store.BATTLENET))?.let { listOf("--library", it) }.orEmpty()
|
||||
fun library(context: Context, root: File? = preferred(context)): List<String> =
|
||||
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) {
|
||||
|
||||
@@ -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 = "")
|
||||
|
||||
@@ -6,9 +6,6 @@ import android.net.Uri
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
@@ -46,8 +43,6 @@ internal object SteamStore {
|
||||
/** InvalidPassword, AccessDenied, AccountNotFound, Revoked, Expired, AccountLogonDenied. */
|
||||
private val REFUSALS = setOf(5, 15, 18, 26, 27, 63)
|
||||
|
||||
var picking by mutableStateOf<CatalogItem?>(null)
|
||||
|
||||
class Plan(val installDir: String, val downloadBytes: Long, val installBytes: Long, val buildId: String, val linuxBuild: Boolean) {
|
||||
companion object {
|
||||
fun of(json: JSONObject): Plan? {
|
||||
@@ -222,7 +217,7 @@ internal object SteamStore {
|
||||
toast(context, R.string.steam_store_close_steam)
|
||||
return
|
||||
}
|
||||
picking = item
|
||||
StoresState.steamPicking = item
|
||||
}
|
||||
|
||||
fun install(context: Context, item: CatalogItem, target: SteamClient.Target) {
|
||||
|
||||
@@ -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<AgentPetHost, () -> 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
|
||||
|
||||
@@ -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<String, String> = 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<St
|
||||
}
|
||||
|
||||
private fun action(step: Step): Int = when (step) {
|
||||
Step.CONNECTION -> 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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<Float, Float> {
|
||||
@@ -102,10 +107,13 @@ internal object QamLayout {
|
||||
fun toCss(x: Float, y: Float, scale: Float, left: Float): Pair<Float, Float> = (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<ImageBitmap?>(null)
|
||||
val shape = mutableStateOf<FloatArray?>(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<CdpPage>(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<String>(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()))
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<String, Boolean>()
|
||||
|
||||
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<DrawerSections?> { 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() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -1,52 +1,236 @@
|
||||
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.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.focus.FocusRequester
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.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,
|
||||
) {
|
||||
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)
|
||||
val need = when {
|
||||
lossless.ready -> null
|
||||
lossless.owned -> stringResource(R.string.lsfg_needs_install)
|
||||
else -> 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 engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG")
|
||||
|
||||
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_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 (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
|
||||
Text(
|
||||
need.orEmpty(),
|
||||
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 " ✓")
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = onImportLossless,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
|
||||
.controllerConfirm(onClick = onImportLossless),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: ""))
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) {
|
||||
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) }
|
||||
|
||||
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) }
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedEngine != null) {
|
||||
val multiplierEnabled = mode.engine != FrameGen.ENGINE_LSFG || lossless.ready
|
||||
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,
|
||||
),
|
||||
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}×") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
),
|
||||
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 (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
|
||||
Text(need.orEmpty(), color = colors.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(top = 6.dp))
|
||||
}
|
||||
|
||||
if (gameProfileId != null) {
|
||||
MenuItem(stringResource(R.string.comp_game_use_general), checked = !hasGameOverride) {
|
||||
onResetGame()
|
||||
host.open = null
|
||||
val resetGame = onResetGame
|
||||
OutlinedButton(
|
||||
onClick = resetGame,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
|
||||
.controllerConfirm(onClick = resetGame),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(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
|
||||
}
|
||||
MenuItem(stringResource(R.string.lsfg_import), checked = false, detail = using) { host.open = null; onImportLossless() }
|
||||
OutlinedButton(
|
||||
onClick = onImportLossless,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
|
||||
.controllerConfirm(onClick = onImportLossless),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: ""))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 = "",
|
||||
@@ -284,6 +290,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 +457,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 +713,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 +795,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<kotlinx.coroutines.Job?>(null) }
|
||||
val stepView = androidx.compose.ui.platform.LocalView.current
|
||||
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
|
||||
if (!processSettingsPageVisible) {
|
||||
val keys = navigationKeys(s)
|
||||
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
|
||||
releaseFocusedTextField(stepView)
|
||||
OpenMenus.leaveAll(withPage = true)
|
||||
PageSwipe.direction = step
|
||||
if (s.dualScreen) { onRailSelect(key); return@let }
|
||||
showRailPage(key, false)
|
||||
@@ -847,7 +870,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
|
||||
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
|
||||
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
|
||||
com.droiddeck.launcher.stores.steam.SteamStore.picking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.steam.SteamStore.picking = null } } }
|
||||
com.droiddeck.launcher.stores.StoresState.steamPicking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.StoresState.steamPicking = null } } }
|
||||
StepsLayer(screenAt)
|
||||
UiZooSheet()
|
||||
SessionDrawerPreview(s.secondScreenDisplays)
|
||||
|
||||
@@ -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<String?>(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, a.onImportLossless, legacyButtons = true)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -819,6 +887,34 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
val steamCard: (@Composable (Modifier) -> Unit)? = if (game != null && steamScope != null) { m ->
|
||||
Box(m) { GameSettingsCard(host, game, steamScope) }
|
||||
} else null
|
||||
val frameGenMenuContent: @Composable () -> Unit = {
|
||||
FrameGenMenu(
|
||||
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
|
||||
lossless = s.lossless,
|
||||
onPick = { mode ->
|
||||
val key = frameGenProfileKey
|
||||
if (key == null) {
|
||||
a.onFrameGenPick(mode)
|
||||
} else {
|
||||
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
|
||||
gameFrameGenMode = mode
|
||||
gameFrameGenOverride = true
|
||||
}
|
||||
},
|
||||
onImportLossless = a.onImportLossless,
|
||||
legacyButtons = true,
|
||||
gameProfileId = frameGenProfileKey,
|
||||
hasGameOverride = gameFrameGenOverride,
|
||||
onResetGame = {
|
||||
val key = frameGenProfileKey
|
||||
if (key != null) {
|
||||
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
|
||||
gameFrameGenMode = com.droiddeck.launcher.gpu.FrameGen.mode(context)
|
||||
gameFrameGenOverride = false
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> {
|
||||
add { m ->
|
||||
val back = stringResource(R.string.hop_from_games)
|
||||
@@ -840,33 +936,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
) {
|
||||
host.open = if (host.open == "fg") null else "fg"
|
||||
}
|
||||
FrameGenMenu(
|
||||
host = host,
|
||||
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
|
||||
lossless = s.lossless,
|
||||
onPick = { mode ->
|
||||
val key = frameGenProfileKey
|
||||
if (key == null) {
|
||||
a.onFrameGenPick(mode)
|
||||
} else {
|
||||
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
|
||||
gameFrameGenMode = mode
|
||||
gameFrameGenOverride = true
|
||||
}
|
||||
},
|
||||
onImportLossless = a.onImportLossless,
|
||||
gameProfileId = frameGenProfileKey,
|
||||
hasGameOverride = gameFrameGenOverride,
|
||||
onResetGame = {
|
||||
val key = frameGenProfileKey
|
||||
if (key != null) {
|
||||
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
|
||||
gameFrameGenMode =
|
||||
com.droiddeck.launcher.gpu.FrameGen.mode(context)
|
||||
gameFrameGenOverride = false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
}
|
||||
}
|
||||
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
|
||||
@@ -898,6 +968,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||
}
|
||||
}
|
||||
if (host.open == "fg") {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 4.dp)) {
|
||||
frameGenMenuContent()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<GlassesState, GlassesSettings> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<HoldButton>()
|
||||
private val artworkDpadBounds = RectF()
|
||||
private var crossDpads = emptyList<Pair<List<HoldButton>, RectF>>()
|
||||
private var requestedLayout = customLayout
|
||||
init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
|
||||
|
||||
@@ -185,6 +187,7 @@ class InputSurfaceView(
|
||||
|
||||
private fun renderCustom(pad: PadBridge?) {
|
||||
artworkDpad = emptyList()
|
||||
crossDpads = emptyList()
|
||||
val canvas = object : ViewGroup(context) {
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
val layout = customLayout
|
||||
@@ -203,6 +206,7 @@ class InputSurfaceView(
|
||||
child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight)
|
||||
}
|
||||
updateArtworkDpad(this)
|
||||
updateCrossDpad(this)
|
||||
}
|
||||
|
||||
override fun dispatchDraw(canvas: Canvas) {
|
||||
@@ -244,11 +248,39 @@ class InputSurfaceView(
|
||||
canvas.getChildAt(index) as? HoldButton
|
||||
}
|
||||
val previous = artworkDpad
|
||||
artworkDpad = if (crossed(buttons)) buttons else emptyList()
|
||||
artworkDpad = if (crossed(buttons, artworkDpadBounds)) buttons else emptyList()
|
||||
if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() }
|
||||
}
|
||||
|
||||
private fun crossed(buttons: List<HoldButton>): Boolean {
|
||||
private fun updateCrossDpad(canvas: ViewGroup) {
|
||||
val buttons = (0 until canvas.childCount).map(canvas::getChildAt).filterIsInstance<HoldButton>()
|
||||
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<HoldButton>): 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<HoldButton>, bounds: RectF): Boolean {
|
||||
if (buttons.size != DIRECTIONS.size) return false
|
||||
val (up, right, down, left) = buttons
|
||||
val centerX = (left.left + right.right) / 2f
|
||||
@@ -258,7 +290,7 @@ class InputSurfaceView(
|
||||
kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f ||
|
||||
kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f ||
|
||||
up.bottom >= down.top || left.right >= right.left) return false
|
||||
artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
|
||||
bounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -284,6 +316,7 @@ class InputSurfaceView(
|
||||
val views = (canvas.childCount - 1 downTo 0).map(canvas::getChildAt).filter { it.visibility == VISIBLE }
|
||||
views.firstOrNull { !(it is StickView && it.adaptive) && hits(it, x, y, 0f) }?.let { return it }
|
||||
views.filter { it is HoldButton && hits(it, x, y, slack(it)) }.minByOrNull { distance(it, x, y) }?.let { return it }
|
||||
crossTarget(x, y)?.let { return it }
|
||||
if (views.any { it is HoldButton && hits(it, x, y, slack(it) + ADAPTIVE_CLEARANCE_PX) }) return null
|
||||
return views.filter { it is StickView && it.adaptive && it !in owners.values && (hits(it, x, y, 0f) || it.captures(x - originX(it), y - originY(it))) }
|
||||
.minByOrNull { distance(it, x, y) }
|
||||
|
||||
@@ -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<Color?> { 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<Boolean> { 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,6 +195,10 @@ internal fun librarySources(
|
||||
}
|
||||
}
|
||||
|
||||
internal fun alwaysLibraryTabs(signedIn: Collection<Store>, stores: Boolean, soundMode: Boolean): Set<String> =
|
||||
(if (soundMode) emptyList() else signedIn.map { it.librarySource }).toSet() +
|
||||
listOfNotNull(Library.ADDED.takeIf { stores }, Store.BATTLENET.id.takeIf { stores })
|
||||
|
||||
internal object LibraryDisplay {
|
||||
const val DEFAULT_LEVEL = 2
|
||||
val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f)
|
||||
@@ -374,7 +378,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
.map { it.store.id }.toSet()
|
||||
val sources = librarySources(
|
||||
all, storeTabs.map { it.store.id },
|
||||
listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.ADDED.takeIf { stores }, Store.BATTLENET.id.takeIf { stores }).toSet() + signInChips,
|
||||
alwaysLibraryTabs(owned.keys, stores, soundMode) + signInChips,
|
||||
favorites, concealed,
|
||||
offStores = if (soundMode) emptySet() else storeTabs.filterNot { it.shown }.map { it.store.id }.toSet(),
|
||||
places = if (soundMode) DEFAULT_LIBRARY_PLACES else StoreTabsState.libraryPlaces,
|
||||
@@ -527,13 +531,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,
|
||||
@@ -559,7 +561,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 {
|
||||
@@ -749,20 +751,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() } }
|
||||
}
|
||||
@@ -904,10 +909,13 @@ private fun LibraryHeader(
|
||||
if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() }
|
||||
}
|
||||
|
||||
private fun sourceChipsShown(sources: List<String>, 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<String>, source: String, onSource: (String) -> Unit, manage: Boolean) {
|
||||
val chips = (manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN
|
||||
val chips = sourceChipsShown(sources, manage)
|
||||
if (!chips && !manage) return
|
||||
val pal = LocalPalette.current
|
||||
val keys = if (chips) listOf(LIBRARY_ALL) + sources else emptyList()
|
||||
|
||||
@@ -116,10 +116,7 @@ internal object NavTabs {
|
||||
|
||||
fun more(s: FrontEndState) = listed(s).filter { place(s, it) == TabPlace.MORE }
|
||||
|
||||
fun bar(s: FrontEndState): List<String> {
|
||||
val shown = listed(s).filter { place(s, it) == TabPlace.BAR }
|
||||
return if (more(s).isEmpty()) shown else shown + MORE
|
||||
}
|
||||
fun bar(s: FrontEndState): List<String> = 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
|
||||
|
||||
Loaded 100 of 346 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user