mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-04 03:55:44 +00:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db0ee92d50 | ||
|
|
f9eeef44ed | ||
|
|
eeb10e02fd | ||
|
|
e935263ccb | ||
|
|
673675b45e | ||
|
|
153c873898 | ||
|
|
cec2e4ed70 | ||
|
|
affb0da37f | ||
|
|
8cf1e60cc2 | ||
|
|
e3faee459f | ||
|
|
20df8b1858 | ||
|
|
4ab9635ceb | ||
|
|
34fff40b56 | ||
|
|
5d05c36033 | ||
|
|
ec281db0d1 | ||
|
|
1a7a116939 |
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
|
||||
|
||||
+36
-120
@@ -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'
|
||||
@@ -221,6 +224,14 @@ jobs:
|
||||
with:
|
||||
path: pa13
|
||||
key: pulseaudio-src-${{ steps.plan.outputs.pulseaudio-source }}
|
||||
- name: Cache proot
|
||||
id: proot
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
app/src/main/jniLibs/arm64-v8a/libproot.so
|
||||
app/src/main/jniLibs/arm64-v8a/libproot-loader.so
|
||||
key: proot-v2-${{ steps.plan.outputs.proot }}
|
||||
- name: Cache GOG Galaxy companion
|
||||
id: comet
|
||||
uses: actions/cache@v4
|
||||
@@ -279,6 +290,10 @@ jobs:
|
||||
- name: Build the AAudio sink into the audio bundle
|
||||
run: python3 tools/components/prepare.py audio
|
||||
|
||||
- name: Build proot
|
||||
if: steps.proot.outputs.cache-hit != 'true'
|
||||
run: python3 tools/components/prepare.py proot
|
||||
|
||||
- name: Build the non-Adreno test additions (Mali bridge client, Venus GL probe, Xclipse layer)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -337,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
|
||||
@@ -495,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
|
||||
@@ -662,6 +661,20 @@ jobs:
|
||||
export NDK="$ANDROID_HOME/ndk/$NDK_VERSION"
|
||||
tools/syncthing/build.sh app/src/main/jniLibs/arm64-v8a
|
||||
|
||||
- name: Check the proot pack pin against this build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# shellcheck disable=SC1091
|
||||
source tools/packs/proot/release.env
|
||||
sha=$(sha256sum app/build/packs/proot.tar.zst | cut -d' ' -f1)
|
||||
size=$(stat -c %s app/build/packs/proot.tar.zst)
|
||||
if [ "$sha" != "$PROOT_PACK_SHA256" ] || [ "$size" != "$PROOT_PACK_SIZE" ]; then
|
||||
level=warning
|
||||
if [ "$GITHUB_EVENT_NAME" = pull_request ]; then level=error; fi
|
||||
echo "::$level::built proot pack $sha ($size bytes) does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256, $PROOT_PACK_SIZE bytes). Source builds download the pinned pack, so set PROOT_PACK_SHA256=$sha and PROOT_PACK_SIZE=$size in tools/packs/proot/release.env."
|
||||
if [ "$level" = error ]; then exit 1; fi
|
||||
fi
|
||||
|
||||
- name: Check out MaliBridge
|
||||
run: git submodule update --init external/MaliBridge
|
||||
- name: Fetch the Mali (Venus) component (tools/venus/release.env)
|
||||
@@ -708,101 +721,6 @@ jobs:
|
||||
if-no-files-found: ignore
|
||||
overwrite: true
|
||||
|
||||
- name: Resolve the Robolectric version
|
||||
id: robolectric
|
||||
run: |
|
||||
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
|
||||
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
|
||||
# The cache path sits beside the workspace because runner homes are at different depths from it, and
|
||||
# actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects
|
||||
# "..". Runners that keep their own ~/.m2 skip the cache.
|
||||
- name: Place Robolectric's Android jars beside the workspace
|
||||
id: robolectric-jars
|
||||
run: |
|
||||
set -euo pipefail
|
||||
jars="$GITHUB_WORKSPACE/../robolectric-jars"
|
||||
m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented"
|
||||
if [ -d "$m2" ] && [ ! -L "$m2" ]; then
|
||||
echo "cache=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
mkdir -p "$jars" "$(dirname "$m2")"
|
||||
jars=$(cd "$jars" && pwd)
|
||||
ln -sfn "$jars" "$m2"
|
||||
echo "path=$jars" >> "$GITHUB_OUTPUT"
|
||||
echo "cache=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Restore Robolectric's Android jars
|
||||
id: robolectric-cache
|
||||
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: ${{ steps.robolectric-jars.outputs.path }}
|
||||
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
|
||||
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
|
||||
- name: Count the restored Robolectric jars
|
||||
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||
run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV"
|
||||
- name: Unit tests
|
||||
id: unit-tests
|
||||
env:
|
||||
DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }}
|
||||
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
|
||||
run: |
|
||||
set -o pipefail
|
||||
mkdir -p app/build
|
||||
# A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next.
|
||||
for wait in 60 180 0; do
|
||||
status=0
|
||||
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$?
|
||||
if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://repo\.maven\.apache\.org/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://repo\.maven\.apache\.org/)' app/build/unit-tests.log; then
|
||||
exit "$status"
|
||||
fi
|
||||
echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s"
|
||||
sleep "$wait"
|
||||
done
|
||||
|
||||
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
|
||||
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
|
||||
- name: Save Robolectric's Android jars
|
||||
id: robolectric-jars-final
|
||||
if: always() && steps.robolectric-jars.outputs.cache == 'true'
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import glob, os, zipfile
|
||||
root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars')
|
||||
for f in glob.glob(os.path.join(root, '**', '*'), recursive=True):
|
||||
if not os.path.isfile(f):
|
||||
continue
|
||||
try:
|
||||
ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None
|
||||
except Exception:
|
||||
ok = False
|
||||
if not ok:
|
||||
os.remove(f)
|
||||
PY
|
||||
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
|
||||
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
|
||||
- name: Store Robolectric's Android jars
|
||||
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: ${{ steps.robolectric-jars.outputs.path }}
|
||||
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
|
||||
|
||||
- name: Upload unit test diagnostics
|
||||
id: unit-test-diagnostics
|
||||
if: always() && steps.unit-tests.outcome != 'skipped'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: unit-test-results
|
||||
path: |
|
||||
app/build/unit-tests.log
|
||||
app/build/test-results/testReleaseUnitTest/
|
||||
app/build/reports/tests/testReleaseUnitTest/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
overwrite: true
|
||||
|
||||
- name: Sign with the testkey (v1 + v2 + v3)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -858,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
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ jobs:
|
||||
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
|
||||
}
|
||||
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
|
||||
for name in directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic; do
|
||||
for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic; do
|
||||
file="packs/$name.tar.zst"
|
||||
[ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; }
|
||||
sha=$(sha256sum "$file" | cut -d' ' -f1)
|
||||
|
||||
@@ -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`.
|
||||
|
||||
|
||||
@@ -39,8 +39,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
|
||||
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx, Mali, Xclipse and PowerVR are experimental. Adreno 710 is currently unsupported. No root needed.
|
||||
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
|
||||
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk), install the Linux runtime, press **Play** and sign in to Steam.
|
||||
|
||||
Current Preview builds handle Android’s child-process limit during launch. The linked 0.7.11 release still uses the setup steps in its release notes.
|
||||
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
|
||||
|
||||
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
|
||||
|
||||
@@ -71,13 +70,14 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
|
||||
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
|
||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||
- DwarFS AppImages are unpacked by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
|
||||
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
|
||||
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
||||
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
||||
- Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim.
|
||||
- Wine write watches use userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later). libddsession supplies the arm64 syscall number and answers `PAGEMAP_SCAN` from `/proc/self/pagemap`.
|
||||
- libddsession runs Wine's arm64 `SIGUSR2` context handler (`dlls/ntdll/unix/signal_arm64.c`, LGPL-2.1-or-later) in place on a frame laid out like [Linux](https://github.com/torvalds/linux)'s `arch/arm64/kernel/signal.c`, and serves `fill_vm_counters` in `dlls/ntdll/unix/process.c` the kernel's own `/proc/<pid>/status`.
|
||||
- droiddeck-ntsync follows the [Linux](https://github.com/torvalds/linux) ntsync semantics in `Documentation/userspace-api/ntsync.rst` (GPL-2.0).
|
||||
- The proot fast path orders bindings like [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later).
|
||||
- DiRT 3 and DiRT Showdown keep their telemetry socket the way RoccoC's DiRTTelemetryErrorFix (MIT) does, based on the fix by Carsten Gottschling.
|
||||
- Zink on PowerVR keeps colour textures in colour with Icenowy Zheng's upstream [Mesa](https://gitlab.freedesktop.org/mesa/mesa) fix d55418dae7 (MIT), carried as a runtime patch.
|
||||
- Games and AppImage, Flatpak and Snap programs such as emulators use `TU_DEBUG=sysmem` by default, as does the Steam client. Turnip sysmem rendering can be turned off in Performance settings, except with the Adreno 710/720 driver, which always uses it.
|
||||
|
||||
+18
-5
@@ -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()
|
||||
@@ -90,10 +92,18 @@ def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
|
||||
def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines()
|
||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||
def addonPacks = ['directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].collectEntries { name ->
|
||||
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
|
||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||
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')
|
||||
@@ -207,7 +217,7 @@ android {
|
||||
jniLibs {
|
||||
useLegacyPackaging = true
|
||||
pickFirsts += ['**/libtermux.so']
|
||||
excludes += ['**/libproot.so', '**/libproot-loader.so', '**/libopencv_java4.so', '**/libmediapipe_tasks_jni.so']
|
||||
excludes += ['**/libproot.so', '**/libopencv_java4.so', '**/libmediapipe_tasks_jni.so']
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,9 +281,9 @@ tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
|
||||
def runtimeAssetsDir = layout.buildDirectory.dir('runtimeAssets')
|
||||
def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
|
||||
dependsOn(stageSessionScripts)
|
||||
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst', 'linuxfs/libddfastpath.so', 'linuxfs/libddaudit.so' }
|
||||
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
|
||||
from(rootProject.file('tools/linuxfs/innoextract'))
|
||||
from(rootProject.file('tools')) { include 'droiddeckctl', 'droiddeck-scenario', 'adb_device.py'; into('agent/ctl') }
|
||||
from(rootProject.file('tools')) { include 'droiddeckctl', 'droiddeck-scenario', 'adb_device.py', 'proot_profile.py'; into('agent/ctl') }
|
||||
from(rootProject.file('tools/agent/AGENTS.md')) { into('agent/ctl') }
|
||||
from(rootProject.file('docs/agent-control.md')) { into('agent/ctl') }
|
||||
from(rootProject.file('tools/agent/skills')) { into('agent/skills') }
|
||||
|
||||
@@ -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) },
|
||||
|
||||
@@ -277,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"
|
||||
@@ -481,5 +492,69 @@
|
||||
<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>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -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>
|
||||
@@ -4582,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;
|
||||
@@ -4628,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);
|
||||
@@ -4767,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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -92,6 +92,7 @@ class App : Application() {
|
||||
Thread({
|
||||
runCatching {
|
||||
if (com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).isDirectory) {
|
||||
if (!com.droiddeck.launcher.runtime.LinuxRuntime.patchedProot(app)) com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
|
||||
com.droiddeck.launcher.core.AddonPack.DIRECTAUDIO.ensure(app)
|
||||
com.droiddeck.launcher.session.SessionFiles.ensureDirtStandIn(app)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -57,6 +58,8 @@ import com.droiddeck.launcher.session.LaunchCoordinator
|
||||
import com.droiddeck.launcher.session.LaunchTicket
|
||||
import com.droiddeck.launcher.core.CpuCores
|
||||
import com.droiddeck.launcher.core.DownloadSource
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import com.droiddeck.launcher.core.WifiDiscovery
|
||||
import com.droiddeck.launcher.core.SteamIntegration
|
||||
@@ -187,9 +190,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var gamescopeRealtime by mutableStateOf(false)
|
||||
private var paceCores by mutableStateOf(true)
|
||||
private var gpuClockPin by mutableStateOf(false)
|
||||
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)
|
||||
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
|
||||
private var showPhantomGate by mutableStateOf(false)
|
||||
private var directAudio by mutableStateOf(false)
|
||||
private var picturePosition by mutableStateOf("center")
|
||||
private var integerScaling by mutableStateOf(false)
|
||||
@@ -199,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("")
|
||||
@@ -929,6 +944,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
switchPoll?.let { ui.removeCallbacks(it) }
|
||||
switchPoll = null
|
||||
switchingTo = null
|
||||
queuedLaunch.clear()
|
||||
cancelCompatLaunch()
|
||||
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(LauncherIcon.activity(this))
|
||||
@@ -1086,7 +1102,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(game.gameIdString))
|
||||
}
|
||||
}
|
||||
.playing(game))
|
||||
.playing(game), steamSession = true)
|
||||
}
|
||||
|
||||
private fun Intent.playing(game: Library.SteamGame): Intent =
|
||||
@@ -1244,7 +1260,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
private fun startSessionOrWait(next: Intent): Boolean {
|
||||
val started = startSession(next)
|
||||
val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL) ||
|
||||
next.getStringExtra(SessionService.EXTRA_PROGRAM) in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET))
|
||||
if (!started && (busy || LinuxRuntimeInstaller.isBusy())) android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return started
|
||||
}
|
||||
@@ -1330,6 +1347,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
val handoff = if (savedInstanceState == null && intent.getBooleanExtra(EXTRA_RESTARTED, false)) LauncherHandoff.take() else null
|
||||
val saved = savedInstanceState ?: handoff
|
||||
pendingSessionLogExport = saved?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
|
||||
queuedLaunch.restore(
|
||||
saved?.let { androidx.core.os.BundleCompat.getParcelable(it, STATE_PENDING_GATE_LAUNCH, Intent::class.java) },
|
||||
saved?.getLong(STATE_PENDING_GATE_LAUNCH_AT, 0L) ?: 0L, System.currentTimeMillis(),
|
||||
)
|
||||
homeChoiceOpen = saved?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
|
||||
gameSpaceOffered = saved?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
|
||||
if (savedInstanceState == null) readIntegrationIntent(intent)
|
||||
@@ -1344,7 +1365,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentTab.visible) navRequest = "agent"
|
||||
gameSyncFolder = GameFileSync.folder(this)
|
||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||
refreshAdbPairing()
|
||||
refreshPhantomStatus()
|
||||
if (!SessionState.running) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
|
||||
theme = SessionPrefs.theme(this)
|
||||
frameGenLabel = getString(R.string.frame_gen_off)
|
||||
@@ -1358,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)
|
||||
@@ -1376,10 +1405,20 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
applyLauncherFullscreen()
|
||||
updates.start()
|
||||
setContent {
|
||||
val prootPack by com.droiddeck.launcher.core.AddonPack.PROOT.state.collectAsState()
|
||||
androidx.compose.runtime.LaunchedEffect(prootPack) {
|
||||
if (prootPack == com.droiddeck.launcher.core.AddonPack.State.Ready && installed == null) refresh()
|
||||
}
|
||||
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() },
|
||||
)
|
||||
@@ -1449,10 +1488,18 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
oscMode = oscMode,
|
||||
controller = controllerSettings,
|
||||
updates = updates.state(),
|
||||
phantomProcessStatus = phantomProcessStatus,
|
||||
showPhantomGate = showPhantomGate,
|
||||
orientation = orientation,
|
||||
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,
|
||||
@@ -1476,15 +1523,19 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
),
|
||||
FrontEndActions(
|
||||
onPlay = { playSteam() },
|
||||
onQueuePlaySteam = {
|
||||
queuedLaunch.queue(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, false), System.currentTimeMillis())
|
||||
},
|
||||
onPlaySteamVr = { playSteamVr() },
|
||||
onSteamUrl = { url ->
|
||||
if (!SessionState.running) startSession(
|
||||
Intent(this, SessionActivity::class.java).putExtra(SessionService.EXTRA_STEAM_URL, url),
|
||||
Intent(this, SessionActivity::class.java).putExtra(SessionService.EXTRA_STEAM_URL, url), steamSession = true,
|
||||
)
|
||||
},
|
||||
onPlayDesktopUi = {
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_STEAM)
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"))
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true)
|
||||
},
|
||||
onSteamGame = { g ->
|
||||
if (shortcutPicker) chooseGameShortcut(g)
|
||||
@@ -1784,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 },
|
||||
@@ -1853,9 +1926,31 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
SessionPrefs.setBackActionsInverted(this, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
onRefreshPhantomStatus = { refreshPhantomStatus() },
|
||||
onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) },
|
||||
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
|
||||
onStartPairingGuide = { displayId -> PairingGuideActivity.start(this, displayId) },
|
||||
onSetPhantomProcessLimit = { enabled, complete ->
|
||||
Thread({
|
||||
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@FrontEndActivity, enabled) }
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_unavailable) }
|
||||
ui.post {
|
||||
if (error == null) refreshPhantomStatus()
|
||||
complete(error)
|
||||
}
|
||||
}, "wireless-adb-setting").start()
|
||||
},
|
||||
onCopyPhantomCommand = { enabled ->
|
||||
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
|
||||
ClipData.newPlainText(getString(R.string.main_adb_clip_label), PhantomProcessLimit.adbCommand(enabled)),
|
||||
)
|
||||
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
onDismissPhantomGate = { queuedLaunch.clear(); showPhantomGate = false },
|
||||
onShowPhantomGate = {
|
||||
refreshPhantomStatus()
|
||||
showPhantomGate = true
|
||||
},
|
||||
onStartWirelessAdbPairing = { enabled -> WirelessAdbPairingService.start(this, enabled) },
|
||||
onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) },
|
||||
onEnsureNotifications = { done -> ensureNotifications(done) },
|
||||
updates = updates.actions(),
|
||||
controller = ControllerActions(
|
||||
@@ -2037,7 +2132,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
private fun startSteamSession(steamVr: Boolean = false) {
|
||||
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr))
|
||||
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true, queueIfBlocked = !steamVr)
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
@@ -2068,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) {
|
||||
@@ -2149,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}")
|
||||
@@ -2158,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
|
||||
@@ -2295,7 +2396,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
|
||||
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
|
||||
}
|
||||
refreshAdbPairing()
|
||||
refreshPhantomStatus()
|
||||
syncLossless()
|
||||
updates.onResume()
|
||||
drivers.checkOnOpen()
|
||||
@@ -2369,6 +2470,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
|
||||
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
|
||||
pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
|
||||
queuedLaunch.launch?.let {
|
||||
outState.putParcelable(STATE_PENDING_GATE_LAUNCH, it)
|
||||
outState.putLong(STATE_PENDING_GATE_LAUNCH_AT, queuedLaunch.queuedAt)
|
||||
}
|
||||
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
|
||||
saveCompatLaunch(outState)
|
||||
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
|
||||
@@ -2406,10 +2511,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
override fun onDestroy() {
|
||||
// The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too.
|
||||
if (com.droiddeck.launcher.session.Onboarding.onFirstRunReady === firstRunReady) com.droiddeck.launcher.session.Onboarding.onFirstRunReady = null
|
||||
queuedLaunchRunner.destroy()
|
||||
triggerKeys.cancel()
|
||||
launchCoordinator.cancelAll()
|
||||
cancelCompatLaunch()
|
||||
updates.unregister()
|
||||
frost.stop()
|
||||
runCatching { unregisterReceiver(shortcutsInstallStatus) }
|
||||
super.onDestroy()
|
||||
}
|
||||
@@ -2999,8 +3106,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
fsyncFirst = fsyncFirst,
|
||||
gamescopeRealtime = gamescopeRealtime,
|
||||
gpuClockPin = gpuClockPin,
|
||||
desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
|
||||
guestHostname = guestHostname,
|
||||
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 },
|
||||
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
|
||||
@@ -3013,6 +3120,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
|
||||
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
|
||||
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
|
||||
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
|
||||
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) },
|
||||
@@ -3329,10 +3439,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
|
||||
paceCores = SessionPrefs.paceCores(this)
|
||||
gpuClockPin = SessionPrefs.gpuClockPin(this)
|
||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
||||
prootFastPath = SessionPrefs.prootFastPath(this)
|
||||
nativeUserland = SessionPrefs.nativeUserland(this)
|
||||
desktopAsUser = SessionPrefs.desktopAsUser(this)
|
||||
cursorComposite = SessionPrefs.cursorComposite(this)
|
||||
guestHostname = SessionPrefs.guestHostname(this)
|
||||
refreshAdbPairing()
|
||||
refreshPhantomStatus()
|
||||
}
|
||||
|
||||
private fun gameDebugLogsNeedsRestart(): Boolean =
|
||||
@@ -3515,7 +3628,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
install(release)
|
||||
}
|
||||
|
||||
private fun startSession(intent: Intent): Boolean {
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false, queueIfBlocked: Boolean = false): Boolean {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy()) return false
|
||||
if (SessionState.installing != null && !SessionState.running) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
@@ -3529,6 +3642,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
refreshPhantomStatus()
|
||||
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
if (queueIfBlocked) queuedLaunch.queue(intent, System.currentTimeMillis())
|
||||
showPhantomGate = true
|
||||
return false
|
||||
}
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.canDraw(this)
|
||||
if (warn && available != null) { showNonAdreno = available; return false }
|
||||
startActivity(intent)
|
||||
@@ -3573,14 +3692,42 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
done(granted)
|
||||
}
|
||||
|
||||
private fun refreshAdbPairing() {
|
||||
private val queuedLaunch = com.droiddeck.launcher.session.QueuedLaunch<Intent>(GATE_LAUNCH_MS)
|
||||
private val queuedLaunchRunner = com.droiddeck.launcher.session.QueuedLaunchRunner(
|
||||
queue = queuedLaunch,
|
||||
now = System::currentTimeMillis,
|
||||
blocked = { PhantomProcessLimit.blocksSteam(phantomProcessStatus) },
|
||||
busy = ::steamStartBusy,
|
||||
schedule = { delay, task -> if (delay <= 0L) ui.post(task) else ui.postDelayed(task, delay) },
|
||||
unschedule = ui::removeCallbacks,
|
||||
start = { launch -> startSession(launch, steamSession = true, queueIfBlocked = true) },
|
||||
retryMs = GATE_LAUNCH_RETRY_MS,
|
||||
)
|
||||
|
||||
/** The conditions under which a Steam start waits instead of being refused: setup, a runtime or desktop install, a storage cleanup, or a Steam store download. */
|
||||
private fun steamStartBusy(): Boolean = busy || LinuxRuntimeInstaller.isBusy() || com.droiddeck.launcher.session.Onboarding.settling() ||
|
||||
(SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning ||
|
||||
(!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.downloading())
|
||||
|
||||
private fun refreshPhantomStatus() {
|
||||
phantomProcessStatus = PhantomProcessLimit.read(this)
|
||||
if (queuedLaunch.launch != null && !PhantomProcessLimit.blocksSteam(phantomProcessStatus)) showPhantomGate = false
|
||||
queuedLaunchRunner.poke()
|
||||
adbPaired = WirelessAdbFix.hasSavedPairing(this)
|
||||
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
getString(
|
||||
R.string.phantom_warning, PhantomProcessLimit.title(this, phantomProcessStatus),
|
||||
PhantomProcessLimit.instructions(this, phantomProcessStatus), PhantomProcessLimit.adbCommand(),
|
||||
)
|
||||
} else null
|
||||
}
|
||||
|
||||
private fun openDeveloperOptions(displayId: Int?) {
|
||||
val highlight = if (PhantomProcessLimit.hasDeveloperToggle() &&
|
||||
WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) "disable_phantom_process_monitor" else "toggle_adb_wireless"
|
||||
val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
.putExtra(":settings:fragment_args_key", "toggle_adb_wireless")
|
||||
.apply { if (highlight != null) putExtra(":settings:fragment_args_key", highlight) }
|
||||
try {
|
||||
if (displayId == null) startActivity(intent)
|
||||
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle())
|
||||
@@ -3702,6 +3849,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private const val REQUEST_NOTIFICATIONS = 7103
|
||||
private const val EXTRA_RESTARTED = "com.droiddeck.launcher.extra.RESTARTED"
|
||||
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
|
||||
private const val STATE_PENDING_GATE_LAUNCH = "pending_gate_launch"
|
||||
private const val STATE_PENDING_GATE_LAUNCH_AT = "pending_gate_launch_at"
|
||||
private const val GATE_LAUNCH_MS = 15 * 60_000L
|
||||
private const val GATE_LAUNCH_RETRY_MS = 2_000L
|
||||
private const val KEY_PENDING_SESSION_LOG_EXPORT = "pending_session_log_export"
|
||||
private const val STATE_GAME_SPACE_OFFERED = "game_space_offered"
|
||||
private const val TAG = "MainActivity"
|
||||
|
||||
@@ -58,6 +58,7 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.core.AppLanguage
|
||||
import com.droiddeck.launcher.core.GlobalSettings
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
@@ -67,9 +68,10 @@ import com.droiddeck.launcher.ui.SecondaryButton
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
class PairingGuideActivity : ComponentActivity() {
|
||||
enum class Step { BUILD_NUMBER, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
|
||||
enum class Step { BUILD_NUMBER, CHILD_PROCESS, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
|
||||
|
||||
private var settingsDisplay: Int? = null
|
||||
private var toggleOnly = false
|
||||
private var inPip by mutableStateOf(false)
|
||||
private var launchPending = false
|
||||
|
||||
@@ -78,6 +80,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
||||
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
|
||||
setContent { DroidDeckTheme { Guide() } }
|
||||
launchPending = savedInstanceState == null
|
||||
}
|
||||
@@ -86,6 +89,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
||||
toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
|
||||
launchPending = true
|
||||
}
|
||||
|
||||
@@ -116,7 +120,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
|
||||
private fun launchSettings() {
|
||||
launchPending = false
|
||||
openSettings(stepFor(SettingsState.read(this), WirelessAdbPairingService.stage.value))
|
||||
openSettings(stepFor(SettingsState.read(this), WirelessAdbPairingService.stage.value, toggleOnly))
|
||||
}
|
||||
|
||||
private fun enterPip() {
|
||||
@@ -130,7 +134,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number")
|
||||
} else {
|
||||
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).apply {
|
||||
putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
|
||||
if (step != Step.CHILD_PROCESS) putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
|
||||
}
|
||||
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val display = settingsDisplay
|
||||
@@ -157,10 +161,10 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
delay(500)
|
||||
}
|
||||
}
|
||||
val step = stepFor(settingsState, stage)
|
||||
val step = stepFor(settingsState, stage, toggleOnly)
|
||||
var previous by remember { mutableStateOf(step) }
|
||||
LaunchedEffect(step) {
|
||||
if (previous == Step.BUILD_NUMBER && step == Step.WIRELESS_DEBUGGING) openSettings(step)
|
||||
if (previous == Step.BUILD_NUMBER && (step == Step.WIRELESS_DEBUGGING || step == Step.CHILD_PROCESS)) openSettings(step)
|
||||
previous = step
|
||||
when (step) {
|
||||
Step.DONE -> { delay(1_500); returnToApp() }
|
||||
@@ -168,7 +172,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
LaunchedEffect(stage) { if (stage == Stage.Idle) finish() }
|
||||
LaunchedEffect(stage) { if (stage == Stage.Idle && !toggleOnly) finish() }
|
||||
BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() }
|
||||
|
||||
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {
|
||||
@@ -195,7 +199,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.adbpair_title_pair), style = MaterialTheme.typography.headlineSmall,
|
||||
Text(stringResource(R.string.gate_title), style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text(instruction(step, stage), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground)
|
||||
StepVisual(step, compact = false)
|
||||
@@ -209,7 +213,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
openSettings(step)
|
||||
})
|
||||
SecondaryButton(stringResource(R.string.common_cancel), onClick = {
|
||||
WirelessAdbPairingService.cancel(this@PairingGuideActivity)
|
||||
if (!toggleOnly) WirelessAdbPairingService.cancel(this@PairingGuideActivity)
|
||||
returnToApp()
|
||||
})
|
||||
}
|
||||
@@ -220,11 +224,12 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
@Composable
|
||||
private fun instruction(step: Step, stage: Stage): String = when (step) {
|
||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number)
|
||||
Step.CHILD_PROCESS -> stringResource(R.string.pairguide_child_process)
|
||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless)
|
||||
Step.PAIR -> stringResource(R.string.pairguide_pair)
|
||||
Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3)
|
||||
Step.WORKING -> (stage as? Stage.Working)?.step ?: stringResource(R.string.adbpair_title_pair)
|
||||
Step.DONE -> stringResource(R.string.adbpair_paired)
|
||||
Step.WORKING -> (stage as? Stage.Working)?.step ?: stringResource(R.string.adbpair_title_working)
|
||||
Step.DONE -> stringResource(R.string.adbpair_title_done)
|
||||
Step.FAILED -> (stage as? Stage.Failed)?.error ?: stringResource(R.string.adbpair_title_failed)
|
||||
}
|
||||
|
||||
@@ -236,6 +241,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat")
|
||||
val label = when (step) {
|
||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number)
|
||||
Step.CHILD_PROCESS -> stringResource(R.string.pairguide_row_child_process)
|
||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless)
|
||||
Step.PAIR -> stringResource(R.string.pairguide_row_pair)
|
||||
Step.CODE -> stringResource(R.string.adbpair_enter_code)
|
||||
@@ -250,7 +256,7 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge,
|
||||
color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
when (step) {
|
||||
Step.WIRELESS_DEBUGGING -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
|
||||
Step.WIRELESS_DEBUGGING, Step.CHILD_PROCESS -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
|
||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent)
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
@@ -277,7 +283,8 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
@Composable
|
||||
private fun StepDots(step: Step) {
|
||||
val accent = LocalPalette.current.signal
|
||||
val shown = listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
|
||||
val shown = if (toggleOnly) listOf(Step.BUILD_NUMBER, Step.CHILD_PROCESS)
|
||||
else listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
|
||||
val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
shown.forEachIndexed { index, _ ->
|
||||
@@ -291,20 +298,27 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
private data class SettingsState(
|
||||
val developerOptions: Boolean,
|
||||
val wirelessDebugging: Boolean,
|
||||
val childProcessBlocked: Boolean,
|
||||
) {
|
||||
companion object {
|
||||
fun read(context: Context) = SettingsState(
|
||||
GlobalSettings.developerOptionsOn(context),
|
||||
GlobalSettings.wirelessDebuggingOn(context),
|
||||
PhantomProcessLimit.blocksSteam(PhantomProcessLimit.read(context)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val EXTRA_DISPLAY = "settingsDisplay"
|
||||
private const val EXTRA_TOGGLE_ONLY = "toggleOnly"
|
||||
private const val HIGHLIGHT_KEY = ":settings:fragment_args_key"
|
||||
|
||||
private fun stepFor(settings: SettingsState, stage: Stage): Step = when (stage) {
|
||||
private fun stepFor(settings: SettingsState, stage: Stage, toggleOnly: Boolean): Step = if (toggleOnly) when {
|
||||
!settings.developerOptions -> Step.BUILD_NUMBER
|
||||
settings.childProcessBlocked -> Step.CHILD_PROCESS
|
||||
else -> Step.DONE
|
||||
} else when (stage) {
|
||||
is Stage.Working -> Step.WORKING
|
||||
Stage.Done -> Step.DONE
|
||||
is Stage.Failed -> Step.FAILED
|
||||
@@ -328,10 +342,11 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
return mode == AppOpsManager.MODE_ALLOWED
|
||||
}
|
||||
|
||||
fun start(context: Context, settingsDisplay: Int?): Boolean {
|
||||
fun start(context: Context, settingsDisplay: Int?, toggleOnly: Boolean = false): Boolean {
|
||||
if (settingsDisplay == null && !canFloat(context)) return false
|
||||
context.startActivity(Intent(context, PairingGuideActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
.putExtra(EXTRA_TOGGLE_ONLY, toggleOnly)
|
||||
.apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) })
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
@@ -850,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() ||
|
||||
@@ -988,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)
|
||||
}
|
||||
@@ -1193,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) {
|
||||
@@ -1272,6 +1287,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
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,
|
||||
@@ -1475,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()
|
||||
@@ -1528,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,
|
||||
@@ -1906,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 ->
|
||||
@@ -2005,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()
|
||||
@@ -2094,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,
|
||||
@@ -2133,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()
|
||||
@@ -2142,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()
|
||||
}
|
||||
|
||||
@@ -3045,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 ->
|
||||
@@ -3058,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
|
||||
@@ -3637,6 +3764,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
presentationFaultHint()?.let { return it }
|
||||
if (log == null || !log.isFile) return null
|
||||
return try {
|
||||
var enosys = 0
|
||||
var fexMissing = false
|
||||
val size = log.length()
|
||||
val text = java.io.RandomAccessFile(log, "r").use { f ->
|
||||
@@ -3647,6 +3775,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
String(bytes, Charsets.ISO_8859_1)
|
||||
}
|
||||
text.lineSequence().forEach { line ->
|
||||
if (line.contains("Function not implemented")) enosys++
|
||||
if (line.contains(FEX_MISSING)) fexMissing = true
|
||||
}
|
||||
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
|
||||
@@ -3668,6 +3797,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
} else if (fexMissing) {
|
||||
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
|
||||
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
|
||||
} else if (enosys >= 8) {
|
||||
EndHint(resources.getQuantityString(R.plurals.session_hint_enosys, enosys, enosys,
|
||||
getString(R.string.perf_title), getString(R.string.perf_seccomp), getString(R.string.perf_xalia)))
|
||||
} else null
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
@@ -3675,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 -> {
|
||||
@@ -3767,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)
|
||||
@@ -3850,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)
|
||||
}
|
||||
@@ -5144,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
|
||||
@@ -5173,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() {
|
||||
@@ -6076,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 = {}) {
|
||||
@@ -6148,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)
|
||||
@@ -6263,6 +6396,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
heldButtons.clear()
|
||||
hidePrimaryKeyboard()
|
||||
sessionClipboard.stop()
|
||||
sessionTextInput.stop()
|
||||
padMotion?.stop()
|
||||
cursorVisible = false
|
||||
closeSecondScreen(reset = false)
|
||||
@@ -6278,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()
|
||||
@@ -6349,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()
|
||||
@@ -6428,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)
|
||||
@@ -7145,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) {
|
||||
@@ -7157,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)
|
||||
@@ -7269,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"
|
||||
|
||||
@@ -7,7 +7,7 @@ import java.io.File
|
||||
|
||||
/**
|
||||
* Loopback adb for the agent, so droiddeckctl in the Linux userland reaches the app. It reuses
|
||||
* the Wireless debugging pairing DroidDeck already made: the paired
|
||||
* the Wireless debugging pairing DroidDeck already made (for the phantom process fix): the paired
|
||||
* key goes to the guest as an adb vendor key, and the serial is the paired TLS connect port.
|
||||
* Without a pairing it falls back to adbd on 127.0.0.1:5555, which some devices and `adb tcpip`
|
||||
* leave listening.
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,13 @@ package com.droiddeck.launcher.agent
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
||||
import java.nio.file.StandardOpenOption.READ
|
||||
@@ -54,7 +58,10 @@ object AgentEnv {
|
||||
fun override(context: Context, name: String): JSONObject = synchronized(lock) {
|
||||
AgentAccess.requireCommands(context)
|
||||
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'")
|
||||
if (name in retiredOverrides) throw AgentException("INVALID_NAME", "The Fast Path override was retired")
|
||||
if (name == LEGACY_FAST_PATH) throw AgentException("INVALID_NAME", "The fast-path library is now $FAST_PATH")
|
||||
if (name == "libddfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) {
|
||||
throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library")
|
||||
}
|
||||
val source = File(inbox(context), name)
|
||||
if (Files.isSymbolicLink(source.toPath())) throw AgentException("INVALID_NAME", "The override must be a regular file")
|
||||
if (!source.isFile) throw AgentException("NO_SUCH_FILE", "Push the binary to ${source.path} first")
|
||||
@@ -67,6 +74,10 @@ object AgentEnv {
|
||||
staged.delete()
|
||||
throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
|
||||
}
|
||||
if (name == "libddfastpath.so" && !arm64SharedLibrary(staged)) {
|
||||
staged.delete()
|
||||
throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library")
|
||||
}
|
||||
if (!staged.setExecutable(true, false) || !staged.renameTo(target)) {
|
||||
staged.delete()
|
||||
throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs")
|
||||
@@ -76,9 +87,42 @@ object AgentEnv {
|
||||
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
|
||||
save(context, state)
|
||||
state.put("installed", "$GUEST_BIN/$name")
|
||||
if (name == "libddfastpath.so") {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
target.inputStream().use { input ->
|
||||
val buffer = ByteArray(65536)
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
digest.update(buffer, 0, count)
|
||||
}
|
||||
}
|
||||
state.put("sha256", digest.digest().joinToString("") { "%02x".format(it) })
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
fun fastPathLibrary(context: Context): String = synchronized(lock) {
|
||||
if (!AgentAccess.commandsAllowed(context)) return@synchronized ProotFastPath.LIBRARY
|
||||
if ("libddfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY
|
||||
val file = File(bin(context), "libddfastpath.so")
|
||||
if (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY
|
||||
"$GUEST_BIN/libddfastpath.so"
|
||||
}
|
||||
|
||||
private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input ->
|
||||
val header = ByteArray(20)
|
||||
var count = 0
|
||||
while (count < header.size) {
|
||||
val read = input.read(header, count, header.size - count)
|
||||
if (read < 0) return@use false
|
||||
count += read
|
||||
}
|
||||
header.take(7) == listOf<Byte>(0x7f, 0x45, 0x4c, 0x46, 2, 1, 1) &&
|
||||
header[16] == 3.toByte() && header[17] == 0.toByte() &&
|
||||
header[18] == 183.toByte() && header[19] == 0.toByte()
|
||||
}
|
||||
|
||||
fun beginSession(context: Context): List<String> = synchronized(lock) {
|
||||
if (!AgentAccess.commandsAllowed(context)) {
|
||||
revoke(context)
|
||||
@@ -86,12 +130,18 @@ object AgentEnv {
|
||||
}
|
||||
val state = load(context)
|
||||
val active = strings(state.optJSONArray("pending"))
|
||||
val overrides = strings(state.optJSONArray("pendingOverrides"))
|
||||
bin(context).listFiles()?.filter { it.name !in overrides }?.forEach { it.delete() }
|
||||
val queued = strings(state.optJSONArray("pendingOverrides"))
|
||||
val legacy = File(bin(context), LEGACY_FAST_PATH)
|
||||
val stranded = FAST_PATH in queued && legacy.isFile && !File(bin(context), FAST_PATH).exists() &&
|
||||
!legacy.renameTo(File(bin(context), FAST_PATH))
|
||||
if (stranded) Log.w(TAG, "could not rename the queued $LEGACY_FAST_PATH; it stays queued for the next session")
|
||||
val overrides = if (stranded) queued - FAST_PATH else queued
|
||||
bin(context).listFiles()
|
||||
?.filter { it.name !in overrides && !(stranded && it.name == LEGACY_FAST_PATH) }?.forEach { it.delete() }
|
||||
val lines = strings(state.optJSONArray("persistent")) + active
|
||||
val withPath = if (overrides.isEmpty()) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
|
||||
val withPath = if (overrides.none { it != "libddfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
|
||||
state.put("active", JSONArray(active)).put("pending", JSONArray())
|
||||
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
|
||||
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray(if (stranded) listOf(FAST_PATH) else emptyList()))
|
||||
save(context, state)
|
||||
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
|
||||
withPath
|
||||
@@ -114,7 +164,8 @@ object AgentEnv {
|
||||
save(context, state)
|
||||
}
|
||||
|
||||
private val retiredOverrides = setOf("libddfastpath.so", "libblfastpath.so")
|
||||
private const val FAST_PATH = "libddfastpath.so"
|
||||
private const val LEGACY_FAST_PATH = "libblfastpath.so"
|
||||
|
||||
private fun pathOf(lines: List<String>) =
|
||||
lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: LinuxRuntime.GUEST_PATH
|
||||
@@ -145,7 +196,7 @@ object AgentEnv {
|
||||
if (!state.has(key)) state.put(key, JSONArray())
|
||||
}
|
||||
for (key in listOf("pendingOverrides", "activeOverrides")) {
|
||||
state.put(key, JSONArray(strings(state.optJSONArray(key)).filterNot { it in retiredOverrides }.distinct()))
|
||||
state.put(key, JSONArray(strings(state.optJSONArray(key)).map { if (it == LEGACY_FAST_PATH) FAST_PATH else it }.distinct()))
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -373,7 +373,7 @@ object Codex : AgentHarness {
|
||||
override val plans = false
|
||||
override val efforts = listOf("low", "medium", "high")
|
||||
|
||||
// Codex's sandbox needs Landlock and seccomp, which the Android guest cannot provide, so commands run unsandboxed
|
||||
// Codex's sandbox needs Landlock and seccomp, which proot does not provide, so commands run unsandboxed
|
||||
// and "untrusted" is what makes Codex ask before each one that is not known to be safe.
|
||||
override val permissions = listOf(
|
||||
AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint),
|
||||
|
||||
@@ -14,6 +14,7 @@ import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.OrphanReaper
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
|
||||
@@ -67,7 +68,7 @@ object AgentHost {
|
||||
|
||||
/** Where the agent runs and what the user sees, which no file in the checkout tells it. */
|
||||
@VisibleForTesting
|
||||
internal const val BRIEF = "You run inside DroidDeck on the user's handheld, in its Linux userland (Ubuntu, aarch64), " +
|
||||
internal const val BRIEF = "You run inside DroidDeck on the user's handheld, in its Linux userland (Ubuntu under proot, aarch64), " +
|
||||
"and the user talks to you from DroidDeck's Agent tab, often on a small screen, so keep replies short. " +
|
||||
"DroidDeck's rules for working here are in your global instructions file (~/.claude/CLAUDE.md or ~/.codex/AGENTS.md); " +
|
||||
"if they are not loaded, read ${AgentSetup.CTL}/AGENTS.md before acting on the device. " +
|
||||
@@ -544,23 +545,34 @@ object AgentHost {
|
||||
state = if (installed) State.IDLE else State.MISSING
|
||||
}
|
||||
|
||||
fun guest(app: Context, command: List<String>, workdir: String = "/root", connectAdb: Boolean = true): ProcessBuilder {
|
||||
/**
|
||||
* A process for [command] in the Linux userland, run the way the store helpers run theirs:
|
||||
* proot over the installed rootfs, without a session. Loopback adb is connected first so
|
||||
* droiddeckctl reaches the app.
|
||||
*/
|
||||
fun guest(app: Context, command: List<String>, workdir: String = "/root", connectAdb: Boolean = true, fakeRoot: Boolean = false): ProcessBuilder {
|
||||
val adb = AgentAdb.prepare(app)
|
||||
val env = listOf(
|
||||
"/usr/bin/env", "HOME=/root", "PATH=$GUEST_PATH", "LANG=C.UTF-8",
|
||||
"ADB_SERIAL=${adb.serial}", "ADB_VENDOR_KEYS=${adb.vendorKeys}", "DROIDDECK_PACKAGE=${app.packageName}",
|
||||
"ADB_SERVER_SOCKET=localfilesystem:${File(app.noBackupFilesDir, "agent-adb.sock").path}",
|
||||
"DD_AGENT=1", "DD_AGENT_INBOX=${File(app.filesDir, "agent").path}", "BROWSER=/root/.local/bin/android-open", "DD_BROWSER_DISPLAY=${AgentAdb.browserDisplay}",
|
||||
)
|
||||
val shell = listOf(
|
||||
"/bin/sh", "-c",
|
||||
// proot ends the adb server with the command, so each command that needs adb connects it.
|
||||
(if (connectAdb) "adb start-server >/dev/null 2>&1; adb connect \"\$ADB_SERIAL\" >/dev/null 2>&1; " else "") +
|
||||
"cd \"$1\" 2>/dev/null; shift; exec \"$@\"", "sh", workdir,
|
||||
)
|
||||
val root = LinuxRuntime.rootDir(app)
|
||||
val mounts = LinuxRuntime.binds(app, null, null, LinuxRuntime.sharedStorage(app), null)
|
||||
return com.droiddeck.launcher.runtime.NativeGuest.processBuilder(app, root, mounts, env + shell + command)
|
||||
.redirectErrorStream(true)
|
||||
val proot = LinuxRuntime.command(app, null, null, LinuxRuntime.sharedStorage(app), null, env + shell + command, fakeRoot)
|
||||
return ProcessBuilder(proot).redirectErrorStream(true).apply {
|
||||
environment().apply {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
|
||||
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun guestFileExists(context: Context, path: String): Boolean {
|
||||
@@ -699,6 +711,7 @@ object AgentHost {
|
||||
claimLabRequest(app)
|
||||
claimOpenUrl(app)
|
||||
claimDeviceCode(app)
|
||||
// proot comes from an add-on pack fetched after the app starts, so the runtime can become usable later.
|
||||
if (!available && state != State.WORKING) available = LinuxRuntime.hasRootfs(app)
|
||||
lab = LabProgress.read(LinuxRuntime.rootDir(app))
|
||||
AgentHostService.update(app)
|
||||
|
||||
@@ -7,13 +7,15 @@ import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** Runs a native guest program (`droiddeckctl native`), for testing the native userland. */
|
||||
/** Runs a guest program without proot (`droiddeckctl native`), for testing the native userland. */
|
||||
object AgentNative {
|
||||
private const val OUTPUT_CAP = 256 * 1024
|
||||
|
||||
fun run(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
|
||||
// with the setting off, staging leaves the rootfs as proot wants it
|
||||
if (!com.droiddeck.launcher.session.SessionPrefs.nativeUserland(context)) NativeGuest.prepare(context, root)
|
||||
if (!NativeGuest.available(root)) throw AgentException("NATIVE_UNAVAILABLE", "The rootfs has no native hook or glibc loader yet; start a session once")
|
||||
val argvJson = request.optJSONArray("argv") ?: throw AgentException("INVALID_REQUEST", "argv is required")
|
||||
val argv = (0 until argvJson.length()).map { argvJson.getString(it) }
|
||||
|
||||
@@ -5,6 +5,10 @@ import android.os.SystemClock
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Linux userland processes, read from /proc: proot runs them as real processes under the app's
|
||||
* own uid, so the app can list and end them without a shell.
|
||||
*/
|
||||
object AgentProcesses {
|
||||
data class Proc(
|
||||
val pid: Int, val ppid: Int, val name: String, val args: String,
|
||||
@@ -20,7 +24,7 @@ object AgentProcesses {
|
||||
|
||||
/** Guest processes, those under [turnPid] (the agent's current turn) first. */
|
||||
@Synchronized
|
||||
fun snapshot(root: File, turnPid: Int): List<Proc> {
|
||||
fun snapshot(turnPid: Int): List<Proc> {
|
||||
val me = Process.myPid()
|
||||
val uid = Process.myUid()
|
||||
val stats = HashMap<Int, Stat>()
|
||||
@@ -36,15 +40,14 @@ object AgentProcesses {
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val uptimeTicks = now * HZ / 1000
|
||||
val elapsed = (now - lastAt).coerceAtLeast(1)
|
||||
val launchers = com.droiddeck.launcher.runtime.GuestWorkers.guestPids().toSet() + turnPid +
|
||||
com.droiddeck.launcher.session.SessionState.guestPid
|
||||
val rootPath = root.path.trimEnd('/') + "/"
|
||||
fun ancestors(pid: Int) = generateSequence(stats[pid]?.ppid) { stats[it]?.ppid }.takeWhile { it > 1 }.take(64)
|
||||
fun nativeGuest(pid: Int): Boolean = pid in launchers || args[pid].orEmpty().split(' ').take(2).any {
|
||||
it.startsWith(rootPath)
|
||||
fun isProot(pid: Int): Boolean {
|
||||
val argv = args[pid].orEmpty().split(' ')
|
||||
val program = if (argv.first().endsWith("/linker64")) argv.getOrElse(1) { "" } else argv.first()
|
||||
return program.endsWith("proot.so") || program.endsWith("/proot")
|
||||
}
|
||||
fun ancestors(pid: Int) = generateSequence(stats[pid]?.ppid) { stats[it]?.ppid }.takeWhile { it > 1 }.take(64)
|
||||
val out = stats.values.filter { s ->
|
||||
args[s.pid].orEmpty().isNotEmpty() && (nativeGuest(s.pid) || ancestors(s.pid).any(::nativeGuest))
|
||||
!isProot(s.pid) && args[s.pid].orEmpty().isNotEmpty() && ancestors(s.pid).any { isProot(it) }
|
||||
}.map { s ->
|
||||
val full = args[s.pid].orEmpty()
|
||||
val cpu = lastTicks[s.pid]?.let { ((s.ticks - it) * 1000 * 100 / HZ / elapsed).toInt().coerceIn(0, 800) } ?: 0
|
||||
|
||||
@@ -144,6 +144,8 @@ object AgentSetup {
|
||||
"apt -f install -y --fix-missing; " +
|
||||
"apt install -y --no-install-recommends git gh adb curl ca-certificates python3; $harnessInstall"
|
||||
|
||||
fun runsAsRoot(step: Step) = step == Step.INSTALL
|
||||
|
||||
/** 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)
|
||||
|
||||
@@ -187,7 +189,7 @@ object AgentSetup {
|
||||
val result = runCatching {
|
||||
installHelpers(app)
|
||||
runCatching { harness.prepare(LinuxRuntime.rootDir(app)) }
|
||||
val child = AgentHost.guest(app, command).start()
|
||||
val child = AgentHost.guest(app, command, fakeRoot = runsAsRoot(step)).start()
|
||||
val pid = AgentProcesses.pidOf(child)
|
||||
OrphanReaper.keep(pid)
|
||||
try {
|
||||
@@ -196,7 +198,7 @@ object AgentSetup {
|
||||
child.inputStream.bufferedReader().forEachLine { line ->
|
||||
log.appendLine(line)
|
||||
val text = line.trim()
|
||||
if (text.isNotEmpty()) main.post {
|
||||
if (text.isNotEmpty() && !noise(text)) main.post {
|
||||
detail[step] = text.take(160)
|
||||
if (step == Step.GITHUB && text.startsWith("GitHub device code:")) AgentHostService.update(app)
|
||||
}
|
||||
@@ -257,7 +259,7 @@ object AgentSetup {
|
||||
// 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() }?.trim()?.take(160)
|
||||
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(
|
||||
@@ -268,6 +270,9 @@ object AgentSetup {
|
||||
}
|
||||
}
|
||||
|
||||
/** proot warns about its bindings on every start; that says nothing about the step. */
|
||||
private fun noise(line: String) = line.startsWith("proot warning")
|
||||
|
||||
private fun set(step: Step, value: Status) {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) status[step] = value else main.post { status[step] = value }
|
||||
}
|
||||
|
||||
@@ -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()) {
|
||||
@@ -197,7 +246,25 @@ public class PulseAudioComponent extends SessionPart {
|
||||
final java.io.PrintWriter out = openLog();
|
||||
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);
|
||||
}
|
||||
},
|
||||
@@ -211,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
|
||||
@@ -232,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);
|
||||
@@ -407,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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +152,9 @@ internal class AddonPack(
|
||||
const val COMPLETE = ".complete"
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
@JvmField
|
||||
val PROOT = AddonPack("proot", BuildConfig.PACK_PROOT_SHA256, BuildConfig.PACK_PROOT_SIZE,
|
||||
listOf("libproot.so", "libproot-loader.so"))
|
||||
@JvmField
|
||||
val DIRECTAUDIO = AddonPack("directaudio", BuildConfig.PACK_DIRECTAUDIO_SHA256, BuildConfig.PACK_DIRECTAUDIO_SIZE,
|
||||
listOf("linux-wine11/version.txt", "linux-wine11-systhread/version.txt"))
|
||||
|
||||
@@ -284,6 +284,11 @@ object DeviceReport {
|
||||
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
|
||||
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
|
||||
k("pace cores", SessionPrefs.paceCores(context))
|
||||
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
|
||||
k("native userland (no proot)", SessionPrefs.nativeUserland(context))
|
||||
k("proot fast path", SessionPrefs.prootFastPath(context))
|
||||
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
|
||||
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
|
||||
k("Guest host name", SessionPrefs.guestHostname(context))
|
||||
k("DirectAudio for games", SessionPrefs.directAudio(context))
|
||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||
@@ -303,8 +308,7 @@ object DeviceReport {
|
||||
})
|
||||
|
||||
h("Android process limits")
|
||||
k("Guest-worker handoff available", com.droiddeck.launcher.runtime.GuestWorkers.enabled(context))
|
||||
k("Session root in guest worker", com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted ?: "no session")
|
||||
k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context)))
|
||||
|
||||
h("Device switch files")
|
||||
SessionService.envSwitchFile(context)?.takeIf { it.isFile }?.let { f ->
|
||||
|
||||
@@ -81,7 +81,7 @@ object NetworkReport {
|
||||
append("\netc/droiddeck-net (the link as the session sees it):\n")
|
||||
FileUtils.readString(netdev)?.lines()?.forEach { append(" ").append(it).append('\n') }
|
||||
}
|
||||
append("\nThe session uses the phone's connection\n")
|
||||
append("\nproot makes no network namespace, so the session uses the phone's connection\n")
|
||||
append("directly: IPv4 and IPv6 both pass through, and there is nothing to forward.\n")
|
||||
append("Steam reads Android's transport, connectivity and metering through the runtime's\n")
|
||||
append("NetworkManager D-Bus bridge. Android settings manage Wi-Fi and cellular connections.\n")
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
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,
|
||||
UNREADABLE,
|
||||
}
|
||||
|
||||
object PhantomProcessLimit {
|
||||
private const val SETTING = "settings_enable_monitor_phantom_procs"
|
||||
|
||||
private const val MAX_PHANTOM = "2147483647"
|
||||
private const val PREFS = "phantom-process-limit"
|
||||
private const val PREF_ANDROID_12_OFF = "android12-off"
|
||||
|
||||
fun usesDeviceConfig(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk == Build.VERSION_CODES.S
|
||||
|
||||
fun shellCommands(enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): List<String> = when {
|
||||
usesDeviceConfig(sdk) && enabled -> listOf(
|
||||
"device_config delete activity_manager max_phantom_processes",
|
||||
"device_config set_sync_disabled_for_tests none",
|
||||
"settings put global $SETTING true",
|
||||
)
|
||||
usesDeviceConfig(sdk) -> listOf(
|
||||
"device_config set_sync_disabled_for_tests persistent",
|
||||
"device_config put activity_manager max_phantom_processes $MAX_PHANTOM",
|
||||
"settings put global $SETTING false",
|
||||
)
|
||||
else -> listOf("settings put global $SETTING ${if (enabled) "true" else "false"}")
|
||||
}
|
||||
|
||||
fun verifyCommand(sdk: Int = Build.VERSION.SDK_INT): String =
|
||||
if (usesDeviceConfig(sdk)) "device_config get activity_manager max_phantom_processes"
|
||||
else "settings get global $SETTING"
|
||||
|
||||
fun verified(output: String, enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): Boolean {
|
||||
val value = output.trim()
|
||||
return if (usesDeviceConfig(sdk)) (value == MAX_PHANTOM) != enabled
|
||||
else value == if (enabled) "true" else "false"
|
||||
}
|
||||
|
||||
fun adbCommand(enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): String =
|
||||
shellCommands(enabled, sdk).joinToString(" && ") { "adb shell $it" }
|
||||
|
||||
fun adbCommand(): String = adbCommand(false)
|
||||
|
||||
fun rememberAndroid12(context: Context, off: Boolean) {
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(PREF_ANDROID_12_OFF, off).apply()
|
||||
}
|
||||
|
||||
fun read(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
|
||||
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
|
||||
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 {
|
||||
GlobalSettings.read(context, SETTING)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
return android12Status(off, global, systemProperty(OVERRIDE_PROPERTY))
|
||||
}
|
||||
val global = try {
|
||||
GlobalSettings.read(context, SETTING)
|
||||
} catch (_: Exception) {
|
||||
return PhantomProcessStatus.UNREADABLE
|
||||
}
|
||||
return status(global, systemProperty(OVERRIDE_PROPERTY))
|
||||
}
|
||||
|
||||
fun android12Status(rememberedOff: Boolean, global: String?, override: String?): PhantomProcessStatus =
|
||||
if (rememberedOff || status(global, override) == PhantomProcessStatus.DISABLED) PhantomProcessStatus.DISABLED
|
||||
else PhantomProcessStatus.UNREADABLE
|
||||
|
||||
fun status(global: String?, override: String?): PhantomProcessStatus {
|
||||
val value = global?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
|
||||
?: override?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
|
||||
return when (value) {
|
||||
"false", "0" -> PhantomProcessStatus.DISABLED
|
||||
null -> PhantomProcessStatus.UNSET
|
||||
else -> PhantomProcessStatus.ENABLED
|
||||
}
|
||||
}
|
||||
|
||||
private const val OVERRIDE_PROPERTY = "persist.sys.fflag.override.$SETTING"
|
||||
|
||||
private fun systemProperty(name: String): String? = try {
|
||||
Class.forName("android.os.SystemProperties")
|
||||
.getMethod("get", String::class.java)
|
||||
.invoke(null, name) as? String
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
fun hasDeveloperToggle(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
|
||||
|
||||
fun blocksSteam(status: PhantomProcessStatus): Boolean =
|
||||
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED &&
|
||||
status != PhantomProcessStatus.UNCOUNTED
|
||||
|
||||
fun title(context: Context, status: PhantomProcessStatus): String = context.getString(when (status) {
|
||||
PhantomProcessStatus.ENABLED -> R.string.phantom_title_on
|
||||
PhantomProcessStatus.UNSET -> R.string.phantom_title_unset
|
||||
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) {
|
||||
PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE ->
|
||||
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) {
|
||||
PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence(context)
|
||||
else -> instructions(context, status)
|
||||
}
|
||||
|
||||
fun fixSentence(context: Context, sdk: Int = Build.VERSION.SDK_INT): String =
|
||||
context.getString(if (hasDeveloperToggle(sdk)) R.string.phantom_fix_toggle else R.string.phantom_fix_no_toggle)
|
||||
|
||||
fun reportValue(status: PhantomProcessStatus): String = when (status) {
|
||||
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
|
||||
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
|
||||
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)"
|
||||
}
|
||||
}
|
||||
@@ -161,13 +161,7 @@ object WirelessAdbFix {
|
||||
}
|
||||
}.getOrDefault(address is Inet4Address)
|
||||
|
||||
fun verifyLocalPairing(context: Context) {
|
||||
val port = localConnectPort(context) ?: error(context.getString(R.string.adbpair_command_failed))
|
||||
check(acceptsKey(context, LOOPBACK, port)) { context.getString(R.string.adbpair_command_failed) }
|
||||
saveConnection(context, LOOPBACK, port)
|
||||
}
|
||||
|
||||
private fun localConnectPort(context: Context): Int? =
|
||||
fun localConnectPort(context: Context): Int? =
|
||||
tlsPortProperty()
|
||||
?: findConnectPort(context, LOOPBACK)
|
||||
|
||||
@@ -248,6 +242,26 @@ object WirelessAdbFix {
|
||||
return resolvedPort.get().takeIf { it in 1..65535 }
|
||||
}
|
||||
|
||||
fun setChildProcessLimit(context: Context, host: String, port: Int, enabled: Boolean) {
|
||||
loadOrCreateIdentity(context.applicationContext)
|
||||
Kadb.create(host, port).use { adb ->
|
||||
PhantomProcessLimit.shellCommands(enabled).forEach { command ->
|
||||
val change = adb.shell(command)
|
||||
check(change.exitCode == 0) { change.allOutput.ifBlank { context.getString(R.string.adbfix_command_failed, change.exitCode) } }
|
||||
}
|
||||
val result = adb.shell(PhantomProcessLimit.verifyCommand())
|
||||
check(result.exitCode == 0 && PhantomProcessLimit.verified(result.output, enabled)) {
|
||||
context.getString(R.string.adbfix_not_confirmed, result.allOutput.trim())
|
||||
}
|
||||
}
|
||||
if (PhantomProcessLimit.usesDeviceConfig()) PhantomProcessLimit.rememberAndroid12(context, !enabled)
|
||||
saveConnection(context, host, port)
|
||||
}
|
||||
|
||||
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
|
||||
withSavedPairing(context) { appContext, host, port -> setChildProcessLimit(appContext, host, port, enabled) }
|
||||
}
|
||||
|
||||
fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null
|
||||
|
||||
fun savedPairingIsLocal(context: Context): Boolean = savedConnection(context.applicationContext)?.host
|
||||
|
||||
@@ -38,6 +38,7 @@ class WirelessAdbPairingService : Service() {
|
||||
private var pairingHost: String? = null
|
||||
private var pairingPort: Int? = null
|
||||
@Volatile private var working = false
|
||||
@Volatile private var limitEnabled = false
|
||||
@Volatile private var session = 0
|
||||
private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) }
|
||||
|
||||
@@ -51,14 +52,15 @@ class WirelessAdbPairingService : Service() {
|
||||
onCode(code)
|
||||
}
|
||||
ACTION_CANCEL -> finish(Stage.Idle)
|
||||
else -> begin()
|
||||
else -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true)
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun begin() {
|
||||
private fun begin(enableLimit: Boolean) {
|
||||
if (working) return
|
||||
session++
|
||||
limitEnabled = enableLimit
|
||||
pairingHost = null
|
||||
pairingPort = null
|
||||
working = false
|
||||
@@ -121,6 +123,7 @@ class WirelessAdbPairingService : Service() {
|
||||
}
|
||||
working = true
|
||||
val owner = session
|
||||
val enable = limitEnabled
|
||||
show(Stage.Working(getString(R.string.adbpair_pairing)))
|
||||
Thread({
|
||||
val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } }
|
||||
@@ -138,7 +141,12 @@ class WirelessAdbPairingService : Service() {
|
||||
stopDiscovery()
|
||||
show(Stage.Working(getString(R.string.adbpair_connecting)))
|
||||
}
|
||||
val result = runCatching { WirelessAdbFix.verifyLocalPairing(this) }
|
||||
val result = runCatching {
|
||||
val connectPort = WirelessAdbFix.localConnectPort(this)
|
||||
?: error(getString(R.string.adbpair_port_not_found))
|
||||
main.post { if (owner == session) show(Stage.Working(getString(R.string.adbpair_applying))) }
|
||||
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, enable)
|
||||
}
|
||||
main.post {
|
||||
working = false
|
||||
if (owner != session) return@post
|
||||
@@ -227,15 +235,15 @@ class WirelessAdbPairingService : Service() {
|
||||
.addAction(Notification.Action.Builder(null, getString(R.string.common_cancel), cancel).build())
|
||||
}
|
||||
is Stage.Working -> builder
|
||||
.setContentTitle(getString(R.string.adbpair_title_pair))
|
||||
.setContentTitle(getString(R.string.adbpair_title_working))
|
||||
.setContentText(stage.step)
|
||||
.setProgress(0, 0, true)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
Stage.Done -> builder
|
||||
.setContentTitle(getString(R.string.adbpair_paired))
|
||||
.setContentText(getString(R.string.adbpair_return_to_app))
|
||||
.setStyle(Notification.BigTextStyle().bigText(getString(R.string.adbpair_return_to_app)))
|
||||
.setContentTitle(getString(R.string.adbpair_title_done))
|
||||
.setContentText(getString(R.string.adbpair_done_text))
|
||||
.setStyle(Notification.BigTextStyle().bigText(getString(R.string.adbpair_done_text)))
|
||||
.setAutoCancel(true)
|
||||
is Stage.Failed -> builder
|
||||
.setContentTitle(getString(R.string.adbpair_title_failed))
|
||||
@@ -254,6 +262,7 @@ class WirelessAdbPairingService : Service() {
|
||||
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
|
||||
private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
|
||||
private const val KEY_CODE = "code"
|
||||
private const val EXTRA_ENABLE_LIMIT = "enable_limit"
|
||||
private const val TIMEOUT_MS = 5 * 60_000L
|
||||
|
||||
private val current = MutableStateFlow<Stage>(Stage.Idle)
|
||||
@@ -261,10 +270,10 @@ class WirelessAdbPairingService : Service() {
|
||||
|
||||
private fun publish(stage: Stage) { current.value = stage }
|
||||
|
||||
fun start(context: Context) {
|
||||
fun start(context: Context, enableLimit: Boolean = false) {
|
||||
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
|
||||
publish(Stage.Waiting)
|
||||
val intent = Intent(context, WirelessAdbPairingService::class.java)
|
||||
val intent = Intent(context, WirelessAdbPairingService::class.java).putExtra(EXTRA_ENABLE_LIMIT, enableLimit)
|
||||
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.runtime
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.os.StatFs
|
||||
import android.system.Os
|
||||
import android.util.Log
|
||||
import androidx.annotation.StringRes
|
||||
import com.droiddeck.launcher.R
|
||||
@@ -115,6 +116,7 @@ object AppImageManager {
|
||||
|
||||
private fun extract(context: Context, dir: File, file: File, onProgress: (String) -> Unit): String? {
|
||||
val image = File(dir, "image.AppImage")
|
||||
val links = File(dir, ".links").apply { mkdirs() }
|
||||
try {
|
||||
dir.mkdirs()
|
||||
onProgress(context.getString(R.string.user_apps_copying, file.name))
|
||||
@@ -129,15 +131,30 @@ object AppImageManager {
|
||||
"cd \"$1\" && rm -rf squashfs-root AppDir && { $unpack; } >/dev/null && " +
|
||||
"rm -rf app && mv \"$(readlink -f squashfs-root)\" app && rm -f squashfs-root",
|
||||
"extract", "$GUEST_DIR/${dir.name}",
|
||||
), logName = "appimage-import") { line -> if (out.length < 2000) out.appendLine(line) }
|
||||
), logName = "appimage-import", linkDir = links) { line -> if (out.length < 2000) out.appendLine(line) }
|
||||
if (status != 0 || !File(dir, "app").isDirectory) {
|
||||
listOf("squashfs-root", "AppDir").forEach { FileUtils.delete(File(dir, it)) }
|
||||
return out.lines().lastOrNull { it.isNotBlank() }?.let { context.getString(R.string.appimg_extract_failed_detail, it) }
|
||||
?: context.getString(R.string.appimg_extract_failed)
|
||||
}
|
||||
copyLinkedFiles(File(dir, "app"), links)
|
||||
return null
|
||||
} finally {
|
||||
image.delete()
|
||||
FileUtils.delete(links)
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyLinkedFiles(app: File, links: File) {
|
||||
val roots = setOf(links.path + "/", links.canonicalPath + "/")
|
||||
app.walkTopDown().onEnter { !Files.isLink(it) }.forEach { f ->
|
||||
if (!Files.isLink(f)) return@forEach
|
||||
val target = runCatching { Os.readlink(f.path) }.getOrNull() ?: return@forEach
|
||||
if (roots.none { target.startsWith(it) }) return@forEach
|
||||
val data = f.toPath().toRealPath()
|
||||
java.nio.file.Files.delete(f.toPath())
|
||||
java.nio.file.Files.copy(data, f.toPath())
|
||||
if (java.nio.file.Files.isExecutable(data)) f.setExecutable(true, false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -397,7 +397,7 @@ object BwrapSpawner {
|
||||
|
||||
/**
|
||||
* The sandbox started by the runtime's own glibc loader with the native hook, which maps the
|
||||
* sandbox's mounts; null when the runtime cannot load the hook (older glibc).
|
||||
* sandbox's mounts; null when the runtime cannot load the hook (older glibc), so proot runs it.
|
||||
*/
|
||||
private fun nativeLaunch(context: Context, plan: Plan): Pair<List<String>, Map<String, String>>? {
|
||||
val rootfs = LinuxRuntime.rootDir(context)
|
||||
@@ -415,15 +415,15 @@ object BwrapSpawner {
|
||||
val need = glibcMinor(hook, GLIBC_NEED) { it.maxOrNull() } ?: return null
|
||||
val have = glibcMinor(libc, GLIBC_RELEASE) { it.firstOrNull() } ?: return null
|
||||
if (have < need) {
|
||||
Log.i(TAG, "native userland: this runtime's glibc 2.$have cannot load the hook (2.$need)")
|
||||
Log.i(TAG, "native userland: this runtime's glibc 2.$have cannot load the hook (2.$need); proot runs the sandbox")
|
||||
return null
|
||||
}
|
||||
for (file in listOf(loader, libc)) {
|
||||
val key = "${file.path}:${file.length()}:${file.lastModified()}"
|
||||
if (key in seccompPatched) continue
|
||||
// an unpatched loader or libc dies under Android's filter before the hook loads
|
||||
// an unpatched loader or libc dies under Android's filter before the hook loads: proot runs it
|
||||
val patched = runCatching { ElfSeccompPatch.patchFile(file) }
|
||||
.onFailure { Log.e(TAG, "native userland: could not patch $file for Android's seccomp filter", it) }
|
||||
.onFailure { Log.e(TAG, "native userland: could not patch $file for Android's seccomp filter; proot runs the sandbox", it) }
|
||||
if (patched.isFailure) return null
|
||||
seccompPatched.add("${file.path}:${file.length()}:${file.lastModified()}")
|
||||
}
|
||||
@@ -496,7 +496,7 @@ object BwrapSpawner {
|
||||
* The kernel follows paths the hook does not see (ld.so, symbolic links), so each top-level
|
||||
* mount of the sandbox is also a link to its source in the sandbox's own root, and the
|
||||
* sandbox's links with absolute guest targets are made relative, which reaches them through those.
|
||||
* False when a mount's place could not be made. The mount normally hides
|
||||
* False when a mount's place could not be made; proot then runs the sandbox, whose mounts hide
|
||||
* whatever was left at their places.
|
||||
*/
|
||||
private fun linkMounts(plan: Plan): Boolean {
|
||||
@@ -524,7 +524,7 @@ object BwrapSpawner {
|
||||
}
|
||||
}
|
||||
} catch (e: java.io.IOException) {
|
||||
Log.e(TAG, "native userland: could not make a place for ${bind.guest}", e)
|
||||
Log.e(TAG, "native userland: could not make a place for ${bind.guest}; proot runs the sandbox", e)
|
||||
return false
|
||||
} ?: continue
|
||||
val path = at.toPath()
|
||||
@@ -558,12 +558,38 @@ object BwrapSpawner {
|
||||
return f
|
||||
}
|
||||
|
||||
internal fun prootEnvironment(plan: Plan, startsThroughEnvTool: Boolean): Map<String, String> =
|
||||
if (startsThroughEnvTool) emptyMap() else plan.env - "LD_PRELOAD"
|
||||
|
||||
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
|
||||
val (command, environment) = nativeLaunch(context, plan)
|
||||
?: throw IOException("The sandbox does not have a compatible native runtime")
|
||||
val builder = ProcessBuilder(command).redirectErrorStream(true)
|
||||
.directory(File(hostPath(plan.binds, plan.root.path, plan.cwd)).takeIf { it.isDirectory } ?: plan.root)
|
||||
.also { b -> b.environment().apply { clear(); putAll(environment) } }
|
||||
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
|
||||
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
|
||||
val builder = if (native != null) {
|
||||
ProcessBuilder(native.first).redirectErrorStream(true)
|
||||
.directory(File(hostPath(plan.binds, plan.root.path, plan.cwd)).takeIf { it.isDirectory } ?: plan.root)
|
||||
.also { b -> b.environment().apply { clear(); putAll(native.second) } }
|
||||
} else {
|
||||
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
|
||||
if (verbose != null) { cmd.add("-v"); cmd.add(verbose.toString()) }
|
||||
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
|
||||
val envTool = hasEnvTool(plan)
|
||||
if (envTool) {
|
||||
cmd.add(plan.envTool)
|
||||
cmd.add("-i")
|
||||
plan.env.forEach { (k, v) -> cmd.add("$k=$v") }
|
||||
}
|
||||
cmd.addAll(plan.argv)
|
||||
ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b ->
|
||||
b.environment().apply {
|
||||
clear()
|
||||
putAll(prootEnvironment(plan, envTool))
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
val process = builder.start()
|
||||
val pid = HostProcess.pidOf(process)
|
||||
com.droiddeck.launcher.session.OrphanReaper.keep(pid)
|
||||
@@ -591,8 +617,8 @@ object BwrapSpawner {
|
||||
while (true) {
|
||||
val n = try { stream.read(buffer) } catch (e: IOException) { -1 }
|
||||
if (n < 0) break
|
||||
if (logged < 4096) {
|
||||
String(buffer, 0, minOf(n, 4096 - logged)).lines().filter { it.isNotBlank() }
|
||||
if (logged < 4096 || verbose != null) {
|
||||
String(buffer, 0, if (verbose != null) n else minOf(n, 4096 - logged)).lines().filter { it.isNotBlank() }
|
||||
.forEach { Log.i(TAG, "sandbox $id: $it") }
|
||||
logged += n
|
||||
}
|
||||
|
||||
@@ -168,7 +168,7 @@ object CurseForgeApp {
|
||||
}
|
||||
|
||||
internal var guest: (Context, List<String>, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine ->
|
||||
GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context),
|
||||
GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true,
|
||||
cancelled = cancelled, redact = INSPECTOR, onLine = onLine)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,8 @@ import java.nio.ByteOrder
|
||||
* dynamic linker makes the first two before any preloaded library (so before the hook's SIGSYS
|
||||
* handler) exists, so the call sites in the rootfs's ld.so and libc answer by themselves instead: the
|
||||
* `svc` after `mov x8, #nr` becomes a no-op for set_robust_list (glibc ignores the result) and
|
||||
* `mov x0, #-ENOSYS` for rseq and clone3 (glibc falls back from both).
|
||||
* `mov x0, #-ENOSYS` for rseq and clone3 (glibc falls back from both). Under proot the same
|
||||
* answers are what proot gives.
|
||||
*/
|
||||
object ElfSeccompPatch {
|
||||
private const val SVC = 0xd4000001.toInt()
|
||||
|
||||
@@ -79,9 +79,9 @@ object FlatpakManager {
|
||||
?.maxByOrNull { it.first }?.second
|
||||
}
|
||||
|
||||
private fun runGuest(context: Context, argv: List<String>, onLine: (String) -> Unit): Int {
|
||||
private fun runGuest(context: Context, argv: List<String>, fakeRoot: Boolean, onLine: (String) -> Unit): Int {
|
||||
val name = "flatpak-" + (argv.getOrNull(2)?.takeIf { argv.getOrNull(1) == HELPER } ?: "setup")
|
||||
return GuestCommand.run(context, argv, name, onLine = onLine)
|
||||
return GuestCommand.run(context, argv, fakeRoot, name, onLine = onLine)
|
||||
}
|
||||
|
||||
private inline fun <T> exclusive(what: String, ifBusy: () -> T, block: () -> T): T {
|
||||
@@ -96,7 +96,7 @@ object FlatpakManager {
|
||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||
return exclusive("setup", { context.getString(R.string.flatpakmgr_busy) }) {
|
||||
var failure: String? = null
|
||||
val status = runGuest(context, listOf("/bin/bash", SETUP)) { line ->
|
||||
val status = runGuest(context, listOf("/bin/bash", SETUP), fakeRoot = true) { line ->
|
||||
Log.i(TAG, "setup: $line")
|
||||
when {
|
||||
line.startsWith("== STEP ") -> onProgress(line.removePrefix("== STEP "), -1)
|
||||
@@ -120,7 +120,7 @@ object FlatpakManager {
|
||||
var error: String? = null
|
||||
var step = context.getString(R.string.flatpakmgr_starting)
|
||||
val argv = listOfNotNull("/usr/bin/python3", HELPER, verb, id)
|
||||
val status = runGuest(context, argv) { line ->
|
||||
val status = runGuest(context, argv, fakeRoot = false) { line ->
|
||||
val o = runCatching { JSONObject(line) }.getOrNull()
|
||||
if (o == null) { Log.i(TAG, "$verb: $line"); return@runGuest }
|
||||
when (o.optString("e")) {
|
||||
@@ -195,7 +195,7 @@ object FlatpakManager {
|
||||
if (!ready(context)) return emptySet()
|
||||
var apps: Set<String>? = null
|
||||
exclusive("updates", {}) {
|
||||
runGuest(context, listOf("/usr/bin/python3", HELPER, "updates")) { line ->
|
||||
runGuest(context, listOf("/usr/bin/python3", HELPER, "updates"), fakeRoot = false) { line ->
|
||||
val o = runCatching { JSONObject(line) }.getOrNull() ?: return@runGuest
|
||||
if (o.optString("e") == "updates") {
|
||||
val a = o.optJSONArray("apps")
|
||||
|
||||
@@ -6,12 +6,13 @@ import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.session.OrphanReaper
|
||||
import com.droiddeck.launcher.session.SessionFiles
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object GuestCommand {
|
||||
fun run(context: Context, argv: List<String>, logName: String? = null,
|
||||
extraBinds: List<String>? = null, cancelled: AtomicBoolean? = null,
|
||||
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
|
||||
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
|
||||
redact: Regex? = null, onLine: (String) -> Unit): Int {
|
||||
val log = logName?.let {
|
||||
try {
|
||||
@@ -20,7 +21,7 @@ object GuestCommand {
|
||||
}
|
||||
log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}")
|
||||
try {
|
||||
return runLogged(context, argv, extraBinds, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) }
|
||||
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) }
|
||||
} finally {
|
||||
log?.close()
|
||||
}
|
||||
@@ -28,14 +29,16 @@ object GuestCommand {
|
||||
|
||||
internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "<redacted>") ?: text
|
||||
|
||||
private fun runLogged(context: Context, argv: List<String>, extraBinds: List<String>?,
|
||||
cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
|
||||
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
|
||||
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
SessionFiles.stage(context, root)
|
||||
LinuxNetworkLinkComponent(context, root).publish()
|
||||
val runtimeDir = File(context.filesDir, ".flatpak-rt").apply { mkdirs() }
|
||||
val binds = LinuxRuntime.binds(context, null, runtimeDir, LinuxRuntime.sharedStorage(context), extraBinds)
|
||||
val native = NativeGuest.forSession(context)
|
||||
val fastPathKey = if (!native && fastPath && !fakeRoot && linkDir == null && ProotFastPath.enabled(context)) ProotFastPath.key(root, binds) else null
|
||||
val guest = mutableListOf(
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
|
||||
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
|
||||
@@ -50,8 +53,26 @@ object GuestCommand {
|
||||
"no_proxy=localhost,127.0.0.1,::1", "NO_PROXY=localhost,127.0.0.1,::1",
|
||||
)
|
||||
}
|
||||
fastPathKey?.let { guest += ProotFastPath.guestEnv(root, binds, it) }
|
||||
guest += argv
|
||||
val builder = NativeGuest.processBuilder(context, root, binds, guest).redirectErrorStream(true)
|
||||
val builder = if (native) {
|
||||
NativeGuest.processBuilder(context, root, binds, guest).redirectErrorStream(true)
|
||||
} else {
|
||||
val cmd = LinuxRuntime.prootPrefix(context, root, "/root", fakeRoot)
|
||||
if (linkDir != null) cmd.add("--link2symlink")
|
||||
binds.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
cmd += guest
|
||||
ProcessBuilder(cmd).directory(root).redirectErrorStream(true).also { b ->
|
||||
b.environment().apply {
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cancelled?.get() == true) return 130
|
||||
val process = builder.start()
|
||||
val pid = HostProcess.pidOf(process)
|
||||
|
||||
@@ -20,6 +20,7 @@ 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
|
||||
@@ -224,6 +225,70 @@ 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 {
|
||||
@@ -250,7 +315,28 @@ object GuestWorkers {
|
||||
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,
|
||||
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) {
|
||||
@@ -309,14 +395,22 @@ object GuestWorkers {
|
||||
@Volatile var context: Context? = null
|
||||
private set
|
||||
|
||||
/** Whether this Android version and runtime can hand off guest programs to workers. */
|
||||
/** 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 &&
|
||||
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 } }
|
||||
|
||||
@@ -553,28 +647,34 @@ object GuestWorkers {
|
||||
|
||||
private fun reportEnd(app: Context, slot: Slot) {
|
||||
val onExit = slot.onExit ?: return
|
||||
Thread({ onExit(exitStatus(app, slot.pid)) }, "guest-worker-exit").start()
|
||||
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): Int {
|
||||
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 recorded = false
|
||||
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 {
|
||||
recorded = true
|
||||
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 it.status and 0x7f
|
||||
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 OsConstants.SIGKILL
|
||||
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 (recorded) OsConstants.SIGKILL else -1
|
||||
return if (record != null) killed(OsConstants.SIGKILL) else -1
|
||||
}
|
||||
|
||||
/** The pids of session [of]'s guest programs running in workers. */
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package com.droiddeck.launcher.runtime;
|
||||
|
||||
import com.droiddeck.launcher.core.AddonPack;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.os.Process;
|
||||
import android.system.ErrnoException;
|
||||
import android.system.Os;
|
||||
import android.system.StructStat;
|
||||
import android.system.StructUtsname;
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver;
|
||||
import com.droiddeck.launcher.session.SessionPrefs;
|
||||
|
||||
@@ -55,8 +58,70 @@ public final class LinuxRuntime {
|
||||
return dir;
|
||||
}
|
||||
|
||||
public static File prootTempDir(Context context) {
|
||||
File dir = new File(liveDir(context), "proot");
|
||||
dir.mkdirs();
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static final String HOST_DIR = "opt/android-host";
|
||||
public static final String PROOT_PACK = "add-on pack";
|
||||
public static final String PROOT_ROOTFS = "rootfs fallback";
|
||||
public static final String PROOT_MISSING = "missing";
|
||||
|
||||
private static File rootfsProot(Context context) {
|
||||
return new File(rootDir(context), HOST_DIR + "/proot");
|
||||
}
|
||||
|
||||
private static File rootfsLoader(Context context) {
|
||||
return new File(rootDir(context), HOST_DIR + "/loader");
|
||||
}
|
||||
|
||||
private static boolean rootfsProotReady(Context context) {
|
||||
return Build.VERSION.SDK_INT < 29 && rootfsProot(context).isFile() && rootfsLoader(context).isFile();
|
||||
}
|
||||
|
||||
/** proot execs its loader, and targetSdk 29+ may exec only the APK's libraries, which hold the pack's matching loader. */
|
||||
public static boolean stockProotAllowed(Context context) {
|
||||
return Build.VERSION.SDK_INT < 29 && SessionPrefs.allowStockProot(context);
|
||||
}
|
||||
|
||||
/** Android 10+ refuses to execute files from app data for targetSdk 29+, but executes the APK's extracted libraries. */
|
||||
private static File bundledLoader(Context context) {
|
||||
File file = new File(context.getApplicationInfo().nativeLibraryDir, "libproot-loader.so");
|
||||
return file.isFile() ? file : null;
|
||||
}
|
||||
|
||||
public static boolean patchedProot(Context context) {
|
||||
return AddonPack.PROOT.installed(context);
|
||||
}
|
||||
|
||||
public static File prootBinary(Context context) {
|
||||
if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot.so");
|
||||
if (stockProotAllowed(context)) return rootfsProot(context);
|
||||
return AddonPack.PROOT.file(context, "libproot.so");
|
||||
}
|
||||
|
||||
public static File prootLoader(Context context) {
|
||||
File bundled = bundledLoader(context);
|
||||
if (AddonPack.PROOT.installed(context)) return bundled != null ? bundled : AddonPack.PROOT.file(context, "libproot-loader.so");
|
||||
if (stockProotAllowed(context)) return rootfsLoader(context);
|
||||
return bundled != null ? bundled : AddonPack.PROOT.file(context, "libproot-loader.so");
|
||||
}
|
||||
|
||||
public static String prootSource(Context context) {
|
||||
File bin = prootBinary(context);
|
||||
if (!bin.isFile()) return PROOT_MISSING;
|
||||
return patchedProot(context) && !bin.equals(rootfsProot(context)) ? PROOT_PACK : PROOT_ROOTFS;
|
||||
}
|
||||
|
||||
public static String prootLibraryPath(Context context) {
|
||||
File dir = new File(rootDir(context), HOST_DIR);
|
||||
return dir.equals(prootBinary(context).getParentFile()) ? dir.getPath() : "";
|
||||
}
|
||||
|
||||
public static boolean isInstalled(Context context) {
|
||||
return hasRootfs(context) && NativeGuest.INSTANCE.loader(rootDir(context)) != null;
|
||||
return hasRootfs(context) && (patchedProot(context) || rootfsProotReady(context));
|
||||
}
|
||||
|
||||
public static boolean hasRootfs(Context context) {
|
||||
@@ -77,9 +142,42 @@ public final class LinuxRuntime {
|
||||
return manifests.length > 0 ? manifests[0] : null;
|
||||
}
|
||||
|
||||
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> guestCommand) {
|
||||
return command(context, sessionRoot, runtimeDir, externalStorage, null, guestCommand);
|
||||
}
|
||||
|
||||
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds,
|
||||
List<String> guestCommand) {
|
||||
return command(context, sessionRoot, runtimeDir, externalStorage, extraBinds, guestCommand, false);
|
||||
}
|
||||
|
||||
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds,
|
||||
List<String> guestCommand, boolean fakeRoot) {
|
||||
File root = rootDir(context);
|
||||
List<String> binds = binds(context, sessionRoot, runtimeDir, externalStorage, extraBinds);
|
||||
if (sessionRoot != null) lastBinds = binds;
|
||||
return commandWithBinds(context, root, binds, guestCommand, fakeRoot);
|
||||
}
|
||||
|
||||
public static List<String> commandWithBinds(Context context, File root, List<String> binds,
|
||||
List<String> guestCommand) {
|
||||
return commandWithBinds(context, root, binds, guestCommand, false);
|
||||
}
|
||||
|
||||
public static List<String> commandWithBinds(Context context, File root, List<String> binds,
|
||||
List<String> guestCommand, boolean fakeRoot) {
|
||||
List<String> cmd = fakeRoot ? rootPrefix(context, root, "/root") : prootPrefix(context, root, "/root");
|
||||
for (String spec : binds) bind(cmd, spec);
|
||||
cmd.addAll(guestCommand);
|
||||
return cmd;
|
||||
}
|
||||
|
||||
private static volatile List<String> lastBinds;
|
||||
|
||||
/** The mounts of the running session, which sandboxes and root helpers see too. */
|
||||
/** The mounts of a session started without proot, which sandboxes and root helpers see too. */
|
||||
public static void rememberSessionBinds(List<String> binds) {
|
||||
lastBinds = binds;
|
||||
}
|
||||
@@ -95,6 +193,36 @@ public final class LinuxRuntime {
|
||||
return SessionPrefs.mountSharedStorage(context) ? android.os.Environment.getExternalStorageDirectory() : null;
|
||||
}
|
||||
|
||||
public static List<String> prootPrefix(Context context, File root, String cwd) {
|
||||
return prootPrefix(context, root, cwd, false);
|
||||
}
|
||||
|
||||
public static List<String> rootPrefix(Context context, File root, String cwd) {
|
||||
List<String> cmd = prootPrefix(context, root, cwd, true);
|
||||
cmd.add("--link2symlink");
|
||||
return cmd;
|
||||
}
|
||||
|
||||
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
|
||||
NativeGuest.relinkAfterProot(root);
|
||||
List<String> cmd = new ArrayList<>();
|
||||
cmd.addAll(com.droiddeck.launcher.core.HostProcess.dataExecutable(prootBinary(context).getPath()));
|
||||
cmd.add("--kill-on-exit");
|
||||
cmd.add("--kernel-release=" + guestUtsname(SessionPrefs.guestHostname(context)));
|
||||
int uid = Process.myUid();
|
||||
if (fakeRoot) {
|
||||
cmd.add("-0");
|
||||
} else {
|
||||
cmd.add("-i");
|
||||
cmd.add(uid + ":" + uid);
|
||||
}
|
||||
cmd.add("-r");
|
||||
cmd.add(root.getPath());
|
||||
cmd.add("-w");
|
||||
cmd.add(cwd);
|
||||
return cmd;
|
||||
}
|
||||
|
||||
public static List<String> binds(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds) {
|
||||
File root = rootDir(context);
|
||||
@@ -120,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());
|
||||
@@ -192,7 +320,9 @@ public final class LinuxRuntime {
|
||||
if (extraBinds != null) {
|
||||
for (String spec : extraBinds) bind(cmd, spec);
|
||||
}
|
||||
return cmd;
|
||||
List<String> specs = new ArrayList<>();
|
||||
for (int i = 0; i + 1 < cmd.size(); i += 2) specs.add(cmd.get(i + 1));
|
||||
return specs;
|
||||
}
|
||||
|
||||
private static void bindPowerVrGpuNode(Context context, List<String> cmd) {
|
||||
@@ -467,9 +597,16 @@ public final class LinuxRuntime {
|
||||
}
|
||||
|
||||
private static void bind(List<String> cmd, String spec) {
|
||||
cmd.add("-b");
|
||||
cmd.add(spec);
|
||||
}
|
||||
|
||||
static String guestUtsname(String hostname) {
|
||||
StructUtsname host = Os.uname();
|
||||
return "\\" + host.sysname + "\\" + hostname + "\\" + host.release
|
||||
+ "\\" + host.version + "\\" + host.machine + "\\localdomain\\-1\\";
|
||||
}
|
||||
|
||||
public static synchronized void writeAccounts(Context context) throws IOException {
|
||||
File root = rootDir(context);
|
||||
int uid = Process.myUid();
|
||||
|
||||
@@ -184,6 +184,10 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
};
|
||||
boolean desktop = DesktopCatalog.INSTANCE.desktopInstalled(app);
|
||||
if (packsOnly(app, release, progress)) {
|
||||
job.ok = true;
|
||||
return true;
|
||||
}
|
||||
job.ok = installOnce(app, release, progress);
|
||||
if (job.ok && desktop) keepDesktop(app, progress);
|
||||
return job.ok;
|
||||
@@ -352,6 +356,22 @@ public final class LinuxRuntimeInstaller {
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean packsOnly(Context context, Release release, ProgressListener listener) {
|
||||
if (!LinuxRuntime.hasRootfs(context) || LinuxRuntime.isInstalled(context) || !release.version.equals(rootfsVersion(context))) return false;
|
||||
File root = LinuxRuntime.rootDir(context);
|
||||
try {
|
||||
recoverInterruptedSwap(root, new File(root.getParentFile(), LinuxRuntime.DIR + ".new"), new File(root.getParentFile(), LinuxRuntime.DIR + ".old"));
|
||||
} catch (IOException e) {
|
||||
Log.w(TAG, "packs only: " + e);
|
||||
return false;
|
||||
}
|
||||
String downloading = context.getString(R.string.rtinst_downloading);
|
||||
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
|
||||
return AddonPack.PROOT.await(context, () -> true, packProgress(listener, downloading))
|
||||
&& AddonPack.DIRECTAUDIO.await(context, () -> true, packProgress(listener, downloading))
|
||||
&& LinuxRuntime.isInstalled(context);
|
||||
}
|
||||
|
||||
private static boolean installOnce(Context context, Release release, ProgressListener listener) {
|
||||
File archive = new File(context.getCacheDir(), archiveName(release));
|
||||
boolean keepPartial = false;
|
||||
@@ -363,6 +383,9 @@ public final class LinuxRuntimeInstaller {
|
||||
emptyTrash(LinuxRuntime.rootDir(context).getParentFile());
|
||||
String downloading = context.getString(R.string.rtinst_downloading);
|
||||
if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0);
|
||||
if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context, () -> true, packProgress(listener, downloading))
|
||||
&& !LinuxRuntime.stockProotAllowed(context))
|
||||
return fail("Cannot download proot", AddonPack.PROOT.getFailure());
|
||||
if (!AddonPack.DIRECTAUDIO.await(context, () -> true, packProgress(listener, downloading)))
|
||||
return fail("Cannot download DirectAudio", AddonPack.DIRECTAUDIO.getFailure());
|
||||
boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> {
|
||||
|
||||
@@ -6,7 +6,7 @@ import java.io.File
|
||||
import java.nio.file.Files
|
||||
|
||||
/**
|
||||
* Starts guest programs directly on the Android kernel: the glibc loader of the
|
||||
* Starts guest programs directly on the Android kernel, with no proot: the glibc loader of the
|
||||
* rootfs runs the program and [HOOK] translates the guest's absolute paths, execs and the system
|
||||
* calls Android's seccomp policy blocks, from inside the process.
|
||||
*/
|
||||
@@ -15,16 +15,24 @@ object NativeGuest {
|
||||
const val HOOK = "usr/lib/libddnatv-hook.so"
|
||||
private val LIB_DIRS = listOf("usr/lib", "usr/lib/aarch64-linux-gnu", "usr/local/lib", "usr/lib/systemd")
|
||||
|
||||
/** Libraries every guest program loads before the native hook. */
|
||||
/** Libraries every native program loads before the hook, as /etc/ld.so.preload does for proot. */
|
||||
fun preloadList(root: File): List<String> {
|
||||
val listed = File(root, "etc/droiddeck/native-preload").takeIf { it.isFile }?.readLines().orEmpty()
|
||||
return listed.map { it.trim() }.filter { it.startsWith("/") && File(root, it.removePrefix("/")).isFile }
|
||||
}
|
||||
|
||||
fun enabled(context: Context): Boolean =
|
||||
available(LinuxRuntime.rootDir(context))
|
||||
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
|
||||
|
||||
@Volatile var sessionPrepared = false
|
||||
/** The mode the running session started in; null between sessions. */
|
||||
@Volatile var sessionMode: Boolean? = null
|
||||
|
||||
/**
|
||||
* Whether a session's helpers (root commands, Flatpak sandboxes, installers) run natively: the
|
||||
* session's own mode while one runs, as the setting can change under it and the rootfs is only
|
||||
* prepared for native programs at a session's start.
|
||||
*/
|
||||
fun forSession(context: Context): Boolean = sessionMode ?: enabled(context)
|
||||
|
||||
/**
|
||||
* Development switch: etc/droiddeck/seccomp-sim names a helper (a guest path, then its arguments)
|
||||
@@ -85,7 +93,7 @@ object NativeGuest {
|
||||
|
||||
private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/"))
|
||||
|
||||
/** The environment of the session process: the hook's root, the guest mounts, the preload list. */
|
||||
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
|
||||
fun sessionEnvironment(root: File, binds: List<String>, program: String, hostname: String? = null): Map<String, String> {
|
||||
val preload = preloadList(root)
|
||||
return linkedMapOf(
|
||||
@@ -103,11 +111,9 @@ object NativeGuest {
|
||||
fun workingDirectory(root: File, binds: List<String>, cwd: String): File =
|
||||
File(BwrapSpawner.hostPath(binds.map { BwrapSpawner.Bind.parse(it) }, root.path, cwd)).takeIf { it.isDirectory } ?: root
|
||||
|
||||
/** A process for [guest] (argv) started with [binds], in guest directory [cwd]. */
|
||||
/** 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 {
|
||||
if (!available(root)) com.droiddeck.launcher.session.SessionFiles.stage(context, root)
|
||||
check(available(root)) { "The installed Linux runtime is missing its native loader or hook" }
|
||||
if (!sessionPrepared) prepare(context, root)
|
||||
if (sessionMode == null) prepare(context, root)
|
||||
return ProcessBuilder(command(root, guest.first(), guest.drop(1)))
|
||||
.directory(workingDirectory(root, binds, cwd))
|
||||
.also { builder ->
|
||||
@@ -168,15 +174,21 @@ object NativeGuest {
|
||||
|
||||
private const val RELINK_STAMP = "etc/droiddeck/native-symlinks"
|
||||
|
||||
@JvmStatic
|
||||
fun relinkAfterProot(root: File) {
|
||||
File(root, RELINK_STAMP).delete()
|
||||
}
|
||||
|
||||
private val HOST_LINK_TARGETS = listOf("/proc", "/dev", "/sys", "/sdcard", "/storage", "/data", "/system", "/vendor", "/apex",
|
||||
"/system_ext", "/product", "/odm", "/linkerconfig", "/mnt", "/root/Storage")
|
||||
|
||||
/**
|
||||
* Symbolic links the kernel follows by itself (ld.so, Steam, anything that skips the hook) read
|
||||
* their absolute target on Android's own filesystem. Rewrite rootfs links as relative paths so
|
||||
* the loader resolves them inside the guest. Rerun when the runtime changes.
|
||||
* their absolute target on Android's own filesystem. The image's links were made for proot,
|
||||
* which reads the target inside the rootfs, so each is rewritten as a relative link, which
|
||||
* resolves the same way under proot and without it. Rerun when the runtime changes.
|
||||
*/
|
||||
fun relinkAbsoluteSymlinks(context: Context, root: File): Int {
|
||||
fun relinkAbsoluteSymlinks(context: Context, root: File, commands: () -> Sequence<List<String>> = ::procCommands): Int {
|
||||
val stamp = File(root, RELINK_STAMP)
|
||||
val version = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(context).orEmpty() + "/3"
|
||||
if (stamp.isFile && stamp.readText() == version) return 0
|
||||
@@ -204,11 +216,20 @@ object NativeGuest {
|
||||
|
||||
override fun visitFileFailed(file: java.nio.file.Path, exc: java.io.IOException) = java.nio.file.FileVisitResult.CONTINUE
|
||||
})
|
||||
stamp.parentFile?.mkdirs()
|
||||
stamp.writeText(version)
|
||||
if (!prootRunning(LinuxRuntime.prootBinary(context).path, commands())) {
|
||||
stamp.parentFile?.mkdirs()
|
||||
stamp.writeText(version)
|
||||
}
|
||||
return rewritten
|
||||
}
|
||||
|
||||
internal fun prootRunning(proot: String, commands: Sequence<List<String>>): Boolean =
|
||||
commands.any { args -> args.take(2).any { it == proot } }
|
||||
|
||||
private fun procCommands(): Sequence<List<String>> = (File("/proc").listFiles() ?: emptyArray()).asSequence()
|
||||
.filter { it.name.all(Char::isDigit) }
|
||||
.mapNotNull { runCatching { File(it, "cmdline").readText().split('\u0000') }.getOrNull() }
|
||||
|
||||
/**
|
||||
* The guest path that host path [target] stands for in a session with [binds] ("src:dst"), or null
|
||||
* when it is a guest path already: the rootfs, or the longest mount source holding it (the first
|
||||
@@ -233,8 +254,8 @@ object NativeGuest {
|
||||
|
||||
/**
|
||||
* Wine prefixes' drive links (dosdevices) hold guest paths ("s:" -> /mnt/droiddeck-sd), which
|
||||
* the native hook follows inside a mount. Earlier builds pointed them at host paths, so convert
|
||||
* those links back to guest paths.
|
||||
* proot follows and the hook follows inside a mount. Earlier native sessions made them point at
|
||||
* their real places, which proot cannot see: those are given their guest paths back.
|
||||
*/
|
||||
fun relinkPrefixDrives(root: File, binds: List<String>): Int {
|
||||
val compatdata = listOf(File(root, "root/.local/share/Steam/steamapps/compatdata")) + binds.mapNotNull { spec ->
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
object ProotFastPath {
|
||||
private const val TAG = "ProotFastPath"
|
||||
const val LIBRARY = "/usr/local/lib/libddfastpath.so"
|
||||
const val MAX_BINDS = 256
|
||||
|
||||
fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean =
|
||||
preference && !noSeccomp && !nativeUserland && source == LinuxRuntime.PROOT_PACK
|
||||
|
||||
fun enabled(context: Context): Boolean {
|
||||
val preference = SessionPrefs.prootFastPath(context)
|
||||
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
|
||||
val nativeUserland = SessionPrefs.nativeUserland(context)
|
||||
val source = LinuxRuntime.prootSource(context)
|
||||
val on = allows(preference, noSeccomp, source, nativeUserland)
|
||||
if (preference && !noSeccomp && !nativeUserland && !on)
|
||||
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
|
||||
return on
|
||||
}
|
||||
|
||||
fun key(root: File, binds: List<String>): String? {
|
||||
if (binds.size > MAX_BINDS || binds.any { it.contains('|') } || root.path.contains('|')) return null
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest((root.path + "\n" + binds.joinToString("\n")).toByteArray())
|
||||
return digest.take(12).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
fun hostEnv(key: String): Pair<String, String> = "PROOT_FASTPATH" to key
|
||||
|
||||
fun guestEnv(root: File, binds: List<String>, key: String, sdk: Int = Build.VERSION.SDK_INT): List<String> = listOf(
|
||||
"PROOT_FP_ROOT=" + root.path,
|
||||
"PROOT_FP_BINDS=" + binds.joinToString("|"),
|
||||
"PROOT_FP_KEY=$key",
|
||||
"PROOT_FP_ANDROID_API=$sdk",
|
||||
)
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import android.os.Process
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.session.OrphanReaper
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.json.JSONObject
|
||||
import java.io.DataInputStream
|
||||
import java.io.DataOutputStream
|
||||
@@ -116,7 +117,22 @@ object RootSpawner {
|
||||
val guest = mutableListOf("/usr/bin/env", "-i")
|
||||
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> guest.add("$k=${e.getString(k)}") } }
|
||||
guest.addAll(argv)
|
||||
val builder = NativeGuest.processBuilder(context, root, binds, guest, cwd)
|
||||
val builder = if (NativeGuest.forSession(context)) {
|
||||
NativeGuest.processBuilder(context, root, binds, guest, cwd)
|
||||
} else {
|
||||
val cmd = LinuxRuntime.rootPrefix(context, root, cwd)
|
||||
binds.forEach { cmd.add("-b"); cmd.add(it) }
|
||||
cmd.addAll(guest)
|
||||
ProcessBuilder(cmd).directory(root).also { b ->
|
||||
b.environment().apply {
|
||||
clear()
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
val streams = listOf(stdio(fds.getOrNull(0), false), stdio(fds.getOrNull(1), true), stdio(fds.getOrNull(2), true))
|
||||
try {
|
||||
builder.redirectInput(streams[0].redirect ?: ProcessBuilder.Redirect.PIPE)
|
||||
|
||||
@@ -34,10 +34,12 @@ object BottomDesktop {
|
||||
val guest: List<String>,
|
||||
val binds: List<String>,
|
||||
val sessionRoot: File,
|
||||
val hostEnvironment: Array<String>,
|
||||
val root: File,
|
||||
val sessionDir: File,
|
||||
val generation: Int,
|
||||
val installed: Boolean,
|
||||
val nativeUserland: Boolean,
|
||||
val sharedStorage: File?,
|
||||
)
|
||||
|
||||
@@ -55,10 +57,10 @@ object BottomDesktop {
|
||||
private var service: Messenger? = null
|
||||
private var binding: ServiceConnection? = null
|
||||
private var pendingAttach: Message? = null
|
||||
/** The desktop guest's process: -1 when there is none, 0 while it is being started. */
|
||||
/** The desktop guest's proot: -1 when there is none, 0 while it is being started. */
|
||||
@Volatile private var guestPid = -1
|
||||
|
||||
/** The process to freeze with the session when it pauses. */
|
||||
/** The proot to freeze with the session when it pauses. */
|
||||
val suspendPid: Int get() = guestPid
|
||||
private var guestGeneration = 0
|
||||
var outputSize = 0 to 0
|
||||
@@ -85,14 +87,16 @@ object BottomDesktop {
|
||||
guest: List<String>,
|
||||
binds: List<String>,
|
||||
sessionRoot: File,
|
||||
hostEnvironment: Array<String>,
|
||||
root: File,
|
||||
sessionDir: File,
|
||||
generation: Int,
|
||||
nativeUserland: Boolean,
|
||||
sharedStorage: File?,
|
||||
stillCurrent: () -> Boolean,
|
||||
) {
|
||||
val prepared = Launch(ArrayList(guest), ArrayList(binds), sessionRoot, root, sessionDir, generation,
|
||||
DesktopCatalog.desktopInstalled(root), sharedStorage)
|
||||
val prepared = Launch(ArrayList(guest), ArrayList(binds), sessionRoot, hostEnvironment.copyOf(), root, sessionDir, generation,
|
||||
DesktopCatalog.desktopInstalled(root), nativeUserland, sharedStorage)
|
||||
synchronized(launchLock) { if (stillCurrent()) launch = prepared }
|
||||
}
|
||||
|
||||
@@ -215,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) } })
|
||||
}
|
||||
|
||||
@@ -320,9 +337,15 @@ object BottomDesktop {
|
||||
add("DD_IME_DIR=" + imeDir.path)
|
||||
add(SCRIPT)
|
||||
}
|
||||
val command = com.droiddeck.launcher.runtime.NativeGuest.command(current.root, guest.first(), guest.drop(1))
|
||||
val environment = com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
|
||||
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||
val command = if (current.nativeUserland) {
|
||||
com.droiddeck.launcher.runtime.NativeGuest.command(current.root, guest.first(), guest.drop(1))
|
||||
} else {
|
||||
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
||||
}
|
||||
val environment = if (current.nativeUserland) {
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
|
||||
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||
} else current.hostEnvironment
|
||||
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||
val pid = HostProcess.start(line, environment, current.root, { status ->
|
||||
main.post {
|
||||
@@ -333,7 +356,7 @@ object BottomDesktop {
|
||||
guestGeneration++
|
||||
setState(if (state == State.RUNNING || status == 0) State.ENDED else State.FAILED)
|
||||
}
|
||||
}, null, File(dir, "process.log"))
|
||||
}, null, File(dir, "proot.log"))
|
||||
main.post {
|
||||
if (generation != guestGeneration || launch !== current) {
|
||||
if (pid > 1) SessionService.stopTerminalProcess(context, pid)
|
||||
|
||||
@@ -217,7 +217,7 @@ object GraphicsReport {
|
||||
}
|
||||
if (guestLines.any { it.contains("MEM_EXEC_INIT") }) {
|
||||
appendLine("note: kbase refused KBASE_IOCTL_MEM_EXEC_INIT with EPERM. That answer comes from the kbase driver")
|
||||
appendLine(" itself (Android's seccomp would kill or return ENOSYS; SELinux")
|
||||
appendLine(" itself (proot does not filter ioctls; Android's seccomp would kill or return ENOSYS; SELinux")
|
||||
appendLine(" would return EACCES), so it is the kernel's policy for this context, not the session's.")
|
||||
}
|
||||
appendLine("-- driver lines from the session log (${guestLines.size})")
|
||||
|
||||
@@ -2,7 +2,7 @@ package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
|
||||
/** Finds the processes a session left running, including processes reparented to init. */
|
||||
/** Finds the processes a session left running, also once proot is gone and they belong to init. */
|
||||
object GuestLeftovers {
|
||||
private const val MARKER = "DD_DEBUG_DIR="
|
||||
|
||||
@@ -15,6 +15,7 @@ object GuestLeftovers {
|
||||
parentOf(proc)?.let { parents[pid] = it }
|
||||
if (pid in skip) return@forEach
|
||||
val exe = runCatching { File(proc, "exe").canonicalPath }.getOrNull()
|
||||
// proot runs a guest through its loader, which is then the process's executable
|
||||
if (exe?.startsWith(rootfs) == true ||
|
||||
marker != null && carries(runCatching { File(proc, "environ").readBytes() }.getOrNull(), marker)) {
|
||||
matched.add(pid)
|
||||
|
||||
@@ -47,11 +47,12 @@ object ProtonExtras {
|
||||
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
|
||||
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*aarch64\\.tar\\.(gz|xz)$")),
|
||||
// Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases.
|
||||
// Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases. No-proot only.
|
||||
Tool(BIONIC, "DroidDeck-Bionic", "DroidDeck-Bionic", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Bionic-.*aarch64\\.tar\\.(gz|xz)$"), prereleases = true),
|
||||
)
|
||||
|
||||
fun offered(context: Context): List<Tool> = tools.filter { it.id != BIONIC || LinuxRuntime.isInstalled(context) }
|
||||
/** The sources offered on this device: DroidDeck-Bionic only with Run without proot on. */
|
||||
fun offered(context: Context): List<Tool> = tools.filter { it.id != BIONIC || NativeGuest.enabled(context) }
|
||||
|
||||
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
|
||||
@@ -393,8 +394,20 @@ object ProtonExtras {
|
||||
internal fun guestProcess(context: Context, guest: List<String>): ProcessBuilder {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val runtimeDir = File(context.filesDir, ".proton-install-rt").apply { mkdirs() }
|
||||
return NativeGuest.processBuilder(context, root,
|
||||
LinuxRuntime.binds(context, null, runtimeDir, null, null), guest).redirectErrorStream(true)
|
||||
return if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) {
|
||||
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
|
||||
LinuxRuntime.binds(context, null, runtimeDir, null, null), guest).redirectErrorStream(true)
|
||||
} else {
|
||||
ProcessBuilder(LinuxRuntime.command(context, null, runtimeDir, null, guest))
|
||||
.directory(root)
|
||||
.redirectErrorStream(true)
|
||||
.also { builder ->
|
||||
val hostEnv = builder.environment()
|
||||
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
|
||||
hostEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(context).path
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun releases(tool: Tool): JSONArray? = releases(tool) { page ->
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** A launch the user asked for that waits for something else to finish first, and is forgotten if it waits too long. */
|
||||
class QueuedLaunch<T : Any>(private val lifetimeMs: Long = 15 * 60_000L) {
|
||||
var launch: T? = null
|
||||
private set
|
||||
var queuedAt: Long = 0L
|
||||
private set
|
||||
|
||||
fun queue(launch: T, now: Long) {
|
||||
this.launch = launch
|
||||
queuedAt = now
|
||||
}
|
||||
|
||||
/** Takes back a saved launch with the time it was first queued; one without a valid time or past its lifetime is dropped. */
|
||||
fun restore(launch: T?, queuedAt: Long, now: Long) {
|
||||
if (launch != null && fresh(queuedAt, now)) {
|
||||
this.launch = launch
|
||||
this.queuedAt = queuedAt
|
||||
} else {
|
||||
clear()
|
||||
}
|
||||
}
|
||||
|
||||
/** The launch if it is still wanted; an expired one is cleared. */
|
||||
fun current(now: Long): T? {
|
||||
val queued = launch ?: return null
|
||||
if (fresh(queuedAt, now)) return queued
|
||||
clear()
|
||||
return null
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
launch = null
|
||||
}
|
||||
|
||||
private fun fresh(queuedAt: Long, now: Long) = now - queuedAt in 0..lifetimeMs
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/**
|
||||
* Starts a queued launch once nothing stands in its way and retries until it can or it expires. One runner belongs to one
|
||||
* activity: destroying it clears its queue and cancels its retry, so a restored activity is the only one that starts the launch.
|
||||
*/
|
||||
class QueuedLaunchRunner<T : Any>(
|
||||
private val queue: QueuedLaunch<T>,
|
||||
private val now: () -> Long,
|
||||
private val blocked: () -> Boolean,
|
||||
private val busy: () -> Boolean,
|
||||
private val schedule: (delayMs: Long, task: Runnable) -> Unit,
|
||||
private val unschedule: (Runnable) -> Unit,
|
||||
private val start: (T) -> Unit,
|
||||
private val retryMs: Long = 2_000L,
|
||||
) {
|
||||
private var posted = false
|
||||
private var retry: Runnable? = null
|
||||
private var destroyed = false
|
||||
|
||||
/** Call whenever the blocking setting may have changed. */
|
||||
fun poke() {
|
||||
if (destroyed || posted) return
|
||||
val launch = queue.current(now()) ?: return
|
||||
if (blocked()) return
|
||||
posted = true
|
||||
schedule(0L, Runnable {
|
||||
posted = false
|
||||
attempt(launch)
|
||||
})
|
||||
}
|
||||
|
||||
private fun attempt(launch: T) {
|
||||
if (destroyed || queue.current(now()) !== launch) return
|
||||
if (busy()) {
|
||||
val again = Runnable { if (!destroyed && queue.launch === launch) poke() }
|
||||
retry = again
|
||||
schedule(retryMs, again)
|
||||
return
|
||||
}
|
||||
queue.clear()
|
||||
start(launch)
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
destroyed = true
|
||||
queue.clear()
|
||||
retry?.let(unschedule)
|
||||
retry = null
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import com.droiddeck.launcher.runtime.BwrapSpawner
|
||||
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 {
|
||||
@@ -20,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(
|
||||
@@ -120,7 +124,9 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-fex" to "usr/local/bin/droiddeck-fex",
|
||||
"libddsession.so" to "usr/local/lib/libddsession.so",
|
||||
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
|
||||
"libddfastpath.so" to "usr/local/lib/libddfastpath.so",
|
||||
"libddnatv-hook.so" to "usr/lib/libddnatv-hook.so",
|
||||
"libddaudit.so" to "usr/local/lib/libddaudit.so",
|
||||
"libssbs.so" to "usr/local/lib/libssbs.so",
|
||||
"usr/local/bin/droiddeck-session" to "usr/local/bin/droiddeck-session",
|
||||
"usr/local/bin/droiddeck-fonts" to "usr/local/bin/droiddeck-fonts",
|
||||
@@ -130,6 +136,8 @@ object SessionFiles {
|
||||
"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",
|
||||
@@ -332,26 +340,29 @@ 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")
|
||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||
preload.append("/usr/local/lib/libfakeinput.so\n")
|
||||
}
|
||||
com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
|
||||
val nativeUserland = SessionPrefs.nativeUserland(context)
|
||||
if (nativeUserland) com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
|
||||
if (ProotFastPath.enabled(context)) {
|
||||
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
|
||||
preload.append(library + "\n")
|
||||
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
|
||||
}
|
||||
val etc = File(root, "etc").apply { mkdirs() }
|
||||
File(etc, "droiddeck").mkdirs()
|
||||
FileUtils.writeString(File(etc, "droiddeck/native-preload"), preload.toString())
|
||||
File(etc, "ld.so.preload.staged").delete()
|
||||
File(etc, "ld.so.preload").takeIf { it.isFile }?.let { legacy ->
|
||||
val managed = setOf("/usr/local/lib/libddsession.so", "/usr/local/lib/libfakeinput.so")
|
||||
val remaining = legacy.readLines().filterNot { it.trim() in managed || it.trim().endsWith("/libddfastpath.so") }
|
||||
if (remaining.all { it.isBlank() }) legacy.delete()
|
||||
else FileUtils.writeString(legacy, remaining.joinToString("\n", postfix = "\n"))
|
||||
val staged = File(etc, "ld.so.preload.staged")
|
||||
if (!FileUtils.writeString(staged, preload.toString())
|
||||
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write ld.so.preload")
|
||||
}
|
||||
File(root, "usr/local/lib/libddfastpath.so").delete()
|
||||
File(root, "usr/local/lib/libddaudit.so").delete()
|
||||
|
||||
if (!FileUtils.writeString(File(etc, "steam-compatibility-label"), context.getString(R.string.steam_compat_label))) {
|
||||
Log.e(TAG, "could not write steam-compatibility-label")
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -118,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) {
|
||||
@@ -1129,6 +1162,21 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("mountSharedStorage", on).apply()
|
||||
}
|
||||
|
||||
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
|
||||
|
||||
fun setProotNoSeccomp(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -1136,12 +1184,22 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
|
||||
}
|
||||
|
||||
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
|
||||
|
||||
fun setProotFastPath(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("prootFastPath", on).apply()
|
||||
}
|
||||
|
||||
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
|
||||
|
||||
fun setCursorComposite(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("cursorComposite", on).apply()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun allowStockProot(context: Context): Boolean =
|
||||
context.getExternalFilesDir(null)?.let { File(it, "droiddeck-stock-proot").isFile } == true
|
||||
|
||||
const val DEFAULT_GUEST_HOSTNAME = "DroidDeck"
|
||||
|
||||
@JvmStatic
|
||||
@@ -1816,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
|
||||
|
||||
@@ -47,6 +47,7 @@ import com.droiddeck.launcher.input.SteamControllerBle
|
||||
import com.droiddeck.launcher.runtime.BwrapSpawner
|
||||
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import com.droiddeck.launcher.runtime.UserApps
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
@@ -522,6 +523,7 @@ class SessionService : Service() {
|
||||
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
|
||||
killStragglers()
|
||||
val stillStarting = { gen == sessionGen && SessionState.running }
|
||||
val prootPack = LinuxRuntime.patchedProot(this) || AddonPack.PROOT.await(this, stillStarting)
|
||||
val directAudioPack = AddonPack.DIRECTAUDIO.await(this, stillStarting)
|
||||
val systemVulkan = SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(this))
|
||||
val powerVrPack = !systemVulkan || (stillStarting() && AddonPack.POWERVR.await(this, stillStarting))
|
||||
@@ -542,6 +544,17 @@ class SessionService : Service() {
|
||||
Toast.makeText(this, R.string.session_directaudio_missing, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
if (!LinuxRuntime.patchedProot(this)) {
|
||||
if (LinuxRuntime.stockProotAllowed(this)) {
|
||||
Log.w(TAG, "proot: patched proot missing; droiddeck-stock-proot allows the rootfs copy")
|
||||
} else {
|
||||
val message = getString(R.string.session_proot_missing)
|
||||
Log.e(TAG, "$message (pack ready=$prootPack)")
|
||||
failSession(gen, "PROOT_MISSING", message, -1)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
}
|
||||
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
|
||||
.onFailure { Log.w(TAG, "agent environment skipped", it) }
|
||||
.getOrDefault(emptyList())
|
||||
@@ -590,6 +603,11 @@ class SessionService : Service() {
|
||||
return
|
||||
}
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
val prootLine = "== proot: ${LinuxRuntime.prootBinary(this).path} (${LinuxRuntime.prootSource(this)})"
|
||||
Log.i(TAG, prootLine)
|
||||
runCatching { sessionLog.appendText(prootLine + "\n") }
|
||||
.onFailure { Log.w(TAG, "could not write the proot line to ${sessionLog.path}", it) }
|
||||
|
||||
Log.i(TAG, SessionEvents.step("gpu-clock-pin") { GpuClockPin.start(this) })
|
||||
Log.i(TAG, SessionEvents.step("thread-hints") { GameThreadHints.start(this) })
|
||||
|
||||
@@ -614,6 +632,7 @@ class SessionService : Service() {
|
||||
return
|
||||
}
|
||||
if (steamHere) guest.add("DD_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
|
||||
val fastPathAt = guest.size
|
||||
|
||||
val pulse = SessionEvents.step("audio") { startAudio(guest, sessionDir, directAudioPack) }
|
||||
SessionEvents.step("vk-bridge") { startVkBridge(guest, sessionDir) }
|
||||
@@ -740,27 +759,63 @@ class SessionService : Service() {
|
||||
SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) }
|
||||
|
||||
val sharedStorage = LinuxRuntime.sharedStorage(this)
|
||||
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sharedStorage)
|
||||
if (!com.droiddeck.launcher.runtime.NativeGuest.available(root)) {
|
||||
val message = getString(R.string.session_native_missing)
|
||||
failSession(gen, "NATIVE_RUNTIME_MISSING", message, -1)
|
||||
stopSession(-1, gen)
|
||||
abandonStart(gen, sessionDir)
|
||||
return
|
||||
}
|
||||
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage)
|
||||
val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this)
|
||||
synchronized(stopLock) {
|
||||
if (gen == sessionGen && SessionState.running) com.droiddeck.launcher.runtime.NativeGuest.sessionPrepared = true
|
||||
if (gen == sessionGen && SessionState.running) com.droiddeck.launcher.runtime.NativeGuest.sessionMode = nativeUserland
|
||||
}
|
||||
val fastPathKey = if (ProotFastPath.enabled(this)) {
|
||||
val prootBinds = LinuxRuntime.binds(
|
||||
this, sessionRoot, runtimeDir, sharedStorage, binds,
|
||||
)
|
||||
val root = LinuxRuntime.rootDir(this)
|
||||
ProotFastPath.key(root, prootBinds)?.also { key ->
|
||||
val env = ProotFastPath.guestEnv(root, prootBinds, key)
|
||||
guest.addAll(fastPathAt, env)
|
||||
shellGuest.addAll(fastPathAt, env)
|
||||
Log.i(TAG, "proot: fast path on (${prootBinds.size} binds)")
|
||||
} ?: run {
|
||||
Log.w(TAG, "proot: fast path off - ${prootBinds.size} binds (it holds ${ProotFastPath.MAX_BINDS}) or a path it cannot be told")
|
||||
null
|
||||
}
|
||||
} else null
|
||||
|
||||
val sessionBindSpecs = LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds)
|
||||
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
|
||||
val command = if (nativeUserland) {
|
||||
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
|
||||
com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
|
||||
} else {
|
||||
LinuxRuntime.command(this, sessionRoot, runtimeDir, sharedStorage, binds, guest)
|
||||
}
|
||||
|
||||
val prootEnv = HostEnvironment()
|
||||
prootEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
|
||||
prootEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(this).path
|
||||
if (SessionPrefs.prootNoSeccomp(this)) {
|
||||
prootEnv["PROOT_NO_SECCOMP"] = "1"
|
||||
if (!nativeUserland) Log.i(TAG, "proot: seccomp acceleration off by request")
|
||||
}
|
||||
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> prootEnv[k] = v } }
|
||||
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
|
||||
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { prootEnv[key] = it }
|
||||
}
|
||||
val prootLibs = LinuxRuntime.prootLibraryPath(this)
|
||||
if (prootLibs.isNotEmpty()) prootEnv["LD_LIBRARY_PATH"] = prootLibs
|
||||
|
||||
val drives = com.droiddeck.launcher.runtime.NativeGuest.relinkPrefixDrives(root, sessionBindSpecs)
|
||||
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
|
||||
val command = com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
|
||||
val hostEnv = HostEnvironment().also { env ->
|
||||
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
|
||||
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this))
|
||||
.forEach { (k, v) -> env[k] = v }
|
||||
} else prootEnv
|
||||
|
||||
// The terminal and the bottom desktop run the way the session does: without proot when it does
|
||||
val terminalCommand = if (nativeUserland) {
|
||||
com.droiddeck.launcher.runtime.NativeGuest.command(root, shellGuest.first(), shellGuest.drop(1))
|
||||
} else {
|
||||
LinuxRuntime.command(this, sessionRoot, runtimeDir, sharedStorage, binds, shellGuest)
|
||||
}
|
||||
val terminalCommand = com.droiddeck.launcher.runtime.NativeGuest.command(root, shellGuest.first(), shellGuest.drop(1))
|
||||
val terminalHostEnvironment = LinkedHashMap(System.getenv())
|
||||
hostEnv.asArray().forEach { entry ->
|
||||
val separator = entry.indexOf('=')
|
||||
@@ -768,7 +823,9 @@ class SessionService : Service() {
|
||||
}
|
||||
if (gen == sessionGen && SessionState.running) {
|
||||
SessionTerminal.prepare(terminalCommand, terminalHostEnvironment.map { (key, value) -> "$key=$value" }.toTypedArray(), root, gen)
|
||||
BottomDesktop.prepare(desktopGuest, binds, sessionRoot, root, sessionDir, gen, sharedStorage,
|
||||
val (fastPathName, _) = ProotFastPath.hostEnv("")
|
||||
BottomDesktop.prepare(desktopGuest, binds, sessionRoot,
|
||||
prootEnv.asArray().filterNot { it.startsWith("$fastPathName=") }.toTypedArray(), root, sessionDir, gen, nativeUserland, sharedStorage,
|
||||
) { gen == sessionGen && SessionState.running }
|
||||
}
|
||||
|
||||
@@ -829,7 +886,7 @@ class SessionService : Service() {
|
||||
val program = programStatus(sessionRoot)
|
||||
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
|
||||
stopSession(program ?: status ?: -1, gen)
|
||||
}, null, null) }
|
||||
}, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() }) }
|
||||
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
|
||||
if (gen != sessionGen || !SessionState.running) {
|
||||
Log.i(TAG, "session stopped while its guest was starting; taking it down")
|
||||
@@ -849,12 +906,12 @@ class SessionService : Service() {
|
||||
// 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)
|
||||
SessionEvents.record("guest.worker", mapOf("handoff" to uncounted))
|
||||
synchronized(stopLock) {
|
||||
if (gen == sessionGen && SessionState.running)
|
||||
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = uncounted
|
||||
}
|
||||
if (pid > 1) {
|
||||
raiseTracer(pid, gen)
|
||||
SessionEvents.guestStarted(pid)
|
||||
} else {
|
||||
SessionEvents.record("guest.start_failed", mapOf("pid" to pid))
|
||||
@@ -1223,6 +1280,8 @@ class SessionService : Service() {
|
||||
fakeInputDir: File,
|
||||
sessionDir: File,
|
||||
guest: MutableList<String>,
|
||||
sessionRoot: File,
|
||||
runtimeDir: File,
|
||||
sharedStorage: File?,
|
||||
): ArrayList<String> {
|
||||
val binds = ArrayList<String>()
|
||||
@@ -1350,6 +1409,9 @@ class SessionService : Service() {
|
||||
if (storageDiagnosticLibrary != null && library != null) libraries.add(SecondaryLibrary.CARD_GUESTS[0] to library.label)
|
||||
val gamesLibraries = GameStorage.gamesFolderLibraries(this)
|
||||
if (gamesLibraries.isNotEmpty()) {
|
||||
var room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||
} else Int.MAX_VALUE
|
||||
for (games in gamesLibraries) {
|
||||
if (games.host.path + ":" + games.guest !in binds) continue
|
||||
val problem = GameStorage.prepare(this, games.host.path)
|
||||
@@ -1359,7 +1421,12 @@ class SessionService : Service() {
|
||||
}
|
||||
try {
|
||||
val extra = SecondaryLibrary.binds(filesDir, games.host, listOf(games.guest)).drop(1)
|
||||
if (extra.size > room) {
|
||||
Log.w(TAG, "steam library: ${games.host} needs ${extra.size} binds, $room left for the fast path; not a library this session")
|
||||
continue
|
||||
}
|
||||
binds.addAll(extra)
|
||||
room -= extra.size
|
||||
libraries.add(games.guest to games.label)
|
||||
Log.i(TAG, "steam library: ${games.host} -> ${games.guest} (\"${games.label}\")")
|
||||
} catch (e: Exception) {
|
||||
@@ -1384,8 +1451,15 @@ class SessionService : Service() {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
val room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||
} else Int.MAX_VALUE
|
||||
val content = SecondaryLibrary.contentPath(entry.host)
|
||||
val extra = SecondaryLibrary.binds(filesDir, entry.host, listOf(entry.guest), content = content)
|
||||
if (extra.size > room) {
|
||||
Log.w(TAG, "added steam library: ${entry.path} needs ${extra.size} binds, $room left for the fast path; not a library this session")
|
||||
continue
|
||||
}
|
||||
File(LinuxRuntime.rootDir(this), entry.guest.removePrefix("/")).mkdirs()
|
||||
binds.addAll(extra)
|
||||
libraries.add(entry.guest to entry.label)
|
||||
@@ -1406,10 +1480,17 @@ class SessionService : Service() {
|
||||
if (problem != null) {
|
||||
Log.w(TAG, "x86-64 steam library: $problem")
|
||||
} else try {
|
||||
val room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||
} else Int.MAX_VALUE
|
||||
val extra = SecondaryLibrary.binds(filesDir, x64, listOf(GameStorage.X64_CARD_GUEST)).drop(1)
|
||||
binds.addAll(extra)
|
||||
x64Libraries.put(org.json.JSONObject().put("path", GameStorage.X64_CARD_GUEST).put("label", library.label.replace('"', ' ').replace('\\', ' ')))
|
||||
Log.i(TAG, "x86-64 steam library: $x64 -> ${GameStorage.X64_CARD_GUEST} (\"${library.label}\")")
|
||||
if (extra.size > room) {
|
||||
Log.w(TAG, "x86-64 steam library: $x64 needs ${extra.size} binds, $room left for the fast path; not a library this session")
|
||||
} else {
|
||||
binds.addAll(extra)
|
||||
x64Libraries.put(org.json.JSONObject().put("path", GameStorage.X64_CARD_GUEST).put("label", library.label.replace('"', ' ').replace('\\', ' ')))
|
||||
Log.i(TAG, "x86-64 steam library: $x64 -> ${GameStorage.X64_CARD_GUEST} (\"${library.label}\")")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "x86-64 steam library: $x64 private directories could not be prepared", e)
|
||||
}
|
||||
@@ -1421,7 +1502,14 @@ class SessionService : Service() {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
val room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||
} else Int.MAX_VALUE
|
||||
val extra = SecondaryLibrary.binds(filesDir, entry.x64Host, listOf(entry.x64Guest)).drop(1)
|
||||
if (extra.size > room) {
|
||||
Log.w(TAG, "x86-64 steam library: ${entry.x64Host} needs ${extra.size} binds, $room left for the fast path; not a library this session")
|
||||
continue
|
||||
}
|
||||
binds.addAll(extra)
|
||||
x64Libraries.put(org.json.JSONObject().put("path", entry.x64Guest).put("label", entry.label))
|
||||
} catch (e: Exception) {
|
||||
@@ -1450,11 +1538,15 @@ class SessionService : Service() {
|
||||
try {
|
||||
val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() }
|
||||
val volumes = org.json.JSONArray()
|
||||
var room = if (ProotFastPath.enabled(this)) {
|
||||
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
|
||||
} else Int.MAX_VALUE
|
||||
for (root in com.droiddeck.launcher.files.StorageRoots.list(this)) {
|
||||
if (!root.removable || !root.readable) continue
|
||||
val path = root.dir.absolutePath
|
||||
if (':' in path || '|' in path) continue
|
||||
if (':' in path || '|' in path || room <= 0) continue
|
||||
binds.add(path)
|
||||
room--
|
||||
volumes.put(org.json.JSONObject().put("path", path).put("label", root.label))
|
||||
}
|
||||
listing.writeText(volumes.toString())
|
||||
@@ -1470,19 +1562,19 @@ class SessionService : Service() {
|
||||
// The workers' session number of the session running now (GuestWorkers.serve)
|
||||
@Volatile private var guestWorkerSession = 0
|
||||
|
||||
private fun teardown(guestPid: Int, expectedStartTime: Long? = null, workerSession: Int = guestWorkerSession) {
|
||||
fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(guestPid)?.second == expectedStartTime
|
||||
private fun teardown(prootPid: Int, expectedStartTime: Long? = null, workerSession: Int = guestWorkerSession) {
|
||||
fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime
|
||||
if (!stillSameProcess()) return
|
||||
// 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(guestPid) + workers.flatMap { pid -> listOfNotNull(readStat(pid)?.let { Pair(pid, it.second) }) + descendants(pid) }
|
||||
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(guestPid, 15)
|
||||
if (!waitForExit(guestPid, GRACE_MS)) {
|
||||
android.os.Process.sendSignal(prootPid, 15)
|
||||
if (!waitForExit(prootPid, GRACE_MS)) {
|
||||
if (!stillSameProcess()) return
|
||||
Log.w(TAG, "guest $guestPid did not exit on SIGTERM; killing it")
|
||||
android.os.Process.killProcess(guestPid)
|
||||
Log.w(TAG, "proot $prootPid did not exit on SIGTERM; killing it")
|
||||
android.os.Process.killProcess(prootPid)
|
||||
}
|
||||
var killed = 0
|
||||
for ((pid, started) in tree) {
|
||||
@@ -1491,7 +1583,7 @@ class SessionService : Service() {
|
||||
android.os.Process.killProcess(pid)
|
||||
killed++
|
||||
}
|
||||
if (killed > 0) Log.i(TAG, "swept $killed guest process(es)")
|
||||
if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind")
|
||||
if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workerSession)
|
||||
}
|
||||
|
||||
@@ -1552,8 +1644,8 @@ class SessionService : Service() {
|
||||
return try { Pair(fields[1].toInt(), fields[19].toLong()) } catch (e: NumberFormatException) { null }
|
||||
}
|
||||
|
||||
private fun askSteamToExit(guestPid: Int) {
|
||||
if (!File("/proc/$guestPid").exists()) return
|
||||
private fun askSteamToExit(prootPid: Int) {
|
||||
if (!File("/proc/$prootPid").exists()) return
|
||||
val request = File(LinuxRuntime.sessionRoot(this), "steam-stop")
|
||||
try {
|
||||
request.writeText("")
|
||||
@@ -1562,11 +1654,11 @@ class SessionService : Service() {
|
||||
return
|
||||
}
|
||||
val started = System.currentTimeMillis()
|
||||
if (waitForExit(guestPid, STEAM_PICKUP_MS) || request.exists()) {
|
||||
if (waitForExit(prootPid, STEAM_PICKUP_MS) || request.exists()) {
|
||||
request.delete()
|
||||
return
|
||||
}
|
||||
val exited = waitForExit(guestPid, STEAM_EXIT_MS)
|
||||
val exited = waitForExit(prootPid, STEAM_EXIT_MS)
|
||||
Log.i(TAG, "Steam client ${if (exited) "exited" else "did not exit"} after ${System.currentTimeMillis() - started} ms")
|
||||
}
|
||||
|
||||
@@ -1845,7 +1937,7 @@ class SessionService : Service() {
|
||||
val rootfs = try { File(filesDir, "linuxfs").canonicalPath } catch (e: Exception) { return } + "/"
|
||||
val leftovers = GuestLeftovers.find(rootfs, ended, OrphanReaper.spared() + android.os.Process.myPid())
|
||||
leftovers.forEach { android.os.Process.killProcess(it) }
|
||||
if (leftovers.isNotEmpty()) Log.w(TAG, "killed ${leftovers.size} guest process(es)")
|
||||
if (leftovers.isNotEmpty()) Log.w(TAG, "killed ${leftovers.size} guest process(es) proot no longer tracked")
|
||||
}
|
||||
|
||||
private fun killStragglers() {
|
||||
@@ -2234,6 +2326,24 @@ class SessionService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun raiseTracer(pid: Int, gen: Int) {
|
||||
Thread({
|
||||
try {
|
||||
Thread.sleep(2000)
|
||||
} catch (e: InterruptedException) {
|
||||
return@Thread
|
||||
}
|
||||
if (gen != sessionGen || sessionPid != pid) return@Thread
|
||||
val nice = try {
|
||||
WaylandCompositor.nativeRaisePriority(pid, TRACER_NICE)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "tracer priority", t)
|
||||
return@Thread
|
||||
}
|
||||
Log.i(TAG, "proot tracer $pid: nice $nice (asked for $TRACER_NICE)")
|
||||
}, "tracer-priority").start()
|
||||
}
|
||||
|
||||
private fun failSession(gen: Int, code: String, message: String, status: Int?) {
|
||||
synchronized(stopLock) {
|
||||
if (gen == sessionGen) SessionEvents.fail(code, message, status)
|
||||
@@ -2254,7 +2364,7 @@ class SessionService : Service() {
|
||||
cancelQueuedSteamGame()
|
||||
gameExitWatchToken++
|
||||
// also when startup stopped before the guest ran
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionPrepared = false
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionMode = null
|
||||
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = null
|
||||
if (!SessionState.running) return
|
||||
if (relaunch) SessionState.confirmRelaunchStop()
|
||||
@@ -2283,7 +2393,7 @@ class SessionService : Service() {
|
||||
launchWatcher = null
|
||||
syncWatcher?.stopWatching()
|
||||
syncWatcher = null
|
||||
val guestPid = sessionPid
|
||||
val prootPid = sessionPid
|
||||
sessionPid = -1
|
||||
// The kept shell goes through the same teardown, which reads its descendants before signalling it.
|
||||
val shell = SessionTerminal.detach(sessionGen)?.let { pid -> readStat(pid)?.second?.let { pid to it } }
|
||||
@@ -2311,12 +2421,12 @@ class SessionService : Service() {
|
||||
com.droiddeck.launcher.input.SteamTouchDevice.release()
|
||||
val steamClientMayRun = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
val finishAfterTeardown: () -> Unit = {
|
||||
if (guestPid > 1 || auxiliary.isNotEmpty()) {
|
||||
if (prootPid > 1 || auxiliary.isNotEmpty()) {
|
||||
Thread({
|
||||
if (guestPid > 1 && steamClientMayRun) askSteamToExit(guestPid)
|
||||
if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid)
|
||||
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (guestPid > 1) teardown(guestPid, workerSession = workers)
|
||||
if (prootPid > 1) teardown(prootPid, workerSession = workers)
|
||||
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
|
||||
killGuestLeftovers(ended)
|
||||
pruneSystemVulkanRuntime()
|
||||
@@ -2333,7 +2443,7 @@ class SessionService : Service() {
|
||||
}, "gog-session-stop").start()
|
||||
}
|
||||
}
|
||||
if (guestPid > 1) acquireLocks()
|
||||
if (prootPid > 1) acquireLocks()
|
||||
if (controller != null) controller.closeAndResume(finishAfterTeardown) else finishAfterTeardown()
|
||||
}
|
||||
|
||||
@@ -2577,6 +2687,7 @@ class SessionService : Service() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val TRACER_NICE = -6
|
||||
private const val MIC_RELEASE_TIMEOUT_MS = 5_000L
|
||||
private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug"
|
||||
private const val GAME_PREFIX = "DROIDDECK_GAME_"
|
||||
@@ -2616,7 +2727,7 @@ class SessionService : Service() {
|
||||
private const val ACTION_AUXILIARY_EXITED = "com.droiddeck.launcher.AUXILIARY_EXITED"
|
||||
private const val EXTRA_AUXILIARY_PID = "auxiliaryPid"
|
||||
private val STRAGGLERS = listOf("droiddeck-session", "gamescope", "Xwayland", "steamrtarm64",
|
||||
"steamwebhelper", "pulseaudio/libpulseaudio.so")
|
||||
"steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so")
|
||||
private const val GRACE_MS = 1200L
|
||||
private const val WINE_SAVE_MS = 3000L
|
||||
private const val STEAM_PICKUP_MS = 1500L
|
||||
|
||||
@@ -12,7 +12,7 @@ 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",
|
||||
@@ -22,7 +22,7 @@ object SettingsReset {
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "cursorComposite", "mountSharedStorage",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite", "mountSharedStorage",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "blackFrameInsertion", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "steam_offline_auto", "steam_offline_by_network", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
|
||||
|
||||
@@ -12,6 +12,8 @@ import org.json.JSONObject
|
||||
/** Steam libraries the user added beside the internal one and the card library, each a folder of its own. */
|
||||
object SteamLibraries {
|
||||
const val GUEST_ROOT = "/mnt/droiddeck-lib"
|
||||
// Each library costs a bind per redirected tool and prefix folder; the PRoot fast path holds 256 in all.
|
||||
const val MAX = 4
|
||||
private val lock = Any()
|
||||
|
||||
class Entry(val id: String, val path: String, val label: String) {
|
||||
@@ -50,6 +52,7 @@ object SteamLibraries {
|
||||
|
||||
fun add(context: Context, picked: String, label: String? = null): AddResult {
|
||||
val entries = list(context)
|
||||
if (entries.size >= MAX) return AddResult.Refused(context.getString(R.string.libraries_full, MAX))
|
||||
val path = innerLibrary(File(picked))?.path ?: picked
|
||||
val host = canonical(File(path))
|
||||
if (taken(context, entries).any { overlaps(it, host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
|
||||
@@ -58,6 +61,7 @@ object SteamLibraries {
|
||||
GameStorage.prepare(context, path)?.let { return AddResult.Refused(it) }
|
||||
synchronized(lock) {
|
||||
val current = list(context)
|
||||
if (current.size >= MAX) return AddResult.Refused(context.getString(R.string.libraries_full, MAX))
|
||||
if (current.any { overlaps(canonical(it.host), host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
|
||||
// A removed library's mount stays registered with Steam until its next session, so ids are never reused.
|
||||
val next = maxOf(SessionPrefs.steamLibraryNextId(context), (current.maxOfOrNull { it.id.toInt() } ?: 0) + 1)
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -64,8 +64,8 @@ internal class StoreArchiveUnpacker(
|
||||
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
|
||||
else listOf(work.absolutePath)
|
||||
fun bsdtar(args: List<String>, onLine: (String) -> Unit) =
|
||||
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = logName, extraBinds = binds, cancelled = cancelled) { line ->
|
||||
onLine(line)
|
||||
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = logName, extraBinds = binds, fastPath = true, cancelled = cancelled) { line ->
|
||||
if (!line.startsWith("proot ")) onLine(line)
|
||||
}
|
||||
var entries = 0L
|
||||
var size = 0L
|
||||
|
||||
@@ -82,7 +82,7 @@ object BattleNetInstall {
|
||||
internal fun run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int =
|
||||
GuestCommand.run(
|
||||
context, listOf(BattleNet.PROGRAM) + args, logName = "battlenet-agent",
|
||||
extraBinds = binds(context), cancelled = cancelled, onLine = onLine,
|
||||
extraBinds = binds(context), fastPath = true, cancelled = cancelled, onLine = onLine,
|
||||
)
|
||||
|
||||
fun enqueue(context: Context, item: CatalogItem, folder: File, update: Boolean = false) {
|
||||
|
||||
@@ -249,7 +249,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
desktopParts.forEach { argv += listOf("--desktop", guest(it.file)) }
|
||||
if (runtimePart != null && glesPart != null) argv += listOf("--runtime", guest(runtimePart.file), "--gles", guest(glesPart.file))
|
||||
var answer: JSONObject? = null
|
||||
val code = GuestCommand.run(app, argv, logName = "epic-client") { line ->
|
||||
val code = GuestCommand.run(app, argv, fakeRoot = true, logName = "epic-client") { line ->
|
||||
if (line.startsWith("{")) runCatching { JSONObject(line) }.getOrNull()?.let { answer = it }
|
||||
}
|
||||
val result = answer
|
||||
|
||||
@@ -8,6 +8,7 @@ import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.AchievementNotifications
|
||||
@@ -138,10 +139,22 @@ object GogComet {
|
||||
val data = File(context.filesDir, "gog-achievements").apply { mkdirs() }
|
||||
val ready = CountDownLatch(1)
|
||||
val guest = listOf("/usr/bin/env", "HOME=/root", "XDG_DATA_HOME=${data.path}/data", "XDG_CONFIG_HOME=${data.path}/config", "COMET_LOG=off", "COMET_ALLOWED_CLIENTS=${policy.path}", BIN, "--credentials-stdin")
|
||||
try {
|
||||
val pb = if (com.droiddeck.launcher.runtime.NativeGuest.forSession(context)) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val pb = com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
|
||||
com.droiddeck.launcher.runtime.NativeGuest.processBuilder(context, root,
|
||||
LinuxRuntime.binds(context, null, null, LinuxRuntime.sharedStorage(context), null), guest).redirectErrorStream(true)
|
||||
} else {
|
||||
ProcessBuilder(LinuxRuntime.command(context, null, null, LinuxRuntime.sharedStorage(context), guest)).redirectErrorStream(true).also {
|
||||
it.environment().apply {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
val child = pb.start()
|
||||
process = child; account = user; session = SessionState.sessionId
|
||||
Thread({
|
||||
|
||||
@@ -101,9 +101,11 @@ internal object ItchPatch {
|
||||
.distinct().takeIf { it.isNotEmpty() }
|
||||
val tail = ArrayDeque<String>()
|
||||
val code = try {
|
||||
GuestCommand.run(app, args, logName = "itch-butler", extraBinds = binds, cancelled = cancelled) { line ->
|
||||
if (tail.size == 4) tail.removeFirst()
|
||||
tail.addLast(line)
|
||||
GuestCommand.run(app, args, logName = "itch-butler", extraBinds = binds, fastPath = true, cancelled = cancelled) { line ->
|
||||
if (!line.startsWith("proot ")) {
|
||||
if (tail.size == 4) tail.removeFirst()
|
||||
tail.addLast(line)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
StoreInstalls.deleteTree(staging)
|
||||
|
||||
@@ -61,7 +61,18 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
|
||||
}
|
||||
|
||||
private fun identity(pid: Int, root: Int): String? {
|
||||
if (root <= 0 || pid <= 0 || !descendsFrom(pid, root)) return null
|
||||
if (root <= 0 || pid <= 0) return null
|
||||
val status = java.io.File("/proc/$pid/status").readLines()
|
||||
val tracer = status.first { it.startsWith("TracerPid:") }.substringAfter(':').trim().toInt()
|
||||
if (tracer != 0) {
|
||||
// under proot, every guest process is traced by the proot the app started
|
||||
val tracerGroup = java.io.File("/proc/$tracer/status").readLines()
|
||||
.first { it.startsWith("Tgid:") }.substringAfter(':').trim().toInt()
|
||||
if (tracerGroup != root) return null
|
||||
} else if (!descendsFrom(pid, root)) {
|
||||
// without proot, the process the app started is the backend itself (or its parent)
|
||||
return null
|
||||
}
|
||||
val executable = android.system.Os.stat(binary.path)
|
||||
if (!mapsBackend(java.io.File("/proc/$pid/maps").readText(), binary.path, executable.st_ino))
|
||||
return null
|
||||
|
||||
@@ -4,6 +4,8 @@ import android.content.Context
|
||||
import com.droiddeck.launcher.core.AddonPack
|
||||
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.ProotFastPath
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import org.json.JSONObject
|
||||
import java.io.Closeable
|
||||
@@ -82,15 +84,33 @@ internal object Xodus {
|
||||
val external = LinuxRuntime.sharedStorage(app)
|
||||
val extraBinds = StoreInstallRoot.externalBindSpecsForXodus(app)
|
||||
val binds = LinuxRuntime.binds(app, null, null, external, extraBinds)
|
||||
val fastPathPreloaded = runCatching {
|
||||
File(root, "etc/ld.so.preload").useLines { lines -> lines.any { it.trim() == ProotFastPath.LIBRARY } }
|
||||
}.getOrDefault(false)
|
||||
val native = com.droiddeck.launcher.runtime.NativeGuest.forSession(app)
|
||||
val fastPathKey = if (!native && ProotFastPath.enabled(app) && fastPathPreloaded &&
|
||||
File(root, ProotFastPath.LIBRARY.removePrefix("/")).isFile) ProotFastPath.key(root, binds) else null
|
||||
val guestCommand = mutableListOf(
|
||||
"/usr/bin/env", "HOME=/root", "XODUS_LOG=off", "RUST_LOG=off",
|
||||
"XDG_RUNTIME_DIR=${runtime.path}", "DROIDDECK_XBOX_CREDENTIAL_SOCKET=${credentials.name}", binary,
|
||||
)
|
||||
fastPathKey?.let { key ->
|
||||
guestCommand.addAll(guestCommand.lastIndex, ProotFastPath.guestEnv(root, binds, key))
|
||||
}
|
||||
guestCommand.addAll(args)
|
||||
val builder = com.droiddeck.launcher.runtime.NativeGuest.processBuilder(app, root, binds, guestCommand)
|
||||
val builder = if (native) com.droiddeck.launcher.runtime.NativeGuest.processBuilder(app, root, binds, guestCommand)
|
||||
else ProcessBuilder(LinuxRuntime.commandWithBinds(app, root, binds, guestCommand)).directory(LinuxRuntime.rootDir(app))
|
||||
if (launchDirectory != null) builder.environment()["TMPDIR"] = launchDirectory.path
|
||||
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_PORT"] = credentials.port.toString()
|
||||
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_KEY"] = credentials.key
|
||||
if (!native) builder.environment().apply {
|
||||
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
|
||||
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
|
||||
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (key, value) -> put(key, value) } }
|
||||
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
|
||||
}
|
||||
val digest = java.security.MessageDigest.getInstance("SHA-256")
|
||||
File(pack, binary.removePrefix("$DIR/")).inputStream().use { input ->
|
||||
val buffer = ByteArray(65536)
|
||||
|
||||
@@ -223,7 +223,7 @@ internal fun AgentProcessList(modifier: Modifier) {
|
||||
var procs by remember { mutableStateOf<List<AgentProcesses.Proc>?>(null) }
|
||||
LaunchedEffect(refresh) {
|
||||
while (true) {
|
||||
procs = withContext(Dispatchers.IO) { AgentProcesses.snapshot(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), AgentHost.turnPid) }
|
||||
procs = withContext(Dispatchers.IO) { AgentProcesses.snapshot(AgentHost.turnPid) }
|
||||
delay(2_000)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -283,6 +283,7 @@ private fun action(step: Step): Int = when (step) {
|
||||
Step.PREPARE -> R.string.agent_action_prepare
|
||||
}
|
||||
|
||||
/** 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)) {
|
||||
@@ -292,5 +293,5 @@ private fun pair(context: android.content.Context) {
|
||||
return
|
||||
}
|
||||
WirelessAdbPairingService.start(context)
|
||||
PairingGuideActivity.start(context, null)
|
||||
PairingGuideActivity.start(context, null, false)
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
@Composable
|
||||
fun DeveloperDisplayChoiceDialog(
|
||||
displays: List<Pair<Int, String>>,
|
||||
onMainScreen: () -> Unit,
|
||||
onSecondaryScreen: (Int) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.setup_adb_pair_button)) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Text(stringResource(R.string.gate_choose_display))
|
||||
TextButton(modifier = Modifier.fillMaxWidth().focusGlide(CircleShape), onClick = onMainScreen) { Text(stringResource(R.string.gate_main_screen)) }
|
||||
displays.forEach { (id, label) ->
|
||||
TextButton(modifier = Modifier.fillMaxWidth().focusGlide(CircleShape), onClick = { onSecondaryScreen(id) }) { Text(label) }
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -41,8 +41,73 @@ internal fun FrameGenMenu(
|
||||
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)) }
|
||||
}
|
||||
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)) }
|
||||
}
|
||||
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)) {
|
||||
if (!legacyButtons) OutlinedButton(
|
||||
OutlinedButton(
|
||||
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
|
||||
modifier = Modifier.fillMaxWidth().controllerConfirm(
|
||||
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
|
||||
@@ -54,7 +119,7 @@ internal fun FrameGenMenu(
|
||||
),
|
||||
) { Text(offLabel) }
|
||||
|
||||
Row(Modifier.fillMaxWidth().then(if (legacyButtons) Modifier else Modifier.padding(top = 8.dp)), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -107,7 +107,7 @@ import java.io.File
|
||||
internal fun Pane(
|
||||
s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
onPairWirelessDebugging: () -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit,
|
||||
) {
|
||||
BoxWithConstraints(modifier = modifier) {
|
||||
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) {
|
||||
@@ -174,7 +174,7 @@ internal fun Pane(
|
||||
label = "pane",
|
||||
) { key ->
|
||||
val drawn = (if (page != null && key == s.pageKey) page else pages[key])
|
||||
?: { Content(s, if (key == "games") gameShown[0] else if (key == "soundtracks") soundShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onPairWirelessDebugging) }
|
||||
?: { Content(s, if (key == "games") gameShown[0] else if (key == "soundtracks") soundShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) }
|
||||
val hopSink by androidx.compose.animation.core.animateFloatAsState(
|
||||
if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink",
|
||||
)
|
||||
@@ -237,7 +237,7 @@ private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, L
|
||||
private fun Content(
|
||||
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
onPairWirelessDebugging: () -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
|
||||
@@ -247,7 +247,7 @@ private fun Content(
|
||||
val padV = if (narrow) 12.dp else 18.dp
|
||||
if (selected == "setup") {
|
||||
Column(modifier = modifier.padding(horizontal = padH).padding(top = padV)) {
|
||||
SetupPanel(s, a, onPairWirelessDebugging)
|
||||
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -94,6 +94,7 @@ import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onPlaced
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
|
||||
internal val AttentionAmber: Color @Composable get() = LocalPalette.current.warning
|
||||
|
||||
@@ -211,7 +212,8 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
|
||||
else -> R.string.rail_updates to updatesIcon(RunningBuild.kind())
|
||||
}
|
||||
|
||||
internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed)
|
||||
internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) ||
|
||||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
|
||||
internal fun railBadge(s: FrontEndState, key: String, setupNeedsAttention: Boolean = setupNeedsAttention(s)): Boolean = when (key) {
|
||||
"setup" -> setupNeedsAttention
|
||||
|
||||
@@ -86,6 +86,8 @@ import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.Lossless
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.core.DownloadSource
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import kotlin.math.roundToInt
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
@@ -163,16 +165,24 @@ class FrontEndState(
|
||||
val buildLabel: String = "local",
|
||||
val oscMode: String = SessionPrefs.OSC_AUTO,
|
||||
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
||||
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
|
||||
val adreno: Boolean = true,
|
||||
val vkBridge: Boolean = false,
|
||||
val venus: Boolean = false,
|
||||
val venusHostVulkan: String? = null,
|
||||
val vkBridgeSafe: Boolean = true,
|
||||
val bridgeProtonDxvk: Boolean = false,
|
||||
val showPhantomGate: Boolean = false,
|
||||
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
|
||||
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 = "",
|
||||
@@ -280,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 = {},
|
||||
@@ -311,9 +326,15 @@ class FrontEndActions(
|
||||
val onIntegrationLocation: () -> Unit = {},
|
||||
val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> },
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onRefreshPhantomStatus: () -> Unit = {},
|
||||
val onOpenDeveloperOptions: (Int?) -> Unit = {},
|
||||
val onStartWirelessAdbPairing: () -> Unit = {},
|
||||
val onStartPairingGuide: (Int?) -> Boolean = { false },
|
||||
val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit,
|
||||
val onCopyPhantomCommand: (Boolean) -> Unit = {},
|
||||
val onDismissPhantomGate: () -> Unit = {},
|
||||
val onStartWirelessAdbPairing: (Boolean) -> Unit = {},
|
||||
val onStartPairingGuide: (Int?, Boolean) -> Boolean = { _, _ -> false },
|
||||
val onShowPhantomGate: () -> Unit = {},
|
||||
val onQueuePlaySteam: () -> Unit = {},
|
||||
val onEnsureNotifications: ((Boolean) -> Unit) -> Unit = { it(true) },
|
||||
val controller: ControllerActions? = null,
|
||||
val updates: UpdatesActions = UpdatesActions(),
|
||||
@@ -436,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 { }
|
||||
@@ -501,39 +531,92 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
if (com.droiddeck.launcher.stores.StoresState.openGameRequest != null) selected = "stores"
|
||||
}
|
||||
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
|
||||
var developerChoiceGuided by rememberSaveable { mutableStateOf(false) }
|
||||
var developerChoiceToggle by rememberSaveable { mutableStateOf(false) }
|
||||
var guidedLimitEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val openPairingOn: (Int?) -> Unit = { displayId ->
|
||||
a.onStartWirelessAdbPairing()
|
||||
if (!a.onStartPairingGuide(displayId)) a.onOpenDeveloperOptions(displayId)
|
||||
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
val processSettingsPageVisible = phantomGateVisible || showDeveloperDisplayChoice
|
||||
val requestDeveloperOptions = {
|
||||
developerChoiceGuided = false
|
||||
developerChoiceToggle = false
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
val startGuidedPairing: () -> Unit = {
|
||||
val openDeveloperOptionsOn: (Int?) -> Unit = { displayId ->
|
||||
if (developerChoiceGuided) a.onStartWirelessAdbPairing(guidedLimitEnabled)
|
||||
val guided = developerChoiceGuided || developerChoiceToggle
|
||||
if (!guided || !a.onStartPairingGuide(displayId, developerChoiceToggle)) a.onOpenDeveloperOptions(displayId)
|
||||
developerChoiceGuided = false
|
||||
developerChoiceToggle = false
|
||||
}
|
||||
val requestChildProcessToggle = {
|
||||
if (!PhantomProcessLimit.hasDeveloperToggle() || com.droiddeck.launcher.core.GlobalSettings.developerOptionsOn(ctx)) {
|
||||
requestDeveloperOptions()
|
||||
} else {
|
||||
developerChoiceGuided = false
|
||||
developerChoiceToggle = true
|
||||
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
}
|
||||
val startGuidedPairing: (Boolean) -> Unit = { enabled ->
|
||||
a.onEnsureNotifications { granted ->
|
||||
if (granted) {
|
||||
if (s.secondScreenDisplays.isEmpty()) openPairingOn(null)
|
||||
guidedLimitEnabled = enabled
|
||||
developerChoiceGuided = true
|
||||
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
}
|
||||
}
|
||||
val childProcessRequest = androidx.compose.runtime.rememberUpdatedState {
|
||||
if (PhantomProcessLimit.hasDeveloperToggle()) requestChildProcessToggle() else a.onShowPhantomGate()
|
||||
}
|
||||
DisposableEffect(Unit) {
|
||||
val handler: () -> Unit = { childProcessRequest.value() }
|
||||
ChildProcessSetup.request = handler
|
||||
onDispose { if (ChildProcessSetup.request === handler) ChildProcessSetup.request = null }
|
||||
}
|
||||
var applyingSavedPairing by remember { mutableStateOf(false) }
|
||||
val fixPhantomLimit = {
|
||||
if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing(false)
|
||||
else if (!applyingSavedPairing) {
|
||||
applyingSavedPairing = true
|
||||
a.onSetPhantomProcessLimit(false) { error ->
|
||||
applyingSavedPairing = false
|
||||
if (error != null) startGuidedPairing(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) {
|
||||
if (phantomGateVisible) {
|
||||
while (true) {
|
||||
kotlinx.coroutines.delay(2_000)
|
||||
a.onRefreshPhantomStatus()
|
||||
}
|
||||
}
|
||||
}
|
||||
val pageBack = { if (!Hops.back(a.onPageBack)) a.onPageBack() }
|
||||
BackHandler(enabled = !showDeveloperDisplayChoice && s.pageKey != null && page != null) { pageBack() }
|
||||
BackHandler(enabled = !processSettingsPageVisible && s.pageKey != null && page != null) { pageBack() }
|
||||
LaunchedEffect(s.pageKey, selected) { Hops.forget(s.pageKey ?: selected) }
|
||||
BackHandler(enabled = !showDeveloperDisplayChoice && s.pageKey == null && Hops.origin?.page == selected) {
|
||||
BackHandler(enabled = !processSettingsPageVisible && s.pageKey == null && Hops.origin?.page == selected) {
|
||||
val rail = Hops.origin?.rail ?: return@BackHandler
|
||||
Hops.back { selected = rail }
|
||||
}
|
||||
val density = androidx.compose.ui.platform.LocalDensity.current.density
|
||||
remember(density) { Hops.density = density; true }
|
||||
BackHandler(
|
||||
enabled = !showDeveloperDisplayChoice && (s.pageKey == null || page == null) &&
|
||||
enabled = !processSettingsPageVisible && (s.pageKey == null || page == null) &&
|
||||
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store"),
|
||||
) {
|
||||
selected = if (selected.startsWith("rom:")) "emu:" + selected.removePrefix("rom:").substringBefore(':') else "desktop"
|
||||
}
|
||||
val backToMore = s.pageKey == null && Hops.origin == null && selected in NavTabs.more(s)
|
||||
BackHandler(enabled = !showDeveloperDisplayChoice && backToMore) {
|
||||
BackHandler(enabled = !processSettingsPageVisible && backToMore) {
|
||||
selected = NavTabs.MORE
|
||||
}
|
||||
LaunchedEffect(s.soundtracksEnabled) {
|
||||
@@ -630,13 +713,13 @@ 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 },
|
||||
) {
|
||||
val bottomNavigation = maxHeight > maxWidth
|
||||
LaunchedEffect(showDeveloperDisplayChoice) {
|
||||
if (showDeveloperDisplayChoice) return@LaunchedEffect
|
||||
LaunchedEffect(processSettingsPageVisible) {
|
||||
if (processSettingsPageVisible) return@LaunchedEffect
|
||||
snapshotFlow { window.isWindowFocused }.first { it }
|
||||
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||
if (s.dualScreen && frontFocus.primaryAttached == 0) focusDualPane()
|
||||
@@ -646,12 +729,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
LaunchedEffect(s.pageKey) {
|
||||
val closed = openPage != null && s.pageKey == null
|
||||
openPage = s.pageKey
|
||||
if (!closed || frontFocus.focusedRail != null || showDeveloperDisplayChoice || inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
if (!closed || frontFocus.focusedRail != null || processSettingsPageVisible || inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
withFrameNanos { }
|
||||
runCatching { frontFocus.paneEntry().requestFocus() }
|
||||
}
|
||||
LaunchedEffect(selected, s.pageKey, showDeveloperDisplayChoice) {
|
||||
if (showDeveloperDisplayChoice) return@LaunchedEffect
|
||||
LaunchedEffect(selected, s.pageKey, processSettingsPageVisible) {
|
||||
if (processSettingsPageVisible) return@LaunchedEffect
|
||||
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
|
||||
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
if (s.pageKey == "performance") {
|
||||
@@ -666,7 +749,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
else focusWithinFrames({ anyFocused }) { if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.railFor(railSelection) }
|
||||
}
|
||||
LaunchedEffect(railPicks) {
|
||||
if (railPicks == 0 || showDeveloperDisplayChoice) return@LaunchedEffect
|
||||
if (railPicks == 0 || processSettingsPageVisible) return@LaunchedEffect
|
||||
kotlinx.coroutines.delay(Motion.ms(PAGE_EXIT_MS).toLong())
|
||||
if (inputModeManager.inputMode != InputMode.Keyboard) return@LaunchedEffect
|
||||
val entry = withTimeoutOrNull(1_000) { snapshotFlow { frontFocus.primaryAttached > 0 }.first { it } }
|
||||
@@ -704,7 +787,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
}
|
||||
var screenAt by remember { mutableStateOf(Offset.Zero) }
|
||||
if (s.dualScreen) DualPanelPublisher(s, railSelection, openTab, { key ->
|
||||
if (showDeveloperDisplayChoice) return@DualPanelPublisher
|
||||
if (processSettingsPageVisible) return@DualPanelPublisher
|
||||
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||
focusManager.clearFocus(force = true)
|
||||
onRailSelect(key)
|
||||
@@ -712,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 (!showDeveloperDisplayChoice) {
|
||||
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)
|
||||
@@ -758,7 +844,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
) {
|
||||
Pane(
|
||||
s, selected, a, page,
|
||||
Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !showDeveloperDisplayChoice && appToChooseDisplay == null }, edgeGuard = { !bottomNavigation }) { dir ->
|
||||
Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }, edgeGuard = { !bottomNavigation }) { dir ->
|
||||
val keys = navigationKeys(s)
|
||||
val at = keys.indexOf(railSelectionNow.value)
|
||||
if (at >= 0) keys.getOrNull(at + dir)?.let { key ->
|
||||
@@ -771,7 +857,9 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
if (s.secondScreenDisplays.isEmpty() && s.ownScreen == null) a.onAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
},
|
||||
onPairWirelessDebugging = startGuidedPairing,
|
||||
onOpenDeveloperOptions = requestChildProcessToggle,
|
||||
onPairWirelessDebugging = { startGuidedPairing(false) },
|
||||
onRequestWirelessAdb = startGuidedPairing,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -803,6 +891,18 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
onDismiss = { appToChooseDisplay = null },
|
||||
)
|
||||
}
|
||||
if (phantomGateVisible) {
|
||||
Box(Modifier.fillMaxSize().background(colors.background)) {
|
||||
PhantomProcessGatePage(
|
||||
status = s.phantomProcessStatus,
|
||||
onDismiss = a.onDismissPhantomGate,
|
||||
onOpenDeveloperOptions = requestChildProcessToggle,
|
||||
applyingSavedPairing = applyingSavedPairing,
|
||||
onFixWithWirelessDebugging = fixPhantomLimit,
|
||||
onCopyCommand = { a.onCopyPhantomCommand(false) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (showDeveloperDisplayChoice) {
|
||||
DeveloperDisplayChoiceDialog(
|
||||
displays = s.secondScreenDisplays.map { display ->
|
||||
@@ -810,14 +910,16 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
},
|
||||
onMainScreen = {
|
||||
showDeveloperDisplayChoice = false
|
||||
openPairingOn(null)
|
||||
openDeveloperOptionsOn(null)
|
||||
},
|
||||
onSecondaryScreen = { displayId ->
|
||||
showDeveloperDisplayChoice = false
|
||||
openPairingOn(displayId)
|
||||
openDeveloperOptionsOn(displayId)
|
||||
},
|
||||
onDismiss = {
|
||||
showDeveloperDisplayChoice = false
|
||||
developerChoiceGuided = false
|
||||
developerChoiceToggle = false
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -826,7 +928,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
(s.pageKey == null && Hops.origin?.page == selected) ||
|
||||
((s.pageKey == null || page == null) &&
|
||||
(selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store"))
|
||||
val exitArmed = !showDeveloperDisplayChoice && !hasBackTarget
|
||||
val exitArmed = !processSettingsPageVisible && !hasBackTarget
|
||||
LaunchedEffect(exitArmed, selected) { ExitGesture.reset() }
|
||||
BackHandler(enabled = exitArmed && DevPreview.drawer == null) {
|
||||
when (ExitGesture.back()) {
|
||||
@@ -843,6 +945,10 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
}
|
||||
}
|
||||
|
||||
internal object ChildProcessSetup {
|
||||
@Volatile var request: (() -> Unit)? = null
|
||||
}
|
||||
|
||||
internal object MainTabSteps {
|
||||
@Volatile var handler: ((Int) -> Unit)? = null
|
||||
@Volatile var otherKeys = 0
|
||||
|
||||
@@ -83,6 +83,8 @@ import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import com.droiddeck.launcher.core.AppLanguage
|
||||
import com.droiddeck.launcher.core.DeviceSupport
|
||||
import com.droiddeck.launcher.core.DownloadSource
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.stores.download.StoreDownloadTier
|
||||
import com.droiddeck.launcher.R
|
||||
@@ -148,10 +150,13 @@ internal fun CheckRow(state: CheckState, title: String, detail: String?, divider
|
||||
internal fun SetupPanel(
|
||||
s: FrontEndState,
|
||||
a: FrontEndActions,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onRequestWirelessAdb: (Boolean) -> Unit,
|
||||
onPairWirelessDebugging: () -> Unit,
|
||||
) {
|
||||
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
|
||||
@@ -166,6 +171,21 @@ internal fun SetupPanel(
|
||||
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) }
|
||||
val setProcessLimit: (Boolean) -> Unit = { enabled ->
|
||||
processLimitBusy = true
|
||||
processLimitMessage = null
|
||||
a.onSetPhantomProcessLimit(enabled) { error ->
|
||||
processLimitBusy = false
|
||||
if (error == null) {
|
||||
a.onRefreshPhantomStatus()
|
||||
} else {
|
||||
processLimitMessage = ctx.getString(R.string.setup_limit_adb_failed)
|
||||
onRequestWirelessAdb(enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
val runtime = when {
|
||||
s.busy -> stringResource(R.string.common_working)
|
||||
s.removalPending -> stringResource(R.string.setup_retry_removal)
|
||||
@@ -178,7 +198,9 @@ internal fun SetupPanel(
|
||||
val gpu = remember { com.droiddeck.launcher.gpu.GpuInfo.detect() }
|
||||
val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED || s.vkBridge
|
||||
val gpuName = remember { DeviceSupport.gpuName(ctx) }
|
||||
val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
val signedIn = s.offlineAccount != null
|
||||
var showLimitDetails by rememberSaveable { mutableStateOf(false) }
|
||||
var editSgdbKey by remember { mutableStateOf(false) }
|
||||
var editDownloadPrefix by remember { mutableStateOf(false) }
|
||||
var editDownloadProxy by remember { mutableStateOf(false) }
|
||||
@@ -210,6 +232,12 @@ internal fun SetupPanel(
|
||||
var tabTurned by remember { mutableStateOf(false) }
|
||||
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true; searching = false; query = ""; if (i == DEVELOPER_TAB) logsRefresh++ }
|
||||
val inputModeManager = LocalInputModeManager.current
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
kotlinx.coroutines.delay(2_000)
|
||||
a.onRefreshPhantomStatus()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(tab) {
|
||||
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
@@ -217,7 +245,7 @@ internal fun SetupPanel(
|
||||
}
|
||||
}
|
||||
val runtimeOk = s.ready && !s.busy && !s.removalPending
|
||||
val checks = listOf(gpuOk, runtimeOk, signedIn)
|
||||
val checks = listOf(gpuOk, runtimeOk, !limitBlocks, signedIn)
|
||||
val passing = checks.count { it }
|
||||
var showChecks by rememberSaveable { mutableStateOf(s.vkBridge) }
|
||||
Rise(0, Modifier.fillMaxSize()) {
|
||||
@@ -241,10 +269,10 @@ 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()
|
||||
OnboardingCard(limitBlocks, a.onShowPhantomGate)
|
||||
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
|
||||
val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()
|
||||
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
|
||||
@@ -333,6 +361,41 @@ internal fun SetupPanel(
|
||||
if (divider) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
}
|
||||
val limitCheck: @Composable (Boolean) -> Unit = { divider ->
|
||||
CheckRow(
|
||||
if (limitBlocks) CheckState.WARN else CheckState.OK,
|
||||
stringResource(R.string.setup_limit),
|
||||
when (s.phantomProcessStatus) {
|
||||
PhantomProcessStatus.ENABLED -> stringResource(R.string.setup_limit_on)
|
||||
PhantomProcessStatus.UNSET -> stringResource(R.string.setup_limit_unset)
|
||||
PhantomProcessStatus.UNREADABLE -> stringResource(R.string.setup_limit_unknown)
|
||||
else -> PhantomProcessLimit.title(ctx, s.phantomProcessStatus)
|
||||
},
|
||||
divider = divider && !showLimitDetails,
|
||||
) {
|
||||
if (limitBlocks) PrimaryButton(stringResource(R.string.setup_fix_it), compact = true, onClick = a.onShowPhantomGate)
|
||||
else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
|
||||
SecondaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_details), compact = true) { showLimitDetails = !showLimitDetails }
|
||||
}
|
||||
}
|
||||
AnimatedVisibility(showLimitDetails, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) {
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, top = 4.dp, bottom = 10.dp)) {
|
||||
Text(
|
||||
if (limitBlocks) PhantomProcessLimit.gateInstructions(ctx, s.phantomProcessStatus)
|
||||
else PhantomProcessLimit.instructions(ctx, s.phantomProcessStatus),
|
||||
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp),
|
||||
)
|
||||
Actions {
|
||||
if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
|
||||
SecondaryButton(stringResource(R.string.setup_limit_turn_on), compact = true, enabled = !processLimitBusy) { setProcessLimit(true) }
|
||||
}
|
||||
}
|
||||
if (processLimitBusy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp))
|
||||
processLimitMessage?.let { Text(it, fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp)) }
|
||||
}
|
||||
}
|
||||
if (divider && showLimitDetails) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
val accountCheck: @Composable (Boolean) -> Unit = { divider ->
|
||||
CheckRow(
|
||||
if (signedIn) CheckState.OK else CheckState.WARN,
|
||||
@@ -347,12 +410,14 @@ internal fun SetupPanel(
|
||||
divider = divider,
|
||||
)
|
||||
}
|
||||
val all = listOf(gpuCheck, runtimeCheck, accountCheck)
|
||||
val all = listOf(gpuCheck, runtimeCheck, limitCheck, accountCheck)
|
||||
ReadinessCard(
|
||||
passing, checks.size,
|
||||
listOfNotNull(
|
||||
gpu.displayName(ctx),
|
||||
s.installed?.let { stringResource(R.string.setup_ready_runtime, it) },
|
||||
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 },
|
||||
@@ -401,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 ->
|
||||
@@ -617,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) },
|
||||
)
|
||||
@@ -793,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)
|
||||
@@ -814,33 +936,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
) {
|
||||
host.open = if (host.open == "fg") null else "fg"
|
||||
}
|
||||
if (host.open == "fg") 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
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
}
|
||||
}
|
||||
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
|
||||
@@ -872,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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1255,7 +1356,7 @@ private fun CustomColorRows() {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun OnboardingCard() {
|
||||
internal fun OnboardingCard(limitBlocks: Boolean = false, onSetUpLimit: () -> Unit = {}) {
|
||||
val active by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
|
||||
val failed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
|
||||
val facts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
|
||||
@@ -1301,5 +1402,18 @@ internal fun OnboardingCard() {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (limitBlocks) {
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.setup_limit), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Text(stringResource(R.string.onboarding_limit_reason), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
PrimaryButton(stringResource(R.string.onboarding_limit_action), compact = true, onClick = onSetUpLimit)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -531,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,
|
||||
@@ -563,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 {
|
||||
@@ -753,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() } }
|
||||
}
|
||||
@@ -908,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()
|
||||
|
||||
@@ -487,7 +487,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
}
|
||||
}
|
||||
}
|
||||
for (found in s.foundSteamLibraries) {
|
||||
if (s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) for (found in s.foundSteamLibraries) {
|
||||
SettingsRow(
|
||||
found.label,
|
||||
stringResource(R.string.libraries_found_hint, pluralStringResource(R.plurals.mode_added_count, found.games, found.games), found.shown),
|
||||
@@ -495,17 +495,19 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
SecondaryButton(stringResource(R.string.libraries_add_found), compact = true) { a.onAddFoundSteamLibrary(found.path) }
|
||||
}
|
||||
}
|
||||
if (s.allFilesAccessMissing) {
|
||||
if (s.allFilesAccessMissing && s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) {
|
||||
SettingsRow(stringResource(R.string.libraries_access_title), stringResource(R.string.libraries_access_hint)) {
|
||||
SecondaryButton(stringResource(R.string.libraries_access_allow), compact = true, onClick = a.onAllowAllFilesAccess)
|
||||
}
|
||||
}
|
||||
SettingsRow(
|
||||
stringResource(R.string.libraries_add),
|
||||
stringResource(R.string.libraries_hint),
|
||||
if (s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX) stringResource(R.string.libraries_hint)
|
||||
else stringResource(R.string.libraries_full, com.droiddeck.launcher.session.SteamLibraries.MAX),
|
||||
) {
|
||||
SecondaryButton(
|
||||
stringResource(R.string.mode_choose_folder),
|
||||
enabled = s.steamLibraries.size < com.droiddeck.launcher.session.SteamLibraries.MAX,
|
||||
onClick = a.onAddSteamLibrary,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@ import com.droiddeck.launcher.input.PcKey
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -69,6 +72,9 @@ fun PcKeyboard(
|
||||
sendKey: (Int, Boolean) -> Unit,
|
||||
onAndroidKeyboard: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
heightFraction: Float? = null,
|
||||
showButtons: Boolean = true,
|
||||
hoverFeedback: Boolean = false,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -76,31 +82,40 @@ fun PcKeyboard(
|
||||
var capsOn by remember { mutableStateOf(false) }
|
||||
val firstKey = remember { FocusRequester() }
|
||||
val shifted = (mods[42] ?: MOD_OFF) != MOD_OFF || (mods[54] ?: MOD_OFF) != MOD_OFF
|
||||
// Keys go to wherever sendKey points now, but a held key is let go where it went down.
|
||||
val currentSend by androidx.compose.runtime.rememberUpdatedState(sendKey)
|
||||
val heldAt = remember { mutableMapOf<Int, (Int, Boolean) -> Unit>() }
|
||||
fun down(code: Int) {
|
||||
val send = currentSend
|
||||
heldAt[code] = send
|
||||
send(code, true)
|
||||
}
|
||||
fun up(code: Int) = (heldAt.remove(code) ?: currentSend)(code, false)
|
||||
|
||||
fun releaseOnceModifiers() {
|
||||
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { sendKey(code, false); mods[code] = MOD_OFF }
|
||||
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { up(code); mods[code] = MOD_OFF }
|
||||
}
|
||||
fun press(key: PcKey) {
|
||||
if (key.code in PC_MODIFIERS) {
|
||||
when (mods[key.code] ?: MOD_OFF) {
|
||||
MOD_OFF -> { sendKey(key.code, true); mods[key.code] = MOD_ONCE }
|
||||
MOD_OFF -> { down(key.code); mods[key.code] = MOD_ONCE }
|
||||
MOD_ONCE -> mods[key.code] = MOD_LOCKED
|
||||
else -> { sendKey(key.code, false); mods[key.code] = MOD_OFF }
|
||||
else -> { up(key.code); mods[key.code] = MOD_OFF }
|
||||
}
|
||||
return
|
||||
}
|
||||
sendKey(key.code, true)
|
||||
down(key.code)
|
||||
}
|
||||
fun release(key: PcKey) {
|
||||
if (key.code in PC_MODIFIERS) return
|
||||
sendKey(key.code, false)
|
||||
up(key.code)
|
||||
if (key.code == 58) capsOn = !capsOn
|
||||
releaseOnceModifiers()
|
||||
}
|
||||
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||
onDispose { for ((code, state) in mods.toMap()) if (state != MOD_OFF) sendKey(code, false) }
|
||||
onDispose { for (code in heldAt.keys.toList()) up(code) }
|
||||
}
|
||||
LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } }
|
||||
LaunchedEffect(Unit) { if (!hoverFeedback) runCatching { firstKey.requestFocus() } }
|
||||
|
||||
val prefsContext = LocalContext.current
|
||||
remember { PcKeyboardPrefs.load(prefsContext) }
|
||||
@@ -108,7 +123,7 @@ fun PcKeyboard(
|
||||
val rows = PC_KEY_ROWS.map { row -> row.filter { it.code !in hiddenCodes } }.filter { it.isNotEmpty() }
|
||||
|
||||
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
|
||||
val rowHeight = ((maxHeight * (PcKeyboardPrefs.size / 100f) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
|
||||
val rowHeight = ((maxHeight * (heightFraction ?: (PcKeyboardPrefs.size / 100f)) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
|
||||
.coerceIn(20.dp, 56.dp)
|
||||
Box(
|
||||
Modifier.fillMaxWidth()
|
||||
@@ -122,9 +137,11 @@ fun PcKeyboard(
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(24.dp)) {
|
||||
Text(stringResource(R.string.drawer_pc_keyboard), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant)
|
||||
Spacer(Modifier.weight(1f))
|
||||
HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
HeaderButton(stringResource(R.string.pckb_hide), onClose)
|
||||
if (showButtons) {
|
||||
HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
HeaderButton(stringResource(R.string.pckb_hide), onClose)
|
||||
}
|
||||
}
|
||||
rows.forEachIndexed { r, row ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) {
|
||||
@@ -139,7 +156,7 @@ fun PcKeyboard(
|
||||
}
|
||||
key(key.code) {
|
||||
KeyCap(
|
||||
label, key.weight, lit, locked = state == MOD_LOCKED,
|
||||
label, key.weight, lit, locked = state == MOD_LOCKED, hoverFeedback = hoverFeedback,
|
||||
modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier,
|
||||
onDown = { press(key) }, onUp = { release(key) },
|
||||
)
|
||||
@@ -154,25 +171,35 @@ fun PcKeyboard(
|
||||
|
||||
@Composable
|
||||
private fun RowScope.KeyCap(
|
||||
label: String, weight: Float, lit: Boolean, locked: Boolean,
|
||||
label: String, weight: Float, lit: Boolean, locked: Boolean, hoverFeedback: Boolean,
|
||||
modifier: Modifier, onDown: () -> Unit, onUp: () -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val focused by src.collectIsFocusedAsState()
|
||||
val hovered by src.collectIsHoveredAsState()
|
||||
val (pointedAt, laser) = com.droiddeck.launcher.session.xr.rememberXrPointed()
|
||||
val pointed = hoverFeedback && (hovered || laser.value)
|
||||
var down by remember { mutableStateOf(false) }
|
||||
val fill by animateColorAsState(
|
||||
when {
|
||||
down -> pal.signal.copy(alpha = 0.55f)
|
||||
lit -> pal.signal.copy(alpha = if (locked) 0.45f else 0.28f)
|
||||
pointed -> Color.White.copy(alpha = 0.2f)
|
||||
else -> Color.White.copy(alpha = 0.07f)
|
||||
}, Motion.tw(160), label = "keyFill",
|
||||
}, Motion.tw(if (down) 40 else 160), label = "keyFill",
|
||||
)
|
||||
val scale by animateFloatAsState(
|
||||
if (!hoverFeedback) 1f else if (down) 0.9f else if (pointed) 1.06f else 1f, Motion.tw(if (down) 40 else 140), label = "keyScale",
|
||||
)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.weight(weight).fillMaxHeight()
|
||||
.then(pointedAt)
|
||||
.graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale }
|
||||
.background(fill, RoundedCornerShape(7.dp))
|
||||
.glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f))
|
||||
.glideBorder(if (hoverFeedback) pointed || down else focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f))
|
||||
.then(if (hoverFeedback) Modifier.hoverable(src) else Modifier)
|
||||
.pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
awaitFirstDown().consume()
|
||||
|
||||
Loaded 100 of 353 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user