diff --git a/.gitattributes b/.gitattributes
index 3cb68a29e..4c0a6c312 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -3,7 +3,6 @@ tools/mangoapp/** text=auto eol=lf
tools/comet/LICENSE whitespace=-blank-at-eof
tools/comet/droiddeck.patch whitespace=-blank-at-eol,-blank-at-eof
-# These helpers are packaged verbatim and executed inside the Linux runtime.
tools/linuxfs/overlay/** text eol=lf
tools/linuxfs/desktop/** text eol=lf
tools/mangoapp/mangoapp text eol=lf
diff --git a/.github/trusted-test-builds.txt b/.github/trusted-test-builds.txt
new file mode 100644
index 000000000..f91528f39
--- /dev/null
+++ b/.github/trusted-test-builds.txt
@@ -0,0 +1,4 @@
+FX192
+K11MCH1
+kingokksa
+ovurrsl
diff --git a/.github/workflows/authorship.yml b/.github/workflows/authorship.yml
index 97c6637a8..ebbcae644 100644
--- a/.github/workflows/authorship.yml
+++ b/.github/workflows/authorship.yml
@@ -23,7 +23,7 @@ permissions:
jobs:
validate:
- name: Build APK
+ name: Validate source and build result
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
diff --git a/.github/workflows/build-desktop-kde.yml b/.github/workflows/build-desktop-kde.yml
index 365e3d4f8..3d720dcb9 100644
--- a/.github/workflows/build-desktop-kde.yml
+++ b/.github/workflows/build-desktop-kde.yml
@@ -60,11 +60,12 @@ jobs:
- name: Build
run: |
set -euo pipefail
- sudo apt-get update -qq && sudo apt-get install -y -qq zstd xz-utils gpgv >/dev/null
- KDE_KWIN_OVERRIDE="$PWD/out/kwin" tools/desktop-kde/build.sh out
+ sudo apt-get update -qq && sudo apt-get install -y -qq zstd xz-utils gpgv gcc-aarch64-linux-gnu >/dev/null
+ KDE_KWIN_OVERRIDE="$PWD/out/kwin" DESKTOP_KDE_RELEASE_TAG='${{ inputs.tag }}' tools/desktop-kde/build.sh out
cp out/kwin/desktop-kde.kwin.txt out/
echo "size $(stat -c %s out/desktop-kde.tar.zst) sha256 $(cat out/desktop-kde.sha256)"
echo "language packs $(ls out/desktop-kde-i18n-*.tar.zst | wc -l)"
+ echo "pacman repository $(ls out/repo | wc -l) files, $(du -sm out/repo | cut -f1) MiB"
- uses: actions/upload-artifact@v4
with:
name: desktop-kde
@@ -77,6 +78,7 @@ jobs:
out/desktop-kde.sha256
out/desktop-kde.i18n.txt
out/desktop-kde-i18n-*.tar.zst
+ out/repo/
- name: Publish
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
env:
@@ -89,8 +91,10 @@ jobs:
echo "::error::$TAG is already published in DroidDeck-Components, and published tags are never replaced: use a new tag"
exit 1
fi
- gh release create "$TAG" --latest=false --prerelease=false --title "$TAG" \
+ prerelease=false
+ case $TAG in *-rc*) prerelease=true ;; esac
+ gh release create "$TAG" --latest=false --prerelease="$prerelease" --title "$TAG" \
--notes "KDE Plasma desktop package for DroidDeck's Linux runtime ($GITHUB_REPOSITORY tools/desktop-kde, $GITHUB_SHA). size $(stat -c %s out/desktop-kde.tar.zst), sha256 $(cat out/desktop-kde.sha256). desktop-kde.packages.txt lists the signature-checked Arch Linux ARM packages it was built from." \
out/desktop-kde.tar.zst out/desktop-kde.sha256 out/desktop-kde.packages.txt out/desktop-kde.kwin.txt \
- out/desktop-kde.i18n.txt out/desktop-kde-i18n-*.tar.zst
- gh release edit "$TAG" --latest=false --prerelease=false
+ out/desktop-kde.i18n.txt out/desktop-kde-i18n-*.tar.zst out/repo/*
+ gh release edit "$TAG" --latest=false --prerelease="$prerelease"
diff --git a/.github/workflows/build-fex.yml b/.github/workflows/build-fex.yml
index 8ec3369a1..deb099100 100644
--- a/.github/workflows/build-fex.yml
+++ b/.github/workflows/build-fex.yml
@@ -1,8 +1,5 @@
name: Build FEX (x86-64 Steam client)
-# Checks tools/fex: the same build DroidDeck-Components' build-fex.yml runs from this repository to publish FEX
-# (its single `fex` release and fex.json, which the app follows). Nothing is published from here.
-
on:
push:
paths:
@@ -31,7 +28,6 @@ jobs:
with:
persist-credentials: false
- name: Build in Arch Linux ARM
- # Inputs reach the shell as environment variables, never pasted into the script.
env:
FEX_EXTRA_CXXFLAGS: ${{ inputs.cxxflags }}
FEX_THUNKS: ${{ inputs.thunks == 'true' && '1' || '0' }}
diff --git a/.github/workflows/build-ubuntu-runtime.yml b/.github/workflows/build-ubuntu-runtime.yml
new file mode 100644
index 000000000..f104e9cd7
--- /dev/null
+++ b/.github/workflows/build-ubuntu-runtime.yml
@@ -0,0 +1,95 @@
+name: Build Linux runtime (Ubuntu)
+
+on:
+ push:
+ paths:
+ - 'tools/ubuntu/**'
+ - '.github/workflows/build-ubuntu-runtime.yml'
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: 'Release tag to publish as (e.g. ubuntu-r1); empty = artifact only'
+ required: false
+ default: ''
+
+permissions:
+ contents: read
+
+jobs:
+ debs:
+ runs-on: ubuntu-24.04-arm
+ timeout-minutes: 240
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+ - name: Build Mesa with KGSL and the patched KWin
+ run: |
+ set -euo pipefail
+ docker run --rm -v "$PWD:/work" -w /work ubuntu:26.04 bash tools/ubuntu/build-debs.sh /work/out/debs
+ sudo chown -R "$(id -u):$(id -g)" out
+ - uses: actions/upload-artifact@v4
+ with:
+ name: ubuntu-runtime-debs
+ retention-days: 7
+ compression-level: 0
+ path: out/debs/
+ rootfs:
+ needs: debs
+ runs-on: ubuntu-24.04-arm
+ timeout-minutes: 120
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+ - uses: actions/download-artifact@v4
+ with:
+ name: ubuntu-runtime-debs
+ path: out/debs
+ - uses: actions/create-github-app-token@v2
+ id: components-token
+ if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
+ with:
+ app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
+ private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
+ owner: Droid-Deck
+ repositories: DroidDeck-Components
+ - name: Refuse a published tag
+ if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
+ env:
+ GH_TOKEN: ${{ steps.components-token.outputs.token }}
+ run: |
+ if gh release view '${{ inputs.tag }}' -R Droid-Deck/DroidDeck-Components >/dev/null 2>&1; then
+ echo "::error::${{ inputs.tag }} is already published, and published tags are never replaced: use a new tag"
+ exit 1
+ fi
+ - name: Build
+ run: |
+ set -euo pipefail
+ sudo apt-get update -qq && sudo apt-get install -y -qq zstd gpgv ubuntu-keyring >/dev/null
+ tag='${{ inputs.tag }}'
+ tools/ubuntu/build.sh out/debs out "${tag:-ubuntu-dev}"
+ - uses: actions/upload-artifact@v4
+ with:
+ name: ubuntu-runtime
+ retention-days: 7
+ compression-level: 0
+ path: |
+ out/*.tar.zst
+ out/*.sha256
+ out/*.packages.txt
+ - name: Publish
+ if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
+ env:
+ GH_TOKEN: ${{ steps.components-token.outputs.token }}
+ GH_REPO: Droid-Deck/DroidDeck-Components
+ run: |
+ set -euo pipefail
+ TAG='${{ inputs.tag }}'
+ prerelease=false
+ case $TAG in *-rc*) prerelease=true ;; esac
+ gh release create "$TAG" --latest=false --prerelease="$prerelease" --title "$TAG" \
+ --notes "Ubuntu 26.04 LTS arm64 runtime for DroidDeck ($GITHUB_REPOSITORY tools/ubuntu, $GITHUB_SHA): size $(stat -c %s "out/$TAG.tar.zst"), sha256 $(cat "out/$TAG.sha256"). $TAG-desktop.tar.zst is the Kubuntu Plasma desktop built on top of it, holding only what the runtime does not already have: size $(stat -c %s "out/$TAG-desktop.tar.zst"), sha256 $(cat "out/$TAG-desktop.sha256"). The .packages.txt files list every installed package and version." \
+ "out/$TAG.tar.zst" "out/$TAG.sha256" "out/$TAG.packages.txt" \
+ "out/$TAG-desktop.tar.zst" "out/$TAG-desktop.sha256" "out/$TAG-desktop.packages.txt" out/debs/*.deb
+ gh release edit "$TAG" --latest=false --prerelease="$prerelease"
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index ebfd545ca..1a1d97cf6 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -8,6 +8,8 @@ on:
- '**/*.md'
- 'LICENSE'
- '.gitignore'
+ - 'docs/**'
+ - '.github/ISSUE_TEMPLATE/**'
pull_request:
branches: [ main ]
types: [ opened, synchronize, reopened, ready_for_review ]
@@ -15,33 +17,42 @@ on:
- '**/*.md'
- 'LICENSE'
- '.gitignore'
+ - 'docs/**'
+ - '.github/ISSUE_TEMPLATE/**'
workflow_dispatch:
+ inputs:
+ rebuild_preloads:
+ description: Rebuild preloads instead of reusing the approved binary snapshot
+ type: boolean
+ default: false
permissions:
contents: read
+ actions: read
pull-requests: write
concurrency:
- group: build-${{ github.event.pull_request.number || github.run_id }}
- cancel-in-progress: ${{ github.event_name == 'pull_request' }}
-
-env:
- PRELOAD_CACHE_VERSION: v6
+ group: build-${{ 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:
- xbox:
- name: Xbox ARM64 backend
+ source:
+ name: Pin source tree
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
- runs-on: ubuntu-24.04-arm
- timeout-minutes: 30
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
outputs:
- base-sha: ${{ steps.merge.outputs.base-sha }}
+ base-sha: ${{ steps.merge.outputs.base-sha || steps.trusted.outputs.base-sha }}
tree-sha: ${{ steps.source.outputs.tree-sha }}
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: Pin and merge the APK source
id: merge
@@ -52,10 +63,54 @@ jobs:
echo "base-sha=$(git rev-parse origin/main)" >> "$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
- - name: Record backend source tree
+ - name: Resolve trusted manifest base
+ id: trusted
+ if: github.event_name != 'pull_request'
+ run: |
+ set -euo pipefail
+ git fetch --no-tags origin main
+ echo "base-sha=$(git rev-parse origin/main)" >> "$GITHUB_OUTPUT"
+ - name: Record pinned source tree
id: source
run: echo "tree-sha=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
+
+ xbox:
+ name: Xbox ARM64 backend
+ needs: source
+ if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
+ runs-on: ubuntu-24.04-arm
+ timeout-minutes: 30
+ 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:
+ BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
+ run: |
+ set -euo pipefail
+ git fetch --no-tags origin "$BUILD_BASE_SHA"
+ git config user.name "ci"
+ git config user.email "ci@users.noreply.github.com"
+ git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true
+ git merge --no-ff --no-edit FETCH_HEAD
+ - name: Verify pinned source tree
+ env:
+ SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
+ run: test "$(git rev-parse 'HEAD^{tree}')" = "$SOURCE_TREE"
+ - name: Plan component identities
+ id: plan
+ run: python3 tools/components/prepare.py plan
- uses: actions/cache@v4
id: xbox-cache
with:
@@ -63,14 +118,10 @@ jobs:
app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
app/build/xbox/xodus-droiddeck-source.tar.xz
app/build/xbox/runtime/*-source.tar.xz
- key: xbox-arm64-${{ hashFiles('tools/xbox/**') }}
+ key: xbox-v2-${{ steps.plan.outputs.xbox }}
- name: Build Xbox backend
if: steps.xbox-cache.outputs.cache-hit != 'true'
- run: |
- rustup toolchain install 1.99.0 --profile minimal
- sudo apt-get update -qq
- sudo apt-get install -y build-essential pkg-config libssl-dev protobuf-compiler cmake xz-utils
- bash tools/xbox/build.sh
+ run: python3 tools/components/prepare.py xbox
- uses: actions/upload-artifact@v4
with:
name: xbox-arm64
@@ -85,9 +136,166 @@ jobs:
if-no-files-found: error
retention-days: 14
+ components:
+ name: Prepare verified components
+ needs: source
+ if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 40
+ 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:
+ BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
+ run: |
+ set -euo pipefail
+ git fetch --no-tags origin "$BUILD_BASE_SHA"
+ git config user.name "ci"
+ git config user.email "ci@users.noreply.github.com"
+ git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true
+ git merge --no-ff --no-edit FETCH_HEAD
+ - name: Verify pinned source tree
+ env:
+ SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
+ run: test "$(git rev-parse 'HEAD^{tree}')" = "$SOURCE_TREE"
+ - name: Resolve the pinned Android NDK
+ run: bash tools/ci/resolve-ndk.sh
+
+ - name: Plan component identities
+ id: plan
+ run: python3 tools/components/prepare.py plan
+ - name: Cache remaining Linux runtime assets
+ id: preloads
+ uses: actions/cache@v4
+ with:
+ path: |
+ app/src/main/assets/linuxfs
+ !app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet
+ !app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
+ !app/src/main/assets/linuxfs/i386/libblsession.so
+ !app/src/main/assets/linuxfs/i386/libfakeinput.so
+ !app/src/main/assets/linuxfs/i386/libfaultreport.so
+ !app/src/main/assets/linuxfs/libblaudit.so
+ !app/src/main/assets/linuxfs/libblfastpath.so
+ !app/src/main/assets/linuxfs/libblsession.so
+ !app/src/main/assets/linuxfs/libfakeinput.so
+ !app/src/main/assets/linuxfs/libssbs.so
+ !app/src/main/assets/linuxfs/usr/local/bin/droiddeck-clipboard
+ !app/src/main/assets/linuxfs/x86_64/libblsession.so
+ !app/src/main/assets/linuxfs/x86_64/libfakeinput.so
+ !app/src/main/assets/linuxfs/x86_64/libfaultreport.so
+ !app/src/main/assets/linuxfs/x86_64/libvulkan-thunk.so
+ !app/src/main/assets/linuxfs/x86_64/libwebkitinput.so
+ key: runtime-v9-${{ steps.plan.outputs.runtime }}
+
+ - name: Cache PulseAudio 13.0 source
+ id: pa-src
+ uses: actions/cache@v4
+ 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
+ with:
+ path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet
+ key: comet-v2-${{ steps.plan.outputs.comet }}
+
+ - name: Restore verified preload snapshots
+ id: component-preloads
+ env:
+ GH_TOKEN: ${{ github.token }}
+ FORCE_PRELOAD_REBUILD: ${{ inputs.rebuild_preloads || 'false' }}
+ COMPONENT_TRUSTED_BASE: ${{ needs.source.outputs.base-sha }}
+ run: python3 tools/components/prepare.py preload-snapshot
+
+ - name: Prepare required Linux build tools once
+ env:
+ COMPONENTS_TO_BUILD: >-
+ ${{ steps.preloads.outputs.cache-hit != 'true' && 'runtime' || '' }}
+ ${{ steps.component-preloads.outputs.arm64 != 'true' && 'arm64-preloads' || '' }}
+ ${{ steps.comet.outputs.cache-hit != 'true' && 'comet' || '' }}
+ run: python3 tools/components/prepare.py tools
+
+ - name: Build changed ARM64 preloads
+ if: steps.component-preloads.outputs.arm64 != 'true'
+ run: python3 tools/components/prepare.py arm64-preloads
+
+ - name: Prepare remaining Linux runtime assets
+ if: steps.preloads.outputs.cache-hit != 'true'
+ run: python3 tools/components/prepare.py runtime
+
+ - name: Fetch the Debian image the preloads build in
+ if: steps.component-preloads.outputs.x86 != 'true'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: python3 tools/components/prepare.py debian-image
+
+ - name: Build the x86 preloads FEX guests load (glibc 2.31)
+ if: steps.component-preloads.outputs.x86 != 'true'
+ run: python3 tools/components/prepare.py x86-preloads
+
+ - name: Bundle the droiddeck-esync packs
+ run: python3 tools/components/prepare.py esync
+
+ - name: Fetch PulseAudio 13.0 source
+ if: steps.pa-src.outputs.cache-hit != 'true'
+ run: python3 tools/components/prepare.py pulseaudio-source
+
+ - name: Fetch DirectAudio (tools/directaudio/release.env)
+ run: python3 tools/components/prepare.py directaudio
+
+ - 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: Check the preloads
+ run: |
+ set -euo pipefail
+ bash tools/linuxfs/check-preloads.sh app/src/main/assets/linuxfs
+
+ - name: Build GOG Galaxy companion
+ if: steps.comet.outputs.cache-hit != 'true'
+ run: python3 tools/components/prepare.py comet
+
+ - name: Build the DiRT 3 / DiRT Showdown ws2_32 stand-in
+ run: python3 tools/components/prepare.py dirt-ws2
+
+ - name: Prepare graphics driver variants
+ run: python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/$NDK_VERSION"
+ - name: Record and pack prepared components
+ run: python3 tools/components/prepare.py pack
+ - uses: actions/upload-artifact@v4
+ with:
+ name: prepared-components
+ path: app/build/prepared-components.tar.gz
+ if-no-files-found: error
+ compression-level: 0
+ retention-days: 14
+
build:
- needs: xbox
- name: Compile and test APK
+ needs: [source, components, xbox]
+ name: Compile APK and Android tests
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
runs-on: ubuntu-24.04
timeout-minutes: 45
@@ -98,7 +306,12 @@ jobs:
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
+ submodules: recursive
- name: Check human authorship
env:
@@ -150,7 +363,7 @@ jobs:
- name: Merge onto main, or say what conflicts
if: github.event_name == 'pull_request'
env:
- BUILD_BASE_SHA: ${{ needs.xbox.outputs.base-sha }}
+ BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
run: |
set -uo pipefail
git config user.name "ci"
@@ -159,6 +372,7 @@ jobs:
git fetch --no-tags origin "$BUILD_BASE_SHA"
BASE=$(git rev-parse --short FETCH_HEAD)
HEAD=$(git rev-parse --short HEAD)
+ git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true
if git merge --no-ff --no-edit FETCH_HEAD >/tmp/merge.out 2>&1; then
{
echo "### Mergeable"
@@ -208,28 +422,27 @@ jobs:
- name: Verify backend and APK source match
env:
- XBOX_SOURCE_TREE: ${{ needs.xbox.outputs.tree-sha }}
+ XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
- uses: actions/setup-java@v4
with:
distribution: temurin
- java-version: '17'
+ java-version: '21'
- uses: gradle/actions/setup-gradle@v4
with:
- cache-cleanup: on-success
+ 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 runner's NDK
- run: |
- NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
- VERSION=$(sed -n 's/^Pkg.Revision *= *//p' "$NDK/source.properties")
- echo "NDK_VERSION=$VERSION" >> "$GITHUB_ENV"
+ - 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 }}
@@ -248,266 +461,9 @@ jobs:
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"
- - name: Cache the preloads
- id: preloads
- uses: actions/cache@v4
- with:
- path: app/src/main/assets/linuxfs
- key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/xbox/**', 'tools/linuxfs/debian-image.env', 'tools/vr/**') }}
-
- - name: Build libfakeinput.so and libblsession.so (glibc aarch64)
- if: steps.preloads.outputs.cache-hit != 'true'
- run: |
- set -euo pipefail
- sudo apt-get -o Dir::Etc::sourcelist=sources.list.d/ubuntu.sources \
- -o Dir::Etc::sourceparts=- -o Acquire::Retries=3 update -qq
- sudo apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libvulkan1 mesa-vulkan-drivers >/dev/null
- D=app/src/main/assets/linuxfs
- mkdir -p "$D"
- aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
- -pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \
- -o "$D/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl
- aarch64-linux-gnu-strip --strip-unneeded "$D/libfakeinput.so"
- aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
- -o "$D/libblsession.so" tools/linuxfs/preload/*.c -ldl
- aarch64-linux-gnu-strip --strip-unneeded "$D/libblsession.so"
- aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
- -o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
- aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so"
- aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \
- -fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$D/libblaudit.so" tools/proot/fastpath/audit.c
- aarch64-linux-gnu-strip --strip-unneeded "$D/libblaudit.so"
- aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
- -o "$D/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
- aarch64-linux-gnu-strip --strip-unneeded "$D/libssbs.so"
- mkdir -p "$D/usr/local/bin"
- aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$D/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
- aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-clipboard"
- VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \
- tools/vr/build.sh --native "$D/usr/local/lib/droiddeck-vr"
- for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
- install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
- done
- for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
- [ -f "$f" ] && install -Dm644 "$f" "$D/${f#tools/linuxfs/overlay/}"
- done
- if [ -f tools/gamescope/release.env ]; then
- . tools/gamescope/release.env
- curl -fsSL --retry 3 -o gamescope.tzst "https://github.com/${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}/releases/download/${GAMESCOPE_TAG}/gamescope.tzst"
- echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c -
- tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D"
- test -f "$D/usr/local/bin/gamescope"
- rm gamescope.tzst
- fi
- . tools/linuxfs/uruntime.env
- curl -fsSL --retry 3 -o uruntime "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}"
- echo "${URUNTIME_SHA256} uruntime" | sha256sum -c -
- install -Dm644 uruntime "$D/usr/local/lib/droiddeck/uruntime"
- install -Dm644 tools/linuxfs/licenses/uruntime-LICENSE "$D/usr/local/share/licenses/uruntime/LICENSE"
- rm uruntime
- M="$D/usr/local/lib/mangoapp"
- mkdir -p "$M" mango-pkgs
- grep -v '^#' tools/mangoapp/packages.txt | while read -r sum url; do
- [ -n "$url" ] || continue
- curl -fsSL --retry 3 -o mango-pkgs/pkg.tar.zst "$url"
- echo "$sum mango-pkgs/pkg.tar.zst" | sha256sum -c -
- tar --use-compress-program=unzstd -xf mango-pkgs/pkg.tar.zst -C mango-pkgs
- rm mango-pkgs/pkg.tar.zst
- done
- install -m644 mango-pkgs/usr/bin/mangoapp "$M/mangoapp"
- for so in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
- cp -L "mango-pkgs/usr/lib/$so" "$M/$so"
- done
- aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
- -o "$M/libtracefs.so.1" tools/mangoapp/libtracefs-shim.c
- aarch64-linux-gnu-strip --strip-unneeded "$M/libtracefs.so.1"
- install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp"
- rm -rf mango-pkgs
- ls -l "$M"
- mkdir -p pw-pkgs
- grep -v '^#' tools/pipewire/packages.txt | while read -r sum url; do
- [ -n "$url" ] || continue
- curl -fsSL --retry 3 -o pw-pkgs/pkg.tar.zst "$url"
- echo "$sum pw-pkgs/pkg.tar.zst" | sha256sum -c -
- tar --use-compress-program=unzstd -xf pw-pkgs/pkg.tar.zst -C pw-pkgs
- rm pw-pkgs/pkg.tar.zst
- done
- tools/pipewire/assemble.sh pw-pkgs "$D/usr/local/lib/droiddeck-pipewire.tzst"
- rm -rf pw-pkgs
- ls -l "$D/usr/local/lib/droiddeck-pipewire.tzst"
- T="$D/usr/local/lib/droiddeck-msitools"
- mkdir -p "$T" msi-pkgs
- grep -v '^#' tools/msitools/packages.txt | while read -r sum url; do
- [ -n "$url" ] || continue
- curl -fsSL --retry 3 -o msi-pkgs/pkg.tar.xz "$url"
- echo "$sum msi-pkgs/pkg.tar.xz" | sha256sum -c -
- tar -xJf msi-pkgs/pkg.tar.xz -C msi-pkgs
- rm msi-pkgs/pkg.tar.xz
- done
- install -m644 msi-pkgs/usr/bin/msiinfo "$T/msiinfo"
- install -m644 msi-pkgs/usr/bin/cabextract "$T/cabextract"
- install -m644 msi-pkgs/usr/lib/7zip/7z "$T/7z"
- install -m644 msi-pkgs/usr/lib/7zip/7z.so "$T/7z.so"
- for so in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
- cp -L "msi-pkgs/usr/lib/$so" "$T/$so"
- done
- for f in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do
- install -Dm644 "tools/msitools/licenses/$f" "$D/usr/local/share/licenses/droiddeck-msitools/$f"
- done
- rm -rf msi-pkgs
- ls -l "$T"
- install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$D/usr/local/bin/droiddeck-desktop"
- install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$D/usr/local/bin/droiddeck-gpu"
- install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$D/usr/local/bin/droiddeck-desktop-gpu"
- install -Dm644 tools/linuxfs/desktop/kwin_wayland_wrapper "$D/usr/local/bin/kwin_wayland_wrapper"
- install -Dm644 tools/linuxfs/desktop/firefox-droiddeck.js "$D/usr/lib/firefox/defaults/pref/droiddeck.js"
- ls -lR "$D"
-
- - name: Fetch the Debian image the preloads build in
- if: steps.preloads.outputs.cache-hit != 'true'
- env:
- GH_TOKEN: ${{ github.token }}
- run: |
- set -euo pipefail
- . tools/linuxfs/debian-image.env
- image=public.ecr.aws/docker/library/debian:bullseye
- if gh release download "$DEBIAN_IMAGE_TAG" -R "$GITHUB_REPOSITORY" -p "$DEBIAN_IMAGE_ASSET" -O /tmp/debian-image.tar.zst \
- && { [ -z "$DEBIAN_IMAGE_SHA256" ] || echo "$DEBIAN_IMAGE_SHA256 /tmp/debian-image.tar.zst" | sha256sum -c -; }; then
- zstd -dc /tmp/debian-image.tar.zst | docker load
- rm -f /tmp/debian-image.tar.zst
- else
- echo "::warning::the hosted Debian image could not be fetched; pulling from the registry instead"
- for attempt in 1 2 3 4 5; do
- docker pull "$image" && break
- [ "$attempt" -lt 5 ] || { echo "::error::could not pull $image after $attempt attempts"; exit 1; }
- echo "pull attempt $attempt failed (registry busy?); retrying in $((attempt * 30)) s"
- sleep $((attempt * 30))
- done
- fi
- docker image ls "$image"
-
- - name: Build the x86 preloads FEX guests load (glibc 2.31)
- if: steps.preloads.outputs.cache-hit != 'true'
- run: |
- set -euo pipefail
- docker run --rm -v "$PWD:/src" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
- set -euo pipefail
- install_compilers() {
- apt-get -o Acquire::Check-Valid-Until=false update -qq &&
- DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null
- }
- printf "deb http://deb.debian.org/debian bullseye main\ndeb http://security.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
- if ! install_compilers; then
- printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
- install_compilers
- fi
- tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
- '
- sudo chown -R "$(id -u):$(id -g)" app/src/main/assets/linuxfs
- ls -l app/src/main/assets/linuxfs/x86_64 app/src/main/assets/linuxfs/i386
-
- - name: Bundle the droiddeck-esync packs
- run: |
- set -euo pipefail
- if [ -f tools/droiddeck-esync/release.env ]; then
- . tools/droiddeck-esync/release.env
- release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}"
- curl -fsSL --retry 3 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"
- echo "$SYNC_BUNDLE_SHA256 sync-bundle.tzst" | sha256sum -c -
- mkdir -p app/src/main/assets/droiddeck-esync
- tar --use-compress-program=unzstd -xf sync-bundle.tzst -C app/src/main/assets/droiddeck-esync
- rm sync-bundle.tzst
- curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json"
- revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' sync-index.json)
- for id in $revoked; do
- if [ -e "app/src/main/assets/droiddeck-esync/packs/$id.tzst" ]; then
- echo "::warning::$SYNC_BUNDLE_ASSET carries revoked pack $id; it is left out of the APK (point tools/droiddeck-esync/release.env at a newer bundle)"
- rm -f "app/src/main/assets/droiddeck-esync/packs/$id.tzst"
- fi
- done
- rm sync-index.json
- test -f app/src/main/assets/droiddeck-esync/index.json
- test -f app/src/main/assets/droiddeck-esync/index.json.sig
- ls -lR app/src/main/assets/droiddeck-esync
- fi
-
- - name: Cache PulseAudio 13.0 source
- id: pa-src
- uses: actions/cache@v4
- with:
- path: pa13
- key: pulseaudio-src-13.0
- - name: Fetch PulseAudio 13.0 source
- if: steps.pa-src.outputs.cache-hit != 'true'
- run: |
- set -euo pipefail
- curl -fsSL -o pa.tar.gz https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
- mkdir -p pa13 && tar -xzf pa.tar.gz -C pa13 --strip-components=1 && rm pa.tar.gz
- - name: Fetch DirectAudio (tools/directaudio/release.env)
- run: tools/directaudio/fetch.sh "$PWD" "$PWD/sink-out"
- - name: Build the AAudio sink into the audio bundle
- run: |
- set -euo pipefail
- export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
- tools/aaudio-sink/build.sh "$PWD/pa13" "$PWD/sink-out"
- rm -rf pa-bundle && mkdir -p pa-bundle
- tar --use-compress-program=unzstd -xf app/src/main/assets/pulseaudio.tzst -C pa-bundle
- test ! -f pa-bundle/modules/arm64/module-aaudio-sink.so
- install -m755 sink-out/module-aaudio-sink.so pa-bundle/modules/arm64/module-aaudio-sink.so
- install -m755 sink-out/module-directaudio-native-sink.so pa-bundle/modules/arm64/module-directaudio-native-sink.so
- (cd pa-bundle && tar --use-compress-program='zstd -19' -cf ../pulseaudio.tzst .)
- mkdir -p app/build/prepared-assets
- mv pulseaudio.tzst app/build/prepared-assets/pulseaudio.tzst
- tar --use-compress-program=unzstd -tf app/build/prepared-assets/pulseaudio.tzst | grep -c '\.so$'
- rm -rf pa-bundle sink-out
- - 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-${{ env.NDK_VERSION }}-${{ hashFiles('tools/proot/**') }}
- - name: Build proot
- if: steps.proot.outputs.cache-hit != 'true'
- run: |
- set -euo pipefail
- export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
- tools/proot/build.sh app/src/main/jniLibs/arm64-v8a
-
- - name: Check the preloads
- run: |
- set -euo pipefail
- bash tools/linuxfs/check-preloads.sh app/src/main/assets/linuxfs
-
- - name: Check Quest tracking IPC
- run: |
- set -euo pipefail
- NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
- VK_INCLUDE=$(ls -d "$NDK"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1)
- mkdir -p build/vr/include
- cp -R "$VK_INCLUDE/vulkan" build/vr/include/
- if [ -d "$VK_INCLUDE/vk_video" ]; then cp -R "$VK_INCLUDE/vk_video" build/vr/include/; fi
- g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_tracking.cpp -o /tmp/test-xr-tracking
- /tmp/test-xr-tracking
- g++ -std=c++17 -Wall -Wextra -Werror tools/vr/tests/test_xr_touch.cpp -o /tmp/test-xr-touch
- /tmp/test-xr-touch
- g++ -std=c++17 -Wall -Wextra -Werror tools/vr/tests/test_pad_controller_config.cpp -o /tmp/test-pad-controller-config
- /tmp/test-pad-controller-config
- g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_vsync.cpp -o /tmp/test-xr-vsync
- /tmp/test-xr-vsync
- g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_frames.cpp -o /tmp/test-xr-frames
- /tmp/test-xr-frames
- cc -Itools/vr/third_party/wayland -c tools/vr/src/wayland_client_stub.c -o /tmp/test-wayland-stub.o
- cc -Itools/vr/third_party/wayland -c app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c -o /tmp/test-xdg-shell.o
- g++ -std=c++17 -Wall -Wextra -Werror -Wno-unused-parameter -Wno-missing-field-initializers -pthread -Ibuild/vr/include \
- -Itools/vr/third_party/wayland -Iapp/src/main/cpp/waylandcomp/generated \
- tools/vr/tests/test_presenter_shutdown.cpp tools/vr/src/presenter.cpp /tmp/test-wayland-stub.o /tmp/test-xdg-shell.o \
- -ldl -o /tmp/test-presenter-shutdown
- timeout 10 /tmp/test-presenter-shutdown
-
- name: Rust toolchain for the store engines (aarch64-linux-android)
id: rust
run: |
@@ -525,9 +481,10 @@ jobs:
~/.cargo/git/db
~/.cargo/bin/cargo-ndk
app/src/main/rust/stores/target
- key: stores-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}
+ key: stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-${{ hashFiles('app/src/main/rust/stores/src/**', 'app/src/main/rust/stores/Cargo.toml', 'app/src/main/rust/stores/build.rs', 'app/src/main/rust/stores/.cargo/**', 'app/build.gradle') }}
restore-keys: |
- stores-${{ steps.rust.outputs.rustc }}-
+ stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-
+ stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-
- name: cargo-ndk
run: |
@@ -545,21 +502,63 @@ jobs:
restore-keys: |
cxx-${{ env.NDK_VERSION }}-
+ - uses: actions/download-artifact@v4
+ with:
+ name: prepared-components
+ path: app/build
+ - name: Verify and unpack prepared components
+ env:
+ SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
+ run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE"
+
- uses: actions/download-artifact@v4
with:
name: xbox-arm64
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
- - name: Build GOG Galaxy companion
- if: steps.preloads.outputs.cache-hit != 'true'
- run: |
- rustup toolchain install 1.90.0 --profile minimal
- rustup target add --toolchain 1.90.0 aarch64-unknown-linux-gnu
- RUSTUP_TOOLCHAIN=1.90.0 bash tools/comet/build.sh
-
+ - name: Cache checksum-pinned pack inputs
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/droiddeck-pack-inputs
+ key: pack-inputs-v1-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env') }}
+ restore-keys: pack-inputs-v1-
- name: Build the add-on packs
run: bash tools/packs/build.sh app/build/packs
+ - name: Pin the Syncthing source
+ id: syncthing-src
+ run: |
+ set -euo pipefail
+ git submodule update --init --recursive tools/syncthing/syncthing-android
+ echo "commit=$(git -C tools/syncthing/syncthing-android/syncthing/src/github.com/syncthing/syncthing rev-parse HEAD)" >> "$GITHUB_OUTPUT"
+ - name: Cache Syncthing
+ id: syncthing
+ uses: actions/cache@v4
+ with:
+ path: app/src/main/jniLibs/arm64-v8a/libsyncthingnative.so
+ key: syncthing-${{ env.NDK_VERSION }}-${{ hashFiles('tools/syncthing/build.sh', 'tools/syncthing/syncthing-android/gradle/libs.versions.toml') }}-${{ steps.syncthing-src.outputs.commit }}
+ - uses: actions/setup-go@v5
+ if: steps.syncthing.outputs.cache-hit != 'true'
+ with:
+ go-version: stable
+ cache: false
+ - name: Build Syncthing
+ if: steps.syncthing.outputs.cache-hit != 'true'
+ run: |
+ set -euo pipefail
+ export NDK="$ANDROID_HOME/ndk/$NDK_VERSION"
+ tools/syncthing/build.sh app/src/main/jniLibs/arm64-v8a
+
+ - name: Note when the proot pack pin is behind 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)
+ if [ "$sha" != "$PROOT_PACK_SHA256" ]; then
+ echo "::warning::built proot pack $sha does not match tools/packs/proot/release.env ($PROOT_PACK_SHA256). This build publishes the pack it just built. Source builds keep downloading the pinned pack until release.env is updated."
+ fi
+
- name: Build
id: build
env:
@@ -567,7 +566,6 @@ jobs:
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
run: |
set -o pipefail
- python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/$NDK_VERSION"
python3 tools/release/runtime_inputs.py record
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
python3 tools/release/check_session_assets.py app/build/outputs/apk/release/app-release.apk
@@ -583,13 +581,6 @@ jobs:
git diff --exit-code -- app/src/main/rust/stores/Cargo.lock \
|| { echo "::error::Cargo.lock changed during the build; commit the regenerated lockfile (uploaded as stores-cargo-lock)"; exit 1; }
- - name: Store engines host unit tests
- timeout-minutes: 10
- continue-on-error: true
- run: |
- cd app/src/main/rust/stores
- cargo test --locked 2>&1 | tail -60
-
- name: Upload the regenerated Cargo.lock
if: failure()
uses: actions/upload-artifact@v4
@@ -598,16 +589,11 @@ jobs:
path: app/src/main/rust/stores/Cargo.lock
if-no-files-found: ignore
- - name: Install Python test dependencies
- run: |
- sudo apt-get update -qq
- sudo apt-get install -y -qq python3-yaml gcc-aarch64-linux-gnu qemu-user
-
- - name: Steam import and game environment tests
- run: python3 -m unittest discover -s tools/tests -p 'test_*.py'
-
- 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
@@ -682,87 +668,147 @@ jobs:
UNIT_TEST_OUTCOME: ${{ steps.unit-tests.outcome }}
TEST_DIAGNOSTICS_URL: ${{ steps.unit-test-diagnostics.outputs.artifact-url }}
APK_OUTCOME: ${{ steps.apk-upload.outcome }}
- SAME_REPO: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
+ run: bash tools/release/report-build.sh
+
+ store-tests:
+ name: Store engines host tests
+ needs: source
+ if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 15
+ continue-on-error: true
+ permissions:
+ contents: read
+ actions: read
+ 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:
+ BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
run: |
- set -uo pipefail
- MARK=""
- {
- echo "$MARK"
- echo "## Build of this pull request"
- echo
- [ -f /tmp/pr-merge.md ] && cat /tmp/pr-merge.md
- echo
- case "$BUILD_OUTCOME:$UNIT_TEST_OUTCOME:$APK_OUTCOME" in
- success:success:success)
- echo "### Build passed"
- echo
- echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key."
- echo
- if [ "$SAME_REPO" = true ]; then
- echo "A release-signed tester build that installs over Stable or Preview is being published now and will appear in DroidDeck's **Test builds** list. Label the PR \`no-test-build\` to skip that."
- else
- echo "**Maintainer:** add the \`publish-test\` label to publish a release-signed tester build that installs over Stable or Preview and appears in DroidDeck's **Test builds** list. The label is removed automatically after publishing."
- fi
- echo
- echo "Fallback: [open **PR Release Publish**]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/workflows/pr-release-publish.yml) on \`main\` and enter PR \`$PR\`."
- ;;
- success:success:*)
- echo "### APK publication incomplete"
- echo
- echo "Compilation and unit tests passed, but APK publication did not complete. See [the run]($RUN_URL)."
- ;;
- success:failure:*)
- echo "### ERROR: Unit tests failed"
- echo
- echo "The APK compiled, but unit tests failed. No installable artifact was published."
- echo
- if [ -n "$TEST_DIAGNOSTICS_URL" ]; then
- echo "The [unit-test-results]($TEST_DIAGNOSTICS_URL) artifact contains the test log and any generated reports."
- else
- echo "The test diagnostics upload did not complete. See [the test log]($RUN_URL)."
- fi
- ;;
- success:*)
- echo "### Build incomplete"
- echo
- echo "The APK compiled, but unit tests did not complete successfully. See [the run]($RUN_URL)."
- ;;
- failure:*)
- echo "### ERROR: Build failed"
- echo
- echo "The compiler's errors ([full log]($RUN_URL)):"
- echo
- echo '```'
- { grep -E '^e: |^w: .*error|error:|CMake Error|fatal error|ninja: error|FAILED|What went wrong|Execution failed for task|Unresolved reference|Type mismatch|Unresolved' /tmp/build.log 2>/dev/null \
- | sed -e 's#file:///home/runner/work/[^/]*/[^/]*/##' -e 's#/home/runner/work/[^/]*/[^/]*/##' \
- | grep -v '^w: ' | awk '!seen[$0]++' | head -80; } || true
- echo '```'
- echo
- echo "What went wrong (Gradle)"
- echo
- echo '```'
- awk '/^\* What went wrong/{p=1} /^\* Try:/{p=0} p{print}' /tmp/build.log 2>/dev/null | head -60
- echo '```'
- echo ""
- ;;
- skipped:*|cancelled:*)
- echo "### Not built"
- echo
- echo "The build did not run (see above, or [the run]($RUN_URL))."
- ;;
- esac
- echo
- } > /tmp/pr-report.md
- cat /tmp/pr-report.md >> "$GITHUB_STEP_SUMMARY"
- ID=$(gh api "repos/${GITHUB_REPOSITORY}/issues/${PR}/comments" --paginate --jq ".[] | select(.body | startswith(\"$MARK\")) | .id" | head -1 || true)
- if [ -n "$ID" ]; then
- gh api -X PATCH "repos/${GITHUB_REPOSITORY}/issues/comments/${ID}" -F body=@/tmp/pr-report.md >/dev/null
- else
- gh api -X POST "repos/${GITHUB_REPOSITORY}/issues/${PR}/comments" -F body=@/tmp/pr-report.md >/dev/null
- fi
+ set -euo pipefail
+ git fetch --no-tags origin "$BUILD_BASE_SHA"
+ git config user.name "ci"
+ git config user.email "ci@users.noreply.github.com"
+ git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true
+ git merge --no-ff --no-edit FETCH_HEAD
+ - name: Verify backend and test source match
+ env:
+ XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
+ run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
+ - name: Rust toolchain
+ id: rust
+ run: echo "rustc=$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
+ - name: Cache cargo registry and the host test target
+ uses: actions/cache@v4
+ with:
+ path: |
+ ~/.cargo/registry/index
+ ~/.cargo/registry/cache
+ ~/.cargo/git/db
+ app/src/main/rust/stores/target
+ key: stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-${{ hashFiles('app/src/main/rust/stores/src/**', 'app/src/main/rust/stores/Cargo.toml', 'app/src/main/rust/stores/build.rs') }}
+ restore-keys: |
+ stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-
+ stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}-
+ - name: Store engines host unit tests
+ timeout-minutes: 10
+ continue-on-error: true
+ run: |
+ set -o pipefail
+ cd app/src/main/rust/stores
+ cargo test --locked 2>&1 | tail -60
+
+ python-tests:
+ name: Python and native regression tests
+ needs: source
+ if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 15
+ 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:
+ BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
+ run: |
+ set -euo pipefail
+ git fetch --no-tags origin "$BUILD_BASE_SHA"
+ git config user.name "ci"
+ git config user.email "ci@users.noreply.github.com"
+ git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true
+ git merge --no-ff --no-edit FETCH_HEAD
+ - name: Verify backend and test source match
+ env:
+ XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
+ run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
+ - name: Install Python test dependencies
+ timeout-minutes: 7
+ run: bash tools/ci/install-ubuntu-packages.sh python3-yaml gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user libvulkan-dev mesa-vulkan-drivers
+ - name: Resolve the pinned Android NDK
+ run: bash tools/ci/resolve-ndk.sh
+
+ - name: Check Quest tracking IPC
+ run: |
+ set -euo pipefail
+ NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
+ VK_INCLUDE=$(ls -d "$NDK"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1)
+ mkdir -p build/vr/include
+ cp -R "$VK_INCLUDE/vulkan" build/vr/include/
+ if [ -d "$VK_INCLUDE/vk_video" ]; then cp -R "$VK_INCLUDE/vk_video" build/vr/include/; fi
+ g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_tracking.cpp -o /tmp/test-xr-tracking
+ /tmp/test-xr-tracking
+ g++ -std=c++17 -Wall -Wextra -Werror tools/vr/tests/test_xr_touch.cpp -o /tmp/test-xr-touch
+ /tmp/test-xr-touch
+ g++ -std=c++17 -Wall -Wextra -Werror tools/vr/tests/test_pad_controller_config.cpp -o /tmp/test-pad-controller-config
+ /tmp/test-pad-controller-config
+ g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_vsync.cpp -o /tmp/test-xr-vsync
+ /tmp/test-xr-vsync
+ g++ -std=c++17 -Wall -Wextra -Werror -pthread tools/vr/tests/test_xr_frames.cpp -o /tmp/test-xr-frames
+ /tmp/test-xr-frames
+ cc -Itools/vr/third_party/wayland -c tools/vr/src/wayland_client_stub.c -o /tmp/test-wayland-stub.o
+ cc -Itools/vr/third_party/wayland -c app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c -o /tmp/test-xdg-shell.o
+ g++ -std=c++17 -Wall -Wextra -Werror -Wno-unused-parameter -Wno-missing-field-initializers -pthread -Ibuild/vr/include \
+ -Itools/vr/third_party/wayland -Iapp/src/main/cpp/waylandcomp/generated \
+ tools/vr/tests/test_presenter_shutdown.cpp tools/vr/src/presenter.cpp /tmp/test-wayland-stub.o /tmp/test-xdg-shell.o \
+ -ldl -o /tmp/test-presenter-shutdown
+ timeout 10 /tmp/test-presenter-shutdown
+
+ - name: Steam import and game environment tests
+ run: bash tools/ci/run-python-tests.sh
+
+ checks:
+ name: Compile and test APK
+ needs: [build, python-tests]
+ if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - name: Require compilation and every test job
+ env:
+ BUILD_RESULT: ${{ needs.build.result }}
+ PYTHON_RESULT: ${{ needs.python-tests.result }}
+ run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success
sign:
- needs: build
+ needs: [build, checks]
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
permissions:
contents: read
@@ -774,7 +820,7 @@ jobs:
secrets: inherit
packs:
- needs: build
+ needs: [build, checks]
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
permissions:
contents: read
@@ -794,6 +840,10 @@ jobs:
CI_REPO: Droid-Deck/DroidDeck-CI
KEEP: 10
steps:
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
- uses: actions/download-artifact@v4
with:
pattern: droiddeck-signed-*
@@ -811,72 +861,13 @@ jobs:
- name: Describe the change
env:
GH_TOKEN: ${{ github.token }}
- run: |
- set -euo pipefail
- pr=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls" \
- --jq '[.[] | select(.merged_at != null and .base.ref == "main")] | first // empty')
- if [ -n "$pr" ]; then
- number=$(jq -r .number <<<"$pr")
- title=$(jq -r .title <<<"$pr")
- merged=$(jq -r '.merged_at[:10]' <<<"$pr")
- summary=$(jq -r '.body // ""' <<<"$pr" | tr -d '\r' | { grep -v '^🤖' || true; } |
- awk '!p && /^#/ { next } NF { p = 1; print; next } p { exit }' | head -n 6 | cut -c1-400)
- {
- echo "**Merged to main** - [PR #$number]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$number): $title (merged $merged)"
- if [ -n "$summary" ]; then
- echo
- echo "$summary"
- fi
- } > notes-head.md
- else
- subject=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA" --jq '.commit.message | split("\n")[0]')
- echo "**Pushed to main** without a PR - $subject" > notes-head.md
- fi
- cat notes-head.md
+ run: bash tools/release/describe-build.sh
- name: Publish to DroidDeck-CI
id: publish
env:
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
- run: |
- set -euo pipefail
- tag=main-${GITHUB_SHA::7}
- cat signed/SHA256SUMS-*.txt > signed/SHA256SUMS.txt
- rm signed/SHA256SUMS-*.txt
- notes="$(cat notes-head.md)
-
- Signed build of $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA - in main, not yet in a DroidDeck release; for testing.
- Commit: $GITHUB_SHA
- VersionCode: $(sed -n 's/^ *versionCode \([0-9][0-9]*\)$/\1/p' app/build.gradle)
- Each apk installs over a DroidDeck release and keeps its data. \`standard\` is the normal app; the others are the same app under another package name, installed beside it.
-
- SHA-256:
- \`\`\`
- $(cat signed/SHA256SUMS.txt)
- \`\`\`"
- gh release delete "$tag" -R "$CI_REPO" --yes --cleanup-tag 2>/dev/null || true
- gh release create "$tag" -R "$CI_REPO" --target main --prerelease \
- --title "main ${GITHUB_SHA::7}" --notes "$notes" signed/*
- gh release list -R "$CI_REPO" -L 200 --json tagName,publishedAt \
- --jq '[.[] | select(.tagName | startswith("main-"))] | sort_by(.publishedAt) | reverse | .['"$KEEP"':][] | .tagName' |
- while IFS= read -r old; do
- if [ "$old" = "$tag" ]; then
- continue
- fi
- if ! gh release delete "$old" -R "$CI_REPO" --yes --cleanup-tag 2>/dev/null; then
- if gh release view "$old" -R "$CI_REPO" >/dev/null 2>&1; then
- echo "::error::Could not delete old release $old"
- exit 1
- fi
- fi
- done
- published=$(gh release view "$tag" -R "$CI_REPO" --json tagName,assets)
- jq -e --arg tag "$tag" '.tagName == $tag and (.assets | length) > 0' <<< "$published" >/dev/null
- url="$GITHUB_SERVER_URL/$CI_REPO/releases/tag/$tag"
- apk=$(cd signed && ls DroidDeck-*.apk | awk 'length(a) == 0 || length($0) < length(a) { a = $0 } END { print a }')
- echo "release=$url" >> "$GITHUB_OUTPUT"
- echo "apk=$GITHUB_SERVER_URL/$CI_REPO/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
- echo "Published $url"
+ run: bash tools/release/publish-ci.sh
- name: Post the Preview build to Discord
env:
@@ -884,26 +875,8 @@ jobs:
GH_TOKEN: ${{ github.token }}
RELEASE: ${{ steps.publish.outputs.release }}
APK: ${{ steps.publish.outputs.apk }}
- run: |
- set -euo pipefail
- if [ -z "$WEBHOOK" ]; then
- echo "::notice::No DISCORD_BUILDS_WEBHOOK secret; nothing posted"
- exit 0
- fi
- commit=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA")
- subject=$(jq -r '.commit.message | split("\n")[0]' <<<"$commit")
- title=$(jq -r '.commit.message | split("\n") | map(select(length > 0)) | .[1] // ""' <<<"$commit")
- pr=$(sed -n 's/^Merge pull request #\([0-9]*\).*/\1/p' <<<"$subject")
- if [ -n "$pr" ]; then
- what="[#$pr]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$pr): ${title:-$subject}"
- else
- what="[\`${GITHUB_SHA::7}\`]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA): $subject"
- fi
- get=$(printf 'Download: [standard APK](<%s>) · [all variants](<%s>)' "$APK" "$RELEASE")
- content=$(printf '**New signed Preview build** `main-%s`\n%s\nIn the app: **Updates → Preview**\n%s' "${GITHUB_SHA::7}" "$what" "$get")
- jq -n --arg content "$content" '{content: $content, allowed_mentions: {parse: []}}' |
- curl -fsS -H 'Content-Type: application/json' -d @- "$WEBHOOK" -o /dev/null
- echo "Posted: $content"
+ run: bash tools/release/announce-preview.sh
+
catalog:
needs: announce
diff --git a/.github/workflows/pr-release-publish.yml b/.github/workflows/pr-release-publish.yml
index dab96e015..85f972a1b 100644
--- a/.github/workflows/pr-release-publish.yml
+++ b/.github/workflows/pr-release-publish.yml
@@ -8,6 +8,10 @@ on:
description: Open pull request number
required: true
type: string
+ automatic_build_run_id:
+ description: Completed build run for automatic publishing
+ required: false
+ type: string
pull_request_target:
types: [labeled]
branches: [main]
@@ -27,16 +31,47 @@ concurrency:
queue: max
jobs:
+ dispatch-fork-builds:
+ if: >-
+ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' &&
+ github.event.workflow_run.conclusion == 'success' &&
+ github.event.workflow_run.head_repository.full_name != github.repository
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ permissions:
+ actions: write
+ pull-requests: read
+ steps:
+ - name: Find fork PRs for the completed build
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RUN_ID: ${{ github.event.workflow_run.id }}
+ RUN_SHA: ${{ github.event.workflow_run.head_sha }}
+ RUN_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
+ RUN_BRANCH: ${{ github.event.workflow_run.head_branch }}
+ run: |
+ set -euo pipefail
+ owner=${RUN_REPO%%/*}
+ gh api --paginate --slurp -X GET "repos/$GITHUB_REPOSITORY/pulls" \
+ -f state=open -f base=main -f "head=$owner:$RUN_BRANCH" -f per_page=100 |
+ jq -r --arg sha "$RUN_SHA" --arg repo "$RUN_REPO" --arg branch "$RUN_BRANCH" '
+ .[][] | select(.head.sha == $sha and .head.repo.full_name == $repo and .head.ref == $branch) | .number' |
+ while IFS= read -r number; do
+ gh workflow run pr-release-publish.yml -R "$GITHUB_REPOSITORY" --ref main \
+ -f "pr_number=$number" -f "automatic_build_run_id=$RUN_ID"
+ done
+
authorize:
if: >-
(github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') ||
- (github.event_name == 'pull_request_target' && github.event.label.name == 'publish-test') ||
+ (github.event_name == 'pull_request_target' &&
+ (github.event.action != 'labeled' || github.event.label.name == 'publish-test')) ||
(github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.head_repository.full_name == github.repository &&
github.event.workflow_run.pull_requests[0] != null)
runs-on: ubuntu-24.04
- timeout-minutes: 45
+ timeout-minutes: 150
outputs:
pr_number: ${{ steps.gate.outputs.pr_number }}
run_id: ${{ steps.gate.outputs.run_id }}
@@ -50,6 +85,7 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
+ fetch-depth: 0
persist-credentials: false
- name: The packages a signed build ships as
id: variants
@@ -61,22 +97,14 @@ jobs:
EVENT_NAME: ${{ github.event_name }}
REQUESTER: ${{ github.actor }}
PR_NUMBER: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }}
+ ACTION: ${{ github.event.action }}
BUILT_SHA: ${{ github.event.workflow_run.head_sha }}
+ AUTO_RUN: ${{ inputs.automatic_build_run_id }}
run: |
set -euo pipefail
[[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]] || { echo "::error::Invalid PR number '$PR_NUMBER'"; exit 1; }
skip() { echo "::notice::Not publishing PR #$PR_NUMBER: $1"; echo "skip=true" >> "$GITHUB_OUTPUT"; exit 0; }
- if [ "$EVENT_NAME" = workflow_run ]; then
- echo "automatic=true" >> "$GITHUB_OUTPUT"
- pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
- [ "$(jq -r .state <<<"$pr")" = open ] || skip "it is not open"
- [ "$(jq -r .draft <<<"$pr")" = false ] || skip "it is a draft"
- [ "$(jq -r .base.ref <<<"$pr")" = main ] || skip "it does not target main"
- [ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork"
- jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
- [ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building"
- fi
- if [ "$EVENT_NAME" = pull_request_target ]; then
+ if [ "$EVENT_NAME" = pull_request_target ] && [ "$ACTION" = labeled ]; then
permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$REQUESTER/permission" --jq .permission)
case "$permission" in
admin|maintain|write) ;;
@@ -85,29 +113,59 @@ jobs:
fi
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null ||
- { echo "::error::PR #$PR_NUMBER must be open, ready for review, and target main"; exit 1; }
+ skip "it must be open, ready for review, and target main"
+ if [ "$EVENT_NAME" = workflow_run ]; then
+ [ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork"
+ [ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building"
+ jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
+ echo "automatic=true" >> "$GITHUB_OUTPUT"
+ elif [ "$EVENT_NAME" = workflow_dispatch ] && [ -n "$AUTO_RUN" ]; then
+ [[ "$AUTO_RUN" =~ ^[1-9][0-9]*$ ]] || { echo '::error::Invalid automatic build run ID'; exit 1; }
+ jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
+ git fetch --no-tags origin main
+ opener=$(jq -r .user.login <<<"$pr")
+ git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$opener" || skip "PR opener @$opener is not trusted for automatic signing"
+ echo "automatic=true" >> "$GITHUB_OUTPUT"
+ fi
head=$(jq -r '.head.sha' <<<"$pr")
base=$(jq -r '.base.sha' <<<"$pr")
run_id=
- for attempt in $(seq 1 60); do
- latest=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml \
- --event pull_request --commit "$head" \
- --json databaseId,headSha,status,conclusion,createdAt,attempt -L 100 |
- jq -c --arg head "$head" '[.[] | select(.headSha == $head)] |
- sort_by([.createdAt, .attempt]) | last // empty')
+ for attempt in $(seq 1 240); do
+ latest=$(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/build.yml/runs?event=pull_request&head_sha=$head&per_page=100" |
+ jq -c --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
+ [.workflow_runs[] | select(.head_sha == $head and .head_repository.full_name == $repo and .head_branch == $ref)] |
+ sort_by([.created_at, .run_attempt]) | last // empty')
+ if [[ -z "$latest" && "$attempt" == 1 ]]; then
+ git fetch --no-tags origin main
+ git fetch --no-tags origin "refs/pull/$PR_NUMBER/head"
+ git diff --no-renames --name-only -z "$base...FETCH_HEAD" > "$RUNNER_TEMP/pr-changed-paths"
+ excluded=true
+ while IFS= read -r -d '' path; do
+ case "$path" in
+ *.md|LICENSE|.gitignore) ;;
+ *) excluded=false; break ;;
+ esac
+ done < "$RUNNER_TEMP/pr-changed-paths"
+ [ "$excluded" = false ] || skip "its changes do not trigger the APK build"
+ fi
if [[ -n "$latest" && $(jq -r .status <<<"$latest") == completed ]]; then
conclusion=$(jq -r .conclusion <<<"$latest")
- [[ "$conclusion" == success ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; }
- run_id=$(jq -r .databaseId <<<"$latest")
- break
+ if [[ "$conclusion" == success ]]; then
+ run_id=$(jq -r .id <<<"$latest")
+ if [ -n "$AUTO_RUN" ] && [ "$run_id" != "$AUTO_RUN" ]; then
+ skip "a newer build exists"
+ fi
+ break
+ fi
+ [[ "$conclusion" == action_required ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; }
fi
status=not-started
[[ -z "$latest" ]] || status=$(jq -r .status <<<"$latest")
echo "Waiting for the PR build of ${head:0:7} to finish ($status)"
sleep 30
done
- [[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 30 minutes'; exit 1; }
+ [[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 120 minutes'; exit 1; }
run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id")
jq -e --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
.event == "pull_request" and .head_sha == $head and .conclusion == "success" and
@@ -137,6 +195,13 @@ jobs:
.head.sha == $head and .base.sha == $base
' <<<"$current" >/dev/null ||
{ echo "::error::PR #$PR_NUMBER moved on while its build was checked; publish again"; exit 1; }
+ if [ "$EVENT_NAME" = workflow_run ] || { [ "$EVENT_NAME" = workflow_dispatch ] && [ -n "$AUTO_RUN" ]; }; then
+ jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$current" >/dev/null && skip "it is labelled no-test-build"
+ if [ "$EVENT_NAME" = workflow_dispatch ]; then
+ git fetch --no-tags origin main
+ git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$(jq -r .user.login <<<"$current")" || skip "the PR opener is no longer trusted"
+ fi
+ fi
{
echo "pr_number=$PR_NUMBER"
echo "run_id=$run_id"
@@ -271,17 +336,24 @@ jobs:
echo "release=$release" >> "$GITHUB_OUTPUT"
echo "apk=$GITHUB_SERVER_URL/$repo/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
- - name: Whether the PR's branch is in this repo
- id: same-repo
+ - name: Whether the PR opener is trusted
+ id: trusted-opener
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
run: |
- head_repo=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .head.repo.full_name)
- echo "same=$([ "$head_repo" = "$GITHUB_REPOSITORY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
+ pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
+ opener=$(jq -r .user.login <<<"$pr")
+ git fetch --no-tags origin main
+ if [ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] ||
+ git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$opener"; then
+ echo "trusted=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "trusted=false" >> "$GITHUB_OUTPUT"
+ fi
- name: Clear the publish request label
- if: ${{ github.event_name == 'pull_request_target' && steps.publish.outcome == 'success' }}
+ if: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && steps.publish.outcome == 'success' }}
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
@@ -295,12 +367,12 @@ jobs:
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
RELEASE: ${{ steps.publish.outputs.release }}
APK: ${{ steps.publish.outputs.apk }}
- SAME_REPO: ${{ steps.same-repo.outputs.same }}
+ TRUSTED_OPENER: ${{ steps.trusted-opener.outputs.trusted }}
run: |
set -euo pipefail
short=${HEAD_SHA:0:7}
mark=''
- if [ "$SAME_REPO" = true ]; then
+ if [ "$TRUSTED_OPENER" = true ]; then
NEXT='Each green build of a new push is signed and published here on its own. Label the PR `no-test-build` to stop that.'
else
NEXT='Pushes to this PR do not re-sign automatically. After a new green build, a maintainer can add the `publish-test` label again.'
diff --git a/.github/workflows/publish-packs.yml b/.github/workflows/publish-packs.yml
index 580b1c818..de4adb3b2 100644
--- a/.github/workflows/publish-packs.yml
+++ b/.github/workflows/publish-packs.yml
@@ -1,11 +1,5 @@
name: Publish add-on packs
-# The add-on packs (tools/packs/build.sh) a Build APK run made, published to DroidDeck-Components under
-# content-addressed tags (pack--). The APK from that run pins each pack's
-# SHA-256 and downloads it from that tag. A tag is created once and never replaced.
-# Only main and release builds publish here; a PR test build attaches the packs main has not published
-# to its pr-N release on DroidDeck-CI (pr-release-publish.yml), which is deleted when the PR closes.
-
on:
workflow_call:
inputs:
@@ -61,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 proot directaudio tracking xbox comet; do
+ for name in proot directaudio tracking xbox comet butler; 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)
diff --git a/.gitignore b/.gitignore
index e5bdbfffc..bfeee7641 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,6 +13,8 @@ app/src/main/jniLibs/arm64-v8a/libproot.so
app/src/main/jniLibs/arm64-v8a/.proot-inputs
app/src/main/jniLibs/arm64-v8a/.proot-outputs
app/src/main/jniLibs/arm64-v8a/libproot-loader.so
+app/src/main/jniLibs/arm64-v8a/libsyncthingnative.so
+app/src/main/jniLibs/arm64-v8a/.syncthing-inputs
app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so
app/src/main/rust/stores/target/
app/src/main/assets/droiddeck-esync/
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 000000000..50f7a038b
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "tools/syncthing/syncthing-android"]
+ path = tools/syncthing/syncthing-android
+ url = https://github.com/researchxxl/syncthing-android
diff --git a/LICENSE b/LICENSE
index 5ae980bfc..3ffac1c5e 100644
--- a/LICENSE
+++ b/LICENSE
@@ -631,8 +631,8 @@ to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
- Pluvia is an unofficial Steam client app for Android
- Copyright (C) 2024 Oxters Wyzgowski
+ DroidDeck brings the SteamOS experience to Android
+ Copyright (C) 2026 DroidDeck contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -652,7 +652,7 @@ Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
- Pluvia Copyright (C) 2024 Oxters Wyzgowski
+ DroidDeck Copyright (C) 2026 DroidDeck contributors
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
diff --git a/README.md b/README.md
index fb86fa653..12494cad1 100644
--- a/README.md
+++ b/README.md
@@ -5,54 +5,155 @@
-DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Adreno handheld, with Windows games through Valve's ARM64 Proton.
+DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linux desktop, integration with GOG, Epic Games, Xbox, and other storefronts, Steam VR, and more!
-
+
100% open source. No ads. No telemetry. No source withheld.
-
+
+
+
+
-> Note: DroidDeck does not have a stand-alone website. Do not click on any download links from websites claiming to be the DroidDeck team.
+
+
+
-## Requirements and install
+
+
+
+
-Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Adreno 6xx is experimental: DirectX 11 uses DXVK 2 and may run, and DirectX 12 games can still crash. Mali, Xclipse, PowerVR, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; with additional options to install Appimages and set up scripts. **Stores** (Setup › Stores › "Show Stores in the rail") signs in to GOG, Epic Games and Amazon Games and downloads games into the Games storage. Epic keeps its direct API install path. Opening Epic Stores prepares Epic’s official Linux launcher preview. When installed, Epic games launched from DroidDeck use that client, and games installed in the client are imported into DroidDeck’s library and shortcuts. The x86-64 client runs through FEX on ARM and DroidDeck retains its Proton hooks; this preview and ARM setup are outside Epic’s listed Linux support. The cog on a store’s chip row sets its opening tab and download speed tier.
+
-On Android 14 and newer, before Steam launches, you must turn on **Disable child process restrictions** in Developer options. If this option is not available in developer settings (Android 12 and 13 devices), first launch of Steam will present a "Fix it for me" button, which will help automate the setup process.
+> DroidDeck has no website. Only download it from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
-## Smart glasses
+
+
+
+
+
+
-Use **Setup → Smart glasses** for app-wide virtual-screen settings across DroidDeck menus, launchers, desktop sessions, and games. Supported VITURE, RayNeo, XREAL, and Rokid connections provide 3DoF; Luma Ultra adds optional experimental 6DoF and stereo-assisted hand/Joy-Con tracking. Model support and SDK requirements differ: see the [smart-glasses support matrix](docs/smart-glasses-support.md) for supported devices, controls, setup, and limitations.
+## Install
-## Community
+1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx is experimental. Mali, Xclipse, PowerVR and Adreno 710 are 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.6.7/DroidDeck-0.6.7.apk), install the Linux runtime, press **Play** and sign in to Steam.
+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.
-Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the zip from **Share logs** (Setup, or the session drawer) so the logs come with it.
+Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
+
+Help, Preview builds and device reports are on [Discord](https://discord.gg/JRGAvawjsm). For bugs, post in **#bug-reports** with the zip from **Share logs**.
## Build
-Run `tools/build_local.sh` with Docker, Java 17, the Android SDK/NDK, Rust through rustup, GitHub CLI, Python 3, and `zstd` installed. It prepares the same native libraries, pinned components and audio sinks as CI, then checks the APK's assets, JNI exports and dependencies. The APK is at `app/build/outputs/apk/release/app-release.apk`. Set `DROIDDECK_PA13_SOURCE_DIR` to an existing PulseAudio 13.0 source directory to skip downloading it. Set `DROIDDECK_SIGNING_ENV` to a signing environment file to install over a release build; relative keystore paths resolve beside that file. To install on an attached device, run `tools/deploy_local.sh`.
+Needs Docker, Java 21, the Android SDK and NDK, Rust via rustup, GitHub CLI, Python 3 and `zstd`.
-After preparation, ordinary `./gradlew :app:assembleRelease` builds can reuse the verified inputs. If native sources, component pins or staged files change, packaging stops with instructions to rerun the helper. Generated audio stays under `app/build/`; the tracked base bundle is never modified. `./gradlew -PskipRust=true :app:testDebugUnitTest` needs no native preparation. For an APK without store engines, use `DROIDDECK_SKIP_RUST=1 tools/build_local.sh`; it omits cached engine libraries too.
+```bash
+tools/build_local.sh
+```
-For the prepared Windows checkout, run `./tools/run_windows.ps1` (optionally with `-Serial `), or select **DroidDeck XR** in Android Studio and run the **app** module on the connected phone. Machine-specific options live in the ignored `local.properties`: `droiddeck.python` selects a Python executable, `droiddeck.skipRust=true` omits the optional store download engines, and `droiddeck.debugApplicationIdSuffix=.xr` installs **DroidDeck XR Dev** alongside the signed release. The development app has its own runtime and Steam login. The local Java selection is in `.gradle/config.properties`.
+The APK lands in `app/build/outputs/apk/release/`. Install it with `tools/deploy_local.sh`. After the first run, `./gradlew :app:assembleRelease` reuses the prepared inputs. Unit tests run with `./gradlew -PskipRust=true :app:testDebugUnitTest`, and the helper and preload suite with `bash tools/test_local.sh`.
-`python tools/prepare_windows_runtime.py` restores this checkout's audited runtime inputs from the pinned CI APK, three locally rebuilt preload libraries, and the checksum-pinned Gamescope archive in `build/windows-setup/`. Start Docker Desktop's Linux engine first: preparation now rebuilds DroidDeck's ARM64 VR driver and Vulkan layer from current source and runs their native regression tests. The compiler image is built automatically on first use. Vulkan headers come from the NDK beside `--llvm-strip`, or from an explicit `--vk-include ` directory.
-
-To reuse that build, pass `--rebuilt-vr build/windows-setup/vr`. Preparation verifies its `vr-build.json` against the current Git revision, source files, Vulkan headers, output checksums, and ARM64 architecture; missing or stale builds fail instead of falling back to the donor's VR libraries. The script checks the actual donor CI merge tree, still rejects unrelated unaudited runtime changes, and records component provenance in `app/build/windows-runtime-provenance.json`. Preserve these ignored preparation files when rebuilding locally; `clean` removes the prepared assets and their verification manifest.
-
-Run the helper and preload regression suite with `bash tools/test_local.sh`. On macOS it runs in Linux through Docker, matching the helpers' runtime and CI instead of compiling Linux preloads against macOS headers.
+On Windows, see `tools/run_windows.ps1` and `tools/prepare_windows_runtime.py`.
## Limits
-Compatibility and performance vary by device; hardware validation is limited. Desktop compositing uses software rendering. Firefox sandboxing is reduced under proot. Logs are kept app-private (`files/logs/`, the last 30 sessions); **Share logs** packs the newest session, with the stores and tool logs, into one scrubbed zip.
+Compatibility and performance vary by device. Desktop compositing is software rendered, and Firefox sandboxing is reduced under proot.
## Credits and licence
-GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc//mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc//status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
+DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. VITURE, RayNeo, XREAL, Rokid, REDMAGIC, Nintendo Switch and Joy-Con are trademarks of their owners. This project is not affiliated with any of them.
-XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
+
+Runtime, Wine and Proton
-Joy-Con VR controllers port the arm model of Google's [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk) (Apache-2.0), adapt the hand skeleton of Valve's [OpenVR](https://github.com/ValveSoftware/openvr) `handskeletonsimulation` sample (BSD-3-Clause), which follows Moshi Turner's hand simulation in [Monado](https://gitlab.freedesktop.org/monado/monado), and use the Index controller offsets from Monado's `vive_poses.c` (BSL-1.0). Joy-Con behaviour was researched in Linux's [hid-nintendo](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-nintendo.c) driver by Daniel J. Ogorchock, [@dekuNukem](https://github.com/dekuNukem)'s [Nintendo_Switch_Reverse_Engineering](https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering), [SDL](https://github.com/libsdl-org/SDL) and the Android Open Source Project, and checked against [ALVR](https://github.com/alvr-org/ALVR), [OpenComposite](https://gitlab.com/znixian/OpenOVR), [PSMoveSteamVRBridge](https://github.com/HipsterSloth/PSMoveSteamVRBridge), [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr), [@krnelpan1c](https://github.com/krnelpan1c)'s [Daydream-Controller-SteamVR](https://github.com/krnelpan1c/Daydream-Controller-SteamVR), [@yoyobuae](https://github.com/yoyobuae)'s [joyconvr](https://github.com/yoyobuae/joyconvr), [Moonlight](https://github.com/moonlight-stream/moonlight-android) and [Dolphin](https://github.com/dolphin-emu/dolphin); see [docs/third-party/joycon](docs/third-party/joycon/README.md). Nintendo Switch and Joy-Con are trademarks of Nintendo; this project is not affiliated with Nintendo.
+- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
+- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
+- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT). FEX's code disk cache was checked in its source.
+- 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.
+- 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//mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
+- Wine write watches use userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later). libblsession supplies the arm64 syscall number and answers `PAGEMAP_SCAN` from `/proc/self/pagemap`.
+- libblsession 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//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.
+- Games use [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's per render pass memory choice. The Steam client keeps `TU_DEBUG=sysmem`.
+- Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose `311210.py` and `570940.py` fail under ARM64 Proton.
+- [ReSkate](https://github.com/Dingo-Shenanigans/ReSkate) (GPL-3.0) by Dingo Shenanigans uses the launch option from its README and D3D12 feature level 12_1.
+- The arm64 client's sign in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest).
-Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision library with its Pose Landmarker (Lite) model, BlazePose GHUM 3D, and its Hand Landmarker model (all Apache-2.0), on frames from AndroidX [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) (Apache-2.0); MediaPipe's usage reports are switched off. The design was checked against [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr) camera app (MIT), and the short Joy-Con movements follow the accelerometer mode of the [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk)'s arm model, Eric Foxlin's zero-velocity updates and Frosio, Pedersini and Borghese's accelerometer autocalibration, and the camera and Joy-Con are joined by a Kalman filter (R. E. Kalman, 1960). Bare camera hands take their gestures after [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, with distances checked on photos from the [HaGRID](https://github.com/hukenovs/hagrid) gesture set (CC BY-SA 4.0, not included), fit the palm with Horn's quaternion method (1987) and smooth it with the 1€ filter (Casiez, Roussel and Vogel, 2012); the white glove model follows Valve's OpenVR render model reference and Index controller poses, is meshed with surface nets (Gibson, 1998; Mikola Lysenko) and blends and shades it with Inigo Quilez's smooth minimum and distance-field ambient occlusion, porting his polygon distance (MIT); see [docs/third-party/handtracking](docs/third-party/handtracking/README.md).
+
-The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead.
+
+Stores
+
+- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them.
+- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
+- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
+- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
+- Xbox games load [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) modules (LGPL-2.1-or-later), including `wintypes.dll`. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
+- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
+- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
+- The Store uses [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1) through DroidDeck's own bubblewrap shim. Chromium and Electron apps start directly, since [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause) always uses Flatpak's spawn portal.
+- Folder sync runs [Syncthing](https://github.com/syncthing/syncthing) (MPL-2.0), built from [@researchxxl](https://github.com/researchxxl)'s [syncthing-android](https://github.com/researchxxl/syncthing-android) fork (MPL-2.0).
+
+
+
+
+Audio, video and HUD
+
+- Steam audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink`.
+- The DroidDeck HUD is [@The412Banner](https://github.com/The412Banner)'s [FusionHUD](https://github.com/The412Banner/FusionHUD) (GPL-3.0 with an attribution term). Its readings match Valve's [MangoHud](https://github.com/flightlessmango/MangoHud) build (MIT), with frame times from gamescope patch 0125.
+- The HUD's CPU, GPU load, thermal and battery readers come from [@xXJSONDeruloXx](https://github.com/xXJSONDeruloXx)'s work.
+- LSFG frame generation comes from Camille LaVey and the [Eden](https://eden-emu.dev) project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported by [@maxjivi05](https://github.com/maxjivi05). It needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders.
+- Remote Play decodes through Android's MediaCodec or the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) in Steam's runtime. Qualcomm low latency settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0).
+- [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) sockets use the settings in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions.
+
+
+
+
+Desktop
+
+- The KDE pacman repository snapshots [Arch Linux ARM](https://archlinuxarm.org) and installs with [pacman](https://gitlab.archlinux.org/pacman/pacman) (GPL-2.0-or-later).
+- [KWin](https://invent.kde.org/plasma/kwin) (GPL-2.0-or-later) is patched to pass on the scroll data its `wayland_backend.cpp` leaves as a TODO.
+- Read without taking code: [Qt](https://code.qt.io/cgit/qt/qtbase.git)'s `qwaylandinputdevice.cpp` and `qguiapplication.cpp`, [Konsole](https://invent.kde.org/utilities/konsole)'s `TerminalDisplay.cpp`, and [Mesa](https://gitlab.freedesktop.org/mesa/mesa)'s `u_threaded_context.c` and `zink_resource.c`.
+- The Steam Keyboard window rule follows Valve's `steamdeck-kde-presets` with [Bazzite](https://github.com/ublue-os/bazzite)'s `0001-steam-virtual-keyboard.patch`.
+- Steam's Browse buttons open a GTK 3 file chooser via PyGObject (LGPL-2.1-or-later), shown over Steam by [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) through `GetAppIdFromReaper`.
+- The AYN Odin 2 phantom second display was confirmed by [@SapphireRhodonite](https://github.com/SapphireRhodonite)'s [WatermelonDS 0.0.5](https://github.com/SapphireRhodonite/WatermelonDS/releases/tag/0.0.5) notes and [iiSU #363](https://github.com/iisu-network/iiSU/issues/363), without taking their code.
+
+
+
+
+Smart glasses
+
+- Builds on WinNative's VITURE work. Protocol checked against [@wheaney](https://github.com/wheaney)'s [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver), [@badicsalex](https://github.com/badicsalex)'s [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and [go-macos/iokit](https://pkg.go.dev/github.com/go-macos/iokit/viture). The optional VITURE SDK is not included.
+- The VITURE protocol V2 frames adapt [@elasticjava](https://github.com/elasticjava)'s [viture-v2](https://github.com/elasticjava/viture-v2) (MIT) by Holger Bartnick. See `docs/third-party/viture-v2`.
+- RayNeo adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0). See [docs/third-party/rayneo](docs/third-party/rayneo/README.md).
+- XREAL 1S references XRLinuxDriver and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [@rohitsangwan01](https://github.com/rohitsangwan01)'s [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) (MIT) and [@0xcaff](https://github.com/0xcaff)'s [xr-tools](https://github.com/0xcaff/xr-tools).
+- Rokid follows ar-drivers-rs, @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/) and Monado's Rokid driver.
+- REDMAGIC display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube).
+
+
+
+
+VR, Joy-Con and hand tracking
+
+- Joy-Con VR ports the arm model from Google's [GVR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk) (Apache-2.0) and adapts the hand skeleton from Valve's [OpenVR](https://github.com/ValveSoftware/openvr) `handskeletonsimulation` sample (BSD-3-Clause), which follows Moshi Turner's work in Monado. Index offsets come from Monado's `vive_poses.c` (BSL-1.0).
+- Joy-Con research: Linux's [hid-nintendo](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-nintendo.c) by Daniel J. Ogorchock, [@dekuNukem](https://github.com/dekuNukem)'s [Nintendo_Switch_Reverse_Engineering](https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering), [SDL](https://github.com/libsdl-org/SDL) and AOSP. Checked against [ALVR](https://github.com/alvr-org/ALVR), [OpenComposite](https://gitlab.com/znixian/OpenOVR), [PSMoveSteamVRBridge](https://github.com/HipsterSloth/PSMoveSteamVRBridge), [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr), [@krnelpan1c](https://github.com/krnelpan1c)'s [Daydream-Controller-SteamVR](https://github.com/krnelpan1c/Daydream-Controller-SteamVR), [@yoyobuae](https://github.com/yoyobuae)'s [joyconvr](https://github.com/yoyobuae/joyconvr), [Moonlight](https://github.com/moonlight-stream/moonlight-android) and [Dolphin](https://github.com/dolphin-emu/dolphin). See [docs/third-party/joycon](docs/third-party/joycon/README.md).
+- Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Pose Landmarker (Lite), BlazePose GHUM 3D and Hand Landmarker (Apache-2.0) on [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) frames (Apache-2.0), with usage reports off. Checked against JoyConVr's camera app (MIT).
+- Tracking math: the GVR arm model's accelerometer mode, Eric Foxlin's zero velocity updates, Frosio, Pedersini and Borghese's accelerometer autocalibration, a Kalman filter (Kalman, 1960), Horn's quaternion method (1987) and the 1€ filter (Casiez, Roussel and Vogel, 2012).
+- Gestures follow [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, tuned on [HaGRID](https://github.com/hukenovs/hagrid) photos (CC BY-SA 4.0, not included).
+- The glove model follows OpenVR's render model reference, is meshed with surface nets (Gibson, 1998; Mikola Lysenko), and uses Inigo Quilez's smooth minimum, distance field ambient occlusion and polygon distance (MIT). See [docs/third-party/handtracking](docs/third-party/handtracking/README.md).
+
+
+
+## Star history
+
+
+
+
+
+
+
diff --git a/app/build.gradle b/app/build.gradle
index 4bc1806c2..0d94314d3 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -1,10 +1,8 @@
plugins {
id 'com.android.application'
}
-apply plugin: 'kotlin-android'
apply plugin: 'org.jetbrains.kotlin.plugin.compose'
-// Machine-specific tooling and optional CI-prepared inputs stay out of version control.
def localBuildOptions = new Properties()
def localBuildOptionsFile = rootProject.layout.projectDirectory.file('local.properties')
if (localBuildOptionsFile.asFile.exists()) {
@@ -78,19 +76,29 @@ def escapedBuildLabel = buildLabel.replace('\\', '\\\\').replace('"', '\\"')
def sourceCommit = providers.environmentVariable('DROIDDECK_SOURCE_COMMIT').getOrNull()
?: providers.environmentVariable('GITHUB_SHA').getOrNull() ?: gitValue(['rev-parse', 'HEAD']) ?: ''
def prNumber = (providers.environmentVariable('DROIDDECK_PR_NUMBER').getOrNull() ?: '0').with { it.isInteger() ? it : '0' }
+def prTitle = providers.environmentVariable('DROIDDECK_PR_TITLE').getOrNull() ?: ''
+def buildBranch = providers.environmentVariable('GITHUB_HEAD_REF').getOrNull()?.trim()
+ ?: gitValue(['branch', '--show-current']) ?: ''
+def escapeJava = { String value -> value.replace('\\', '\\\\').replace('"', '\\"').replace('\n', ' ').replace('\r', ' ') }
def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true'
def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim()
-def commitTime = (gitValue(['show', '-s', '--format=%ct', 'HEAD']) ?: '0').with { it.isLong() ? it : '0' }
+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()
.findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
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 = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'].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'].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 (name == 'proot' && prootPackPin.PROOT_PACK_SHA256) {
+ return [(name): [sha256: prootPackPin.PROOT_PACK_SHA256, size: (prootPackPin.PROOT_PACK_SIZE ?: '0') as long]]
+ }
return [(name): [sha256: '', size: 0L]]
}
def digest = java.security.MessageDigest.getInstance('SHA-256')
@@ -115,18 +123,20 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
android {
namespace 'com.droiddeck.launcher'
- compileSdk 36
+ compileSdk 37
ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724'
defaultConfig {
applicationId "com.droiddeck.launcher"
minSdkVersion 26
- targetSdkVersion 36
- versionCode 15
- versionName "0.6.0"
+ targetSdkVersion 37
+ versionCode 17
+ versionName "0.6.9"
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
buildConfigField "int", "PR_NUMBER", "${prNumber}"
+ buildConfigField "String", "PR_TITLE", "\"${escapeJava(prTitle)}\""
+ buildConfigField "String", "BUILD_BRANCH", "\"${escapeJava(buildBranch)}\""
buildConfigField "boolean", "CI_BUILD", "${ciBuild}"
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
@@ -194,7 +204,6 @@ android {
}
androidResources {
- // aapt's default ignore list, plus the trees shipped as add-on packs (tools/packs).
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*~:droiddeck-xbox:droiddeck-comet:directaudio'
}
@@ -205,8 +214,7 @@ android {
jniLibs {
useLegacyPackaging = true
pickFirsts += ['**/libtermux.so']
- // Shipped in the proot and tracking packs (tools/packs) and run or loaded from there.
- excludes += ['**/libproot.so', '**/libproot-loader.so', '**/libopencv_java4.so', '**/libmediapipe_tasks_jni.so']
+ excludes += ['**/libopencv_java4.so', '**/libmediapipe_tasks_jni.so']
}
}
@@ -220,8 +228,21 @@ android {
unitTests.returnDefaultValues = true
unitTests.includeAndroidResources = true
unitTests.all {
- // Robolectric keeps a sandbox per SDK level the tests ask for; seven no longer fit in Gradle's default 512 MB.
+ if (ciBuild) {
+ outputs.upToDateWhen { false }
+ outputs.doNotCacheIf('CI executes the test suite on every run') { true }
+ }
+ jvmArgs '--add-opens=java.base/java.lang=ALL-UNNAMED',
+ '--add-opens=java.base/java.util=ALL-UNNAMED',
+ '--add-opens=java.base/java.io=ALL-UNNAMED',
+ '--add-opens=java.base/java.net=ALL-UNNAMED',
+ '--add-opens=java.base/java.security=ALL-UNNAMED',
+ '--add-opens=java.base/java.text=ALL-UNNAMED',
+ '--add-opens=java.base/jdk.internal.access=ALL-UNNAMED',
+ '--add-opens=java.desktop/java.awt.font=ALL-UNNAMED',
+ '--add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED'
maxHeapSize = '2g'
+ maxParallelForks = 2
def logTarget = providers.systemProperty('robolectric.logging').orNull
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
}
@@ -231,12 +252,8 @@ android {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
- kotlinOptions {
- jvmTarget = '17'
- }
}
-// Vendor binaries remain in the user's SDK directory; never vendor them into Git.
if (vitureSdkDir) {
android.sourceSets.main.jniLibs.srcDir(new File(vitureSdkDir, 'android'))
def stageVitureNotices = tasks.register('stageVitureNotices', Copy) {
@@ -258,25 +275,44 @@ def runtimeAssetsDir = layout.buildDirectory.dir('runtimeAssets')
def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
dependsOn(stageSessionScripts)
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
+ from(rootProject.file('tools/linuxfs/innoextract'))
from(layout.buildDirectory.dir('prepared-assets'))
into(runtimeAssetsDir)
}
android.sourceSets.main.assets.setSrcDirs([runtimeAssetsDir])
-if (vitureSdkDir) android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('vitureAssets'))
+if (vitureSdkDir) android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('vitureAssets').get().asFile)
if (uvcDir) {
def stageUvcNotices = tasks.register('stageUvcNotices', Copy) {
from(new File(uvcDir, 'licenses'))
into(layout.buildDirectory.dir('uvcAssets/licenses/uvc'))
}
tasks.named('preBuild').configure { dependsOn(stageUvcNotices) }
- android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('uvcAssets'))
+ android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('uvcAssets').get().asFile)
}
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) }
+def stageGogNotices = tasks.register('stageGogNotices', Copy) {
+ from(layout.projectDirectory.dir('src/main/rust/stores/vendor/xdelta3')) { include 'LICENSE', 'README.droiddeck.md' }
+ into(layout.buildDirectory.dir('gogNotices/licenses/xdelta3'))
+}
+android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('gogNotices').get().asFile)
+tasks.named('preBuild').configure { dependsOn(stageGogNotices) }
+
+if (!ciBuild) {
+ def stageLocalPacks = tasks.register('stageLocalPacks', Sync) {
+ from(layout.buildDirectory.dir('packs')) { include '*.tar.zst' }
+ into(layout.buildDirectory.dir('localPackAssets/packs'))
+ }
+ android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('localPackAssets').get().asFile)
+ tasks.named('preBuild').configure { dependsOn(stageLocalPacks) }
+}
+
def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
mustRunAfter(stageSessionScripts, stageRuntimeAssets)
workingDir rootProject.projectDir
- commandLine pythonExecutable, 'tools/release/runtime_inputs.py', 'verify'
+ def allowStale = (project.findProperty('allowStaleRuntime')
+ ?: localBuildOptions.getProperty('droiddeck.allowStaleRuntime', 'false')).toString().toBoolean()
+ commandLine([pythonExecutable, 'tools/release/runtime_inputs.py', 'verify'] + (allowStale ? ['--allow-stale-sources'] : []))
}
tasks.configureEach { task ->
if (task.name in ['packageDebug', 'packageRelease']) task.dependsOn(verifyRuntimeInputs)
@@ -290,6 +326,8 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
description = 'Cross-compiles the store download engines (libdroiddeckstores.so) with cargo-ndk.'
onlyIf { !skipRust }
inputs.dir(rustCrateDir.dir('src'))
+ inputs.dir(rustCrateDir.dir('vendor'))
+ inputs.file(rustCrateDir.file('build.rs'))
inputs.files(rustCrateDir.file('Cargo.toml'), rustCrateDir.file('Cargo.lock'))
inputs.property('ndkVersion', android.ndkVersion)
if (!skipRust) inputs.property('rustToolchain', providers.exec {
@@ -300,7 +338,7 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
workingDir rustCrateDir
def cargoBin = "${System.getProperty('user.home')}/.cargo/bin"
environment 'PATH', "${cargoBin}${File.pathSeparator}${System.getenv('PATH')}"
- environment 'ANDROID_NDK_HOME', android.ndkDirectory.absolutePath
+ environment 'ANDROID_NDK_HOME', androidComponents.sdkComponents.ndkDirectory.get().asFile.absolutePath
environment 'CARGO_TERM_COLOR', 'never'
if (!skipRust) environment 'RUSTC', providers.exec {
commandLine 'rustup', 'which', '--toolchain', 'stable', 'rustc'
@@ -309,7 +347,7 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
'--output-dir', rustJniLibsDir.get().asFile.absolutePath,
'build', '--release', '--locked'
}
-if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir)
+if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir.get().asFile)
tasks.named('preBuild').configure { dependsOn(buildRustStores) }
dependencies {
@@ -318,9 +356,16 @@ dependencies {
implementation 'com.github.luben:zstd-jni:1.5.7-4@aar'
implementation 'org.apache.commons:commons-compress:1.27.1'
implementation 'org.tukaani:xz:1.10'
- implementation platform('androidx.compose:compose-bom:2024.02.00')
+ implementation platform('androidx.compose:compose-bom:2025.02.00')
implementation 'androidx.compose.ui:ui'
- implementation 'androidx.compose.material3:material3'
+ implementation('androidx.compose.material3:material3') {
+ version { strictly '1.2.0' }
+ }
+ constraints {
+ implementation('androidx.compose.material3:material3-android') {
+ version { strictly '1.2.0' }
+ }
+ }
implementation 'androidx.compose.ui:ui-tooling-preview'
debugImplementation 'androidx.compose.ui:ui-tooling'
implementation 'androidx.activity:activity-compose:1.8.2'
@@ -333,12 +378,34 @@ dependencies {
implementation 'androidx.camera:camera-camera2:1.4.2'
implementation 'androidx.camera:camera-lifecycle:1.4.2'
implementation 'androidx.webkit:webkit:1.12.1'
+ implementation 'io.github.webrtc-sdk:android:125.6422.07'
implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") {
exclude group: 'com.google.auto.value', module: 'auto-value'
}
+ implementation 'com.google.zxing:core:3.5.3'
testImplementation 'junit:junit:4.13.2'
- testImplementation 'org.robolectric:robolectric:4.16.1'
+ testImplementation 'org.robolectric:robolectric:4.17'
testImplementation 'androidx.compose.ui:ui-test-junit4'
- testRuntimeOnly 'com.github.luben:zstd-jni:1.5.7-4@jar'
+
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
+ }
+}
+
+androidComponents {
+ beforeVariants(selector().all()) { variant ->
+ variant.enableUnitTest = true
+ }
+}
+
+configurations { hostZstd }
+dependencies { hostZstd 'com.github.luben:zstd-jni:1.5.7-4@jar' }
+androidComponents.onVariants(androidComponents.selector().all()) { variant ->
+ variant.unitTest?.configureTestTask { test ->
+ test.classpath = files(configurations.hostZstd) + test.classpath.filter { !it.name.contains("zstd-jni") }
+ }
}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 002bcfe7d..401f50fce 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -2,7 +2,27 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -12,6 +32,8 @@
+
+
@@ -20,7 +42,10 @@
+
+
+
@@ -37,19 +62,45 @@
android:localeConfig="@xml/locales_config"
android:networkSecurityConfig="@xml/network_security_config"
android:allowBackup="false"
+ android:allowAudioPlaybackCapture="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:hardwareAccelerated="true"
android:largeHeap="true"
android:extractNativeLibs="true"
+ android:pageSizeCompat="enabled"
android:requestLegacyExternalStorage="true"
+ android:enableOnBackInvokedCallback="false"
android:appCategory="game"
android:isGame="true">
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -119,7 +182,7 @@
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity="${applicationId}.home"
- android:screenOrientation="sensorLandscape"
+ android:screenOrientation="user"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
@@ -129,6 +192,18 @@
+
+
+
+
+
+
+
+
+
@@ -155,10 +237,31 @@
android:process=":xboxlogin" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
+
+
+
+
+
+
+
+
+
+
@@ -181,6 +284,26 @@
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/assets/xcloud/player.js b/app/src/main/assets/xcloud/player.js
new file mode 100644
index 000000000..3d3762149
--- /dev/null
+++ b/app/src/main/assets/xcloud/player.js
@@ -0,0 +1,187 @@
+/* DroidDeck Xbox Cloud Gaming player. Includes Greenlight's player (c) UnknownSKL (Jim Kroon), MIT. */
+(()=>{var _=class{_player;_dataChannel;constructor(e){this._player=e,this._dataChannel=this._player._peerConnection.createDataChannel(this.getChannelName(),this.getChannelConfig()),this._dataChannel.onopen=this.onOpen.bind(this),this._dataChannel.onmessage=this.onMessage.bind(this),this._dataChannel.onclosing=this.onClosing.bind(this),this._dataChannel.onclose=this.onClose.bind(this),this._dataChannel.onerror=this.onError.bind(this)}getChannelName(){return"channel"}getChannelConfig(){return{}}onOpen(e){console.log(this.getChannelName(),"Opening channel:",e)}onMessage(e){console.log(this.getChannelName(),"Message channel:",e)}onClosing(e){console.log(this.getChannelName(),"Closing channel:",e)}onClose(e){console.log(this.getChannelName(),"Closed channel:",e)}onError(e){console.log(this.getChannelName(),"Error channel:",e)}send(e){if(this._dataChannel.readyState!=="open"){console.log("["+this.getChannelName()+"] Tried to send data while channel is not open. readyState is:",this._dataChannel.readyState);return}return typeof e=="string"&&(e=new TextEncoder().encode(e)),this._dataChannel.send(e)}getPlayer(){return this._player}destroy(){}};var S=class extends _{_micPermissions="prompt";_micStream;constructor(e){super(e),navigator.permissions.query({name:"microphone"}).then(t=>{this._micPermissions=t.state,t.onchange=()=>{this._micPermissions=t.state}})}getChannelName(){return"chat"}getChannelConfig(){return{ordered:!0,protocol:"chatV1"}}destroy(){}};var v=class r{_player;_index;_physicalGamepadId=-1;_rumbleInterval;_isFocused=!0;_gamepadOverride={buttons:{}};_options={enable_keyboard:!1,enable_gamepad:!0,enable_vibration:!0,keyboard_mapping:{A:"Enter",B:"Backspace",X:"x",Y:"y",DPadUp:"ArrowUp",DPadDown:"ArrowDown",DPadLeft:"ArrowLeft",DPadRight:"ArrowRight",LeftShoulder:"[",RightShoulder:"]",LeftThumb:"l",RightThumb:"r",LeftTrigger:"-",RightTrigger:"=",Menu:"m",View:"v",Nexus:"n"},gamepad_mapping:{A:"0",B:"1",X:"2",Y:"3",DPadUp:"12",DPadDown:"13",DPadLeft:"14",DPadRight:"15",LeftShoulder:"4",RightShoulder:"5",LeftThumb:"10",RightThumb:"11",LeftTrigger:"6",RightTrigger:"7",Menu:"9",View:"8",Nexus:"16"},gamepad_axes_mapping:{LeftThumbXAxis:"0",LeftThumbYAxis:"1",RightThumbXAxis:"2",RightThumbYAxis:"3"},gamepad_deadzone:.08,gamepad_force_capture:!1};_listener={keyDown:this.onKeyDown.bind(this),keyUp:this.onKeyUp.bind(this),gamepadConnected:this.onGamepadConnected.bind(this),gamepadDisconnected:this.onGamepadDisconnected.bind(this),windowFocus:this.onWindowFocus.bind(this),windowBlur:this.onWindowBlur.bind(this)};constructor(e,t={}){this._index=e,this._options={...this._options,...t}}attach(e){this._player=e,this._player._channels.control.sendGamepadState(this._index,!0,this),this._options.enable_keyboard===!0&&(window.addEventListener("keydown",this._listener.keyDown),window.addEventListener("keyup",this._listener.keyUp)),this._options.enable_gamepad===!0&&(window.addEventListener("gamepadconnected",this._listener.gamepadConnected),window.addEventListener("gamepaddisconnected",this._listener.gamepadDisconnected)),this._options.enable_gamepad===!0&&this._options.gamepad_force_capture===!1&&(window.addEventListener("blur",this._listener.windowBlur),window.addEventListener("focus",this._listener.windowFocus)),this.detectActiveGamepad()}detach(){if(this._player===void 0){console.log("[Gamepad] Player is not attached. this._player is:",this._player);return}this._player._channels.control.sendGamepadState(this._index,!1),this._physicalGamepadId=-1,this._rumbleInterval!==void 0&&clearInterval(this._rumbleInterval),this._options.enable_keyboard===!0&&(window.removeEventListener("keydown",this._listener.keyDown),window.removeEventListener("keyup",this._listener.keyUp)),this._options.enable_gamepad===!0&&(window.removeEventListener("gamepadconnected",this._listener.gamepadConnected),window.removeEventListener("gamepaddisconnected",this._listener.gamepadDisconnected)),this._options.enable_gamepad===!0&&this._options.gamepad_force_capture===!1&&(window.removeEventListener("blur",this._listener.windowBlur),window.removeEventListener("focus",this._listener.windowFocus))}sendButtonState(e,t){if(this._player===void 0){console.log("[Gamepad] Player is not attached. this._player is:",this._player);return}if(!(e in this.getDefaultFamepadFrame())){console.log("[Gamepad] Invalid button:",e);return}let n=this.getDefaultFamepadFrame();n.GamepadIndex=this._index,this._gamepadOverride.buttons[e]=t}onKeyDown(e){if(this._isFocused!==!1)for(let t in this._options.keyboard_mapping)this._options.keyboard_mapping[t]===e.key&&(this._gamepadOverride.buttons[t]=1,e.preventDefault())}onKeyUp(e){if(this._isFocused!==!1)for(let t in this._options.keyboard_mapping)this._options.keyboard_mapping[t]===e.key&&(this._gamepadOverride.buttons[t]=0,e.preventDefault())}onWindowFocus(){this._isFocused=!0}onWindowBlur(){}getDefaultFamepadFrame(){return{GamepadIndex:0,Nexus:0,Menu:0,View:0,A:0,B:0,X:0,Y:0,DPadUp:0,DPadDown:0,DPadLeft:0,DPadRight:0,LeftShoulder:0,RightShoulder:0,LeftThumb:0,RightThumb:0,LeftThumbXAxis:0,LeftThumbYAxis:0,RightThumbXAxis:0,RightThumbYAxis:0,LeftTrigger:0,RightTrigger:0}}detectActiveGamepad(){if(this._physicalGamepadId<0)for(let e in navigator.getGamepads()){let t=navigator.getGamepads()[e]?.index;if(t===void 0)continue;let n=!1;for(let i in this._player?._channels.control.getGamepadHandlers())if(this._player?._channels.control.getGamepadHandlers()[i]instanceof r&&(this._player?._channels.control.getGamepadHandlers()[i])._physicalGamepadId===navigator.getGamepads()[e]?.index){console.log("[Gamepad] Active gamepad already detected:",t,(this._player?._channels.control.getGamepadHandlers()[i])._physicalGamepadId),n=!0;continue}n===!1&&(this._physicalGamepadId=t,console.log("[Gamepad] Active gamepad detected:",this._physicalGamepadId))}else console.log("[Gamepad] Physical gamepad already detected:",this._physicalGamepadId)}onGamepadConnected(e){if(this._physicalGamepadId<0){for(let t in this._player?._channels.control.getGamepadHandlers())if(this._player?._channels.control.getGamepadHandlers()[t]instanceof r&&(this._player?._channels.control.getGamepadHandlers()[t])._physicalGamepadId===e.gamepad.index)return;this._physicalGamepadId=e.gamepad.index}}onGamepadDisconnected(e){e.gamepad.index===this._physicalGamepadId&&(this._physicalGamepadId=-1)}hasOverrideButtons(){return Object.keys(this._gamepadOverride.buttons).length>0}getGamepadState(){let e=this.getGamepad(this._physicalGamepadId);if((this._physicalGamepadId<0||e===void 0||this._isFocused===!1)&&this.hasOverrideButtons()===!1)return;let t=this.getDefaultFamepadFrame();if(t.GamepadIndex=this._index,e!==void 0){for(let i in this._options.gamepad_mapping)t[i]=e.buttons[this._options.gamepad_mapping[i]]?.value??0;for(let i in this._options.gamepad_axes_mapping)t[i]=this.normaliseAxis(e.axes[this._options.gamepad_axes_mapping[i]]??0)}for(let i in this._gamepadOverride.buttons)t[i]=this._gamepadOverride.buttons[i];let n=[];for(let i in this._gamepadOverride.buttons)this._gamepadOverride.buttons[i]===0&&n.push(i);for(let i of n)delete this._gamepadOverride.buttons[i];return t.View>0&&t.Menu>0&&(t.View=0,t.Menu=0,t.Nexus=1),t}getGamepad(e=-1){let t=navigator.getGamepads()[e];if(t!==null)return t}getPhysicalGamepadId(){return this._physicalGamepadId}handleVibration(e){if(this._physicalGamepadId<0){console.log("[Gamepad] Received a vibration report but no physical gamepad is connected");return}let t=this.getGamepad(this._physicalGamepadId);if(t===void 0){console.log("[Gamepad] Received a vibration report but no physical gamepad is connected");return}if(this._options.enable_vibration===!1)return;let n={startDelay:0,duration:e.durationMs,weakMagnitude:e.rightMotorPercent*(window.__ddRumble??1),strongMagnitude:e.leftMotorPercent*(window.__ddRumble??1),leftTrigger:e.leftTriggerMotorPercent,rightTrigger:e.rightTriggerMotorPercent};if(t.vibrationActuator?.type==="dual-rumble"){let i=e.rightMotorPercent<.6?(.6-e.rightMotorPercent)/2:0,a=(e.leftTriggerMotorPercent+e.rightTriggerMotorPercent)/4,s=Math.min(i,a);if(n.weakMagnitude=Math.min(1,(e.rightMotorPercent+s)*(window.__ddRumble??1)),n.leftTrigger=0,n.rightTrigger=0,t.vibrationActuator?.playEffect("dual-rumble",n),clearInterval(this._rumbleInterval),e.repeat>0){let o=e.repeat;this._rumbleInterval=setInterval(()=>{o<=0&&clearInterval(this._rumbleInterval),t.vibrationActuator!==void 0&&t.vibrationActuator?.playEffect("dual-rumble",n),o--},e.delayMs+e.durationMs)}}else console.log("[Gamepad] Unknown vibration type:",t.vibrationActuator.type)}normaliseAxis(e){return Math.abs(e)0&&(this._reportType|=1,s=s+this._calculateMetadataSize(e),this._metadataFrames=e),t.length>0&&(this._reportType|=2,s=s+this._calculateGamepadSize(t),this._gamepadFrames=t),n.length>0&&(this._reportType|=4,s=s+this._calculatePointerSize(n),this._pointerFrames=n),i.length>0&&(this._reportType|=32,s=s+this._calculateMouseSize(i),this._mouseFrames=i),a.length>0&&(this._reportType|=64,s=s+this._calculateKeyboardSize(a),this._keyboardFrames=a),this._totalSize=s}_calculateMetadataSize(e){return 1+7*4*e.length}_calculateGamepadSize(e){return 1+23*e.length}_calculatePointerSize(e){let t=1;for(let n in e)t=t+1+e[n].events.length*20;return t}_calculateMouseSize(e){return 1+18*e.length}_calculateKeyboardSize(e){return 1+3*e.length}_writeMetadataData(e,t,n){e.setUint8(t,n.length),t++,n.length>=30&&console.warn("metadataQueue is bigger then 30. This might impact reliability!");for(let i=0;i=30&&console.warn("gamepadQueue is bigger then 30. This might impact reliability!");for(let i=0;i0&&(s|=2),a.Menu>0&&(s|=4),a.View>0&&(s|=8),a.A>0&&(s|=16),a.B>0&&(s|=32),a.X>0&&(s|=64),a.Y>0&&(s|=128),a.DPadUp>0&&(s|=256),a.DPadDown>0&&(s|=512),a.DPadLeft>0&&(s|=1024),a.DPadRight>0&&(s|=2048),a.LeftShoulder>0&&(s|=4096),a.RightShoulder>0&&(s|=8192),a.LeftThumb>0&&(s|=16384),a.RightThumb>0&&(s|=32768),e.setUint16(t,s,!0),e.setInt16(t+2,this._normalizeAxisValue(a.LeftThumbXAxis),!0),e.setInt16(t+4,this._normalizeAxisValue(-a.LeftThumbYAxis),!0),e.setInt16(t+6,this._normalizeAxisValue(a.RightThumbXAxis),!0),e.setInt16(t+8,this._normalizeAxisValue(-a.RightThumbYAxis),!0),e.setUint16(t+10,this._normalizeTriggerValue(a.LeftTrigger),!0),e.setUint16(t+12,this._normalizeTriggerValue(a.RightTrigger),!0),e.setUint32(t+14,1,!0),e.setUint32(t+18,1,!1),t+=22}return t}_writePointerData(e,t,n){e.setUint8(t,1),t++,n.length>=2&&console.warn("pointerQueue is bigger then 1. Only one event will be sent.");let i=n[0];if(i!==void 0){e.setUint8(t,i.events.length),t++;let a=this._serverVideoWidth,s=this._serverVideoHeight;for(let o=0;o=30&&console.warn("mouseQueue is bigger then 30. This might impact reliability!");for(let i=0;i=30&&console.warn("keyboardQueue is bigger then 30. This might impact reliability!");for(let i=0;i0&&(n=this._writeMetadataData(t,n,this._metadataFrames)),this._gamepadFrames.length>0&&(n=this._writeGamepadData(t,n,this._gamepadFrames)),this._pointerFrames.length>0&&(n=this._writePointerData(t,n,this._pointerFrames)),this._mouseFrames.length>0&&(n=this._writeMouseData(t,n,this._mouseFrames)),this._keyboardFrames.length>0&&(n=this._writeKeyboardData(t,n,this._keyboardFrames)),this._reportType===8&&(t.setUint8(n,this._maxTouchpoints),n++),n!==n)throw new Error("Packet length mismatch. Something is wrong!");return t}_normalizeTriggerValue(e){return e<=0||Number.isNaN(e)?0:e>=1?65535:e*65535|0}_normalizeAxisValue(e){let i=Math.round(e*32767);return i>32767?32767:i<-32767?-32767:i}};var F=class{_player;_inputSequenceNum=0;_metadataQueue=[];_gamepadQueue=[];_pointerQueue=[];_mouseQueue=[];_keyboardQueue=[];_gamepadHeartbeatTimers=new Map;_lastGamepadState=new Map;_axisChangeThreshold=.08;constructor(e){this._player=e}_hasQueuedData(){return this._metadataQueue.length>0||this._gamepadQueue.length>0||this._pointerQueue.length>0||this._mouseQueue.length>0||this._keyboardQueue.length>0}_upsertGamepadFrame(e){for(let t=0;tthis._axisChangeThreshold||o>.15)return!0}for(let a of i)if(Math.abs(e[a]-t[a])>.01)return!0;return!1}_isHeartbeatDue(e){let t=this._gamepadHeartbeatTimers.get(e)??0;return performance.now()-t>33}queueMetadataFrame(e){this._metadataQueue.push(e),this.checkQueueAndSend()}queueGamepadFrame(e){let t=this._lastGamepadState.get(e.GamepadIndex),n=this._hasSignificantAxisChange(e,t),i=this._isHeartbeatDue(e.GamepadIndex);(n||i)&&(this._upsertGamepadFrame(e),this._lastGamepadState.set(e.GamepadIndex,e),this._gamepadHeartbeatTimers.set(e.GamepadIndex,performance.now()),this.checkQueueAndSend())}queueGamepadFrames(e,t=!1){for(let n of e)this._upsertGamepadFrame(n);this.checkQueueAndSend(t)}queueMouseFrame(e){this._mouseQueue.push(e),this.checkQueueAndSend()}queueKeyboardFrame(e){this._keyboardQueue.push(e),this.checkQueueAndSend()}queuePointerFrame(e){this._pointerQueue.length>0?this._pointerQueue[0].events=this._pointerQueue[0].events.concat(e.events):this._pointerQueue.push(e),this.checkQueueAndSend()}checkQueueAndSend(e=!1){if(e===!0){this._hasQueuedData()&&this.sendQueue();return}if(this._gamepadQueue.length>0){this.sendQueue();return}if(this._mouseQueue.length>0||this._keyboardQueue.length>0||this._pointerQueue.length>0){this.sendQueue();return}this._metadataQueue.length>5&&this.sendQueue()}sendQueue(){let e=new y(this.getSequenceNum());this._pointerQueue.length>0&&e.setStreamConfig({width:this._player._channels.input.getServerVideoWidth(),height:this._player._channels.input.getServerVideoHeight()}),e.setData(this._metadataQueue,this._gamepadQueue,this._pointerQueue,this._mouseQueue,this._keyboardQueue),this._player._channels.input.send(e.toBuffer()),this.clearQueues()}clearQueues(){this._metadataQueue=[],this._gamepadQueue=[],this._pointerQueue=[],this._mouseQueue=[],this._keyboardQueue=[]}getSequenceNum(){return this._inputSequenceNum++,this._inputSequenceNum}};var A=class extends _{_serverVideoWidth=0;_serverVideoHeight=0;_inputQueue=new F(this.getPlayer());getChannelName(){return"input"}getChannelConfig(){return{ordered:!0,protocol:"1.0"}}getServerVideoWidth(){return this._serverVideoWidth}getServerVideoHeight(){return this._serverVideoHeight}start(){let e=new y(0);e.setMetadata(navigator.maxTouchPoints>1?navigator.maxTouchPoints:1),this.send(e.toBuffer()),console.log("[InputChannel] Sent metadata:",e,e.toBuffer()),setTimeout(this.gamepadStateLoop.bind(this),16)}onMessage(e){let t=new DataView(e.data),n=t.getUint8(0);if(console.log("[InputChannel] received:",t),n===128){console.log("Received a vibration report"),t.getUint8(2);let i=t.getUint8(3),a=this.getPlayer()._channels.control.getGamepadHandler(i);if(a!==void 0){let s=t.getUint8(4)/100,o=t.getUint8(5)/100,d=t.getUint8(6)/100,u=t.getUint8(7)/100,h=t.getUint16(8,!0),g=t.getUint16(10,!0),p=t.getUint8(12),c={gamepadIndex:i,leftMotorPercent:s,rightMotorPercent:o,leftTriggerMotorPercent:d,rightTriggerMotorPercent:u,durationMs:h,delayMs:g,repeat:p};a.handleVibration(c)}else console.log("[InputChannel] Received a vibration report but no gamepad handler is available")}else n===16&&(console.log("[InputChannel] Received server video dimensions:",t.getUint32(2,!0),t.getUint32(6,!0)),this._serverVideoHeight=t.getUint32(2,!0),this._serverVideoWidth=t.getUint32(6,!0))}gamepadStateLoop(){let e=this.getPlayer()._channels.control.getGamepadHandlers(),t=[];for(let n in e)if(e[n]instanceof v){let i=e[n].getGamepadState();i!==void 0&&t.push(i)}t.length>0&&this.queueGamepadFrames(t),setTimeout(this.gamepadStateLoop.bind(this),16)}queueMetadataFrame(e){return this._inputQueue.queueMetadataFrame(e)}queueGamepadFrames(e,t=!1){this._inputQueue.queueGamepadFrames(e,t)}queueMouseFrame(e){this._inputQueue.queueMouseFrame(e)}queueKeyboardFrame(e){this._inputQueue.queueKeyboardFrame(e)}queuePointerFrame(e){this._inputQueue.queuePointerFrame(e)}destroy(){}};function Q(){return crypto.randomUUID()}var D=class{_channel;_data;constructor(e,t){this._channel=e,this._data=t,this.handle(this._data)}handle(e){switch(console.log("[MessageHandler] Handling:",e),e.target){case"/streaming/sessionLifetimeManagement/serverInitiatedDisconnect":this.completeTransaction(e.id,""),this._channel.getPlayer().destroy();break;case"/streaming/properties/titleinfo":console.log("Title update:",e);break;case"/streaming/touchcontrols/showlayoutv2":break;case"/streaming/systemUi/messages/ShowMessageDialog":this.handleMessage(e);break;default:console.log("[MessageChannel] Unhandled transaction:",e)}}completeTransaction(e,t){let n=JSON.stringify({type:"TransactionComplete",content:JSON.stringify(t),id:e,cv:""});this._channel.send(n)}cancelTransaction(e,t){let n=JSON.stringify({type:"ReceiverCancel",content:JSON.stringify(t),id:e,cv:""});this._channel.send(n)}handleMessage(e){let t=JSON.parse(e.content);console.log(t),confirm(t.TitleText+`
+
+`+t.ContentText)?this.completeTransaction(e.id,{Result:0}):this.completeTransaction(e.id,{Result:1})}};var M=class extends _{_handshakeCompleted=!1;getChannelName(){return"message"}getChannelConfig(){return{protocol:"messageV1",ordered:!0}}onOpen(){console.log("[MessageChannel] Sending handshake...");let e=JSON.stringify({type:"Handshake",version:"messageV1",id:"be0bfc6d-1e83-4c8a-90ed-fa8601c5a179",cv:"0"});this.send(e)}onMessage(e){let t=JSON.parse(e.data);switch(t.type){case"HandshakeAck":console.log("[MessageChannel] Handshake completed"),this._handshakeCompleted=!0,this.getPlayer()._channels.control.sendAuthorization(),this.getPlayer()._channels.input.start(),this.sendConfig();break;case"TransactionStart":case"Message":new D(this,t);break;default:console.log("[MessageChannel] Unhandled message type:",t.type,t)}}sendConfig(){let e=[],t=[0,2,0],n=JSON.stringify(this.generateMessage("/streaming/systemUi/configuration",{version:t,systemUis:e}));this.send(n);let i=JSON.stringify(this.generateMessage("/streaming/properties/clientappinstallidchanged",{clientAppInstallId:"c97d7ee0-73b2-4239-bf1d-9d805a338429"}));this.send(i);let a=JSON.stringify(this.generateMessage("/streaming/characteristics/orientationchanged",{orientation:0}));this.send(a);let s=JSON.stringify(this.generateMessage("/streaming/characteristics/touchinputenabledchanged",{touchInputEnabled:!1}));this.send(s);let o=JSON.stringify(this.generateMessage("/streaming/characteristics/clientdevicecapabilities",{}));this.send(o);let d=JSON.stringify(this.generateMessage("/streaming/characteristics/dimensionschanged",{horizontal:1920,vertical:1080,preferredWidth:1920,preferredHeight:1080,safeAreaLeft:0,safeAreaTop:0,safeAreaRight:1920,safeAreaBottom:1080,supportsCustomResolution:!0}));this.send(d)}generateMessage(e,t){return{type:"Message",content:JSON.stringify(t),id:Q(),target:e,cv:""}}destroy(){}};var E=class{_address;_ipv4Address;_ipv4Port;constructor(e){this._address=e;let t=this._address.split(":"),n=t[6]+t[7],i=t[5],a=~parseInt(n.substring(0,2),16)&255,s=~parseInt(n.substring(2,4),16)&255,o=~parseInt(n.substring(4,6),16)&255,d=~parseInt(n.substring(6,8),16)&255,u=~parseInt(i.substring(0,4),16)&65535;this._ipv4Address=a+"."+s+"."+o+"."+d,this._ipv4Port=u}getIpv4Address(){return this._ipv4Address}getIpv4Port(){return this._ipv4Port}};var R=class{_peerConnection;_iceCandidates=[];constructor(e){this._peerConnection=e._peerConnection,this._peerConnection.addEventListener("icecandidate",t=>{t.candidate&&this._iceCandidates.push(t.candidate)})}getCandidates(){return this._iceCandidates}setRemoteCandidates(e){e.length===0&&console.warn("Error: No candidates received!");for(let t in e){if(e[t].candidate==="a=end-of-candidates")continue;let n=e[t].candidate.split(" ");if(n.length>4&&n[4].substr(0,4)==="2001"){let i=new E(n[4]);this._peerConnection.addIceCandidate({candidate:"a=candidate:10 1 UDP 1 "+i.getIpv4Address()+" 9002 typ host ",sdpMLineIndex:e[t].sdpMLineIndex,sdpMid:e[t].sdpMid}),this._peerConnection.addIceCandidate({candidate:"a=candidate:11 1 UDP 1 "+i.getIpv4Address()+" "+i.getIpv4Port()+" typ host ",sdpMLineIndex:e[t].sdpMLineIndex,sdpMid:e[t].sdpMid})}this._peerConnection.addIceCandidate({candidate:e[t].candidate,sdpMid:e[t].sdpMid,sdpMLineIndex:e[t].sdpMLineIndex})}}};var I=class{_player;_peerConnection;constructor(e){this._player=e,this._peerConnection=e._peerConnection}getAvailableCodecs(){let e=RTCRtpReceiver.getCapabilities("video")?.codecs;if(e===void 0)return[];let t=[];for(let n in e)t.includes(e[n].mimeType)||t.push(e[n].mimeType);return t}setLocalSDP(e){return console.log("[SDP] setLocalSDP() Setting local SDP:",e),e.sdp=e.sdp?.replace("useinbandfec=1","useinbandfec=1; stereo=1"),e}setRemoteSDP(e){return console.log("[SDP] setRemoteSDP() Setting remote SDP:",e),e}getDefaultCodecPreferences(){let e=RTCRtpReceiver.getCapabilities("video")?.codecs;if(e===void 0)return[];let t=[],n=[],i=[],a=[];for(let o in e)e[o].mimeType.includes("H264")?e[o].sdpFmtpLine?.includes("profile-level-id=4d")?t.push(e[o]):e[o].sdpFmtpLine?.includes("profile-level-id=42e")?n.push(e[o]):e[o].sdpFmtpLine?.includes("profile-level-id=420")&&i.push(e[o]):(e[o].mimeType.includes("ulpfec")||e[o].mimeType.includes("flexfec")||e[o].mimeType.includes("VP9")||e[o].mimeType.includes("VP8"))&&a.push(e[o]);return[...t,...n,...i,...a]}_setBitrate(e,t,n){let i=e.split(`
+`),a=-1;for(let o=0;o{e.forEach(t=>{t.type==="inbound-rtp"?this.readInboundRtp(t):t.type==="candidate-pair"&&t.packetsReceived!==void 0&&t.packetsReceived>0?this.readCandidatePair(t):t.type==="remote-candidate"&&this.readRemoteCandidate(t)})})}readInboundRtp(e){e.kind==="video"&&e.codecId&&e.packetsReceived!==void 0&&e.packetsReceived>0?(e.codecId.includes("profile-level-id=4d")?this._videoCodec="H264 (High)":e.codecId.includes("profile-level-id=42e")?this._videoCodec="H264 (Normal)":e.codecId.includes("profile-level-id=420")?this._videoCodec="H264 (Low)":this._videoCodec="Other ("+e.codecId+")",e.frameWidth&&(this._videoWidth=e.frameWidth),e.frameHeight&&(this._videoHeight=e.frameHeight),e.framesPerSecond&&(this._videoFps=e.framesPerSecond)):e.kind==="audio"&&e.codecId&&e.packetsReceived!==void 0&&e.packetsReceived>0&&(this._audioCodec=e.codecId)}readCandidatePair(e){this._activeRemoteCandidate=e.remoteCandidateId,this._rtt=e.currentRoundTripTime}readRemoteCandidate(e){e.id===this._activeRemoteCandidate&&(this.isPrivateIP(e.address)?this._remoteIsLocal=!0:this._remoteIsLocal=!1,this.isIpv6(e.address)?this._remoteIsIpv6=!0:this._remoteIsIpv6=!1,this._remoteHost=e.address,this._remotePort=e.port)}isPrivateIP(e){let t=e.split(".");return t[0]==="10"||t[0]==="172"&&parseInt(t[1],10)>=16&&parseInt(t[1],10)<=31||t[0]==="192"&&t[1]==="168"}isIpv6(e){return e.split(":").length>3}};var G=class{_player;_videoComponent;_overlays={debug:void 0};constructor(e,t){this._videoComponent=e,this._player=t}toggleDebug(){this._overlays.debug===void 0?this.createDebugOverlay():this.destroy()}createDebugOverlay(){this._overlays.debug=document.createElement("div"),this._overlays.debug.id="playerDebugOverlay",this._overlays.debug.style.position="absolute",this._overlays.debug.style.top="0",this._overlays.debug.style.left="0",this._overlays.debug.style.width=this._videoComponent.getElement()?.style.width||"100%",this._overlays.debug.style.height=this._videoComponent.getElement()?.style.height||"auto",this._overlays.debug.style.background="linear-gradient(0deg, rgba(0,0,0, 0) 0%, rgba(0,0,0, 0) 75%, rgba(0,0,0, 0.5) 100%)",this._overlays.debug.style.padding="10px",this._overlays.debug.style.pointerEvents="none",document.getElementById(this._player.getElementId())?.appendChild(this._overlays.debug),setTimeout(()=>{this.refreshDebugOverlay()},500),this.refreshDebugOverlay()}destroy(){this._overlays.debug?.remove(),this._overlays.debug=void 0}refreshDebugOverlay(){if(this._overlays.debug!==void 0){this._overlays.debug.innerHTML="",this._overlays.debug.appendChild(this.createLabel("Local Play",this._player.getStats()._remoteIsLocal?"Local":"Remote","ok")),this._overlays.debug.appendChild(this.createLabel("Resolution",this._player.getStats()._videoWidth+"x"+this._player.getStats()._videoHeight,"ok")),this._overlays.debug.appendChild(this.createLabel("Stream FPS",this._player.getStats()._videoFps.toString(),this._player.getStats()._videoFps>=58?"ok":"warning"));let e=this._videoComponent.getFrameStats?.();e&&(this._overlays.debug.appendChild(this.createLabel("Render FPS",e.renderingFps.toString(),e.renderingFps>=58?"ok":"warning")),this._overlays.debug.appendChild(this.createLabel("Render Delay",e.renderDelayMs.toString()+" ms",e.renderDelayMs<16?"ok":e.renderDelayMs<33?"warning":"error")),this._overlays.debug.appendChild(this.createLabel("Dropped Frames",e.droppedFrames.toString(),e.droppedFrames===0?"ok":e.droppedFrames<30?"warning":"error"))),this._overlays.debug.appendChild(this.createLabel("Connection",this._player.getStats()._remoteIsIpv6?"IPv6":"IPv4","ok")),this._overlays.debug.appendChild(this.createLabel("Video",this._player.getStats()._videoCodec,"ok"));let t=this._player.getStats()._rtt*1e3>75?"error":this._player.getStats()._rtt*1e3>40?"warning":"ok";this._overlays.debug.appendChild(this.createLabel("RTT",(this._player.getStats()._rtt*1e3).toString()+" ms",t)),setTimeout(()=>{this.refreshDebugOverlay()},500)}}createLabel(e,t="",n=""){let i={borderRadius:"5px",background:"linear-gradient(0deg, rgba(28,26,26,1) 0%, rgba(47,45,45,1) 100%)",padding:"10px",fontSize:"12px",marginTop:"3px",marginRight:"10px",marginBottom:"2px",textTransform:"uppercase",color:"white",display:"inline-block"},a=document.createElement("span"),s={error:"rgb(220, 53, 69)",warning:"rgb(255, 193, 7)",ok:"rgb(25, 135, 84)"};t!==""?a.innerHTML=`${e}: ${t}`:a.innerText=e;for(let o in i)a.style[o]=i[o];return a}};var L=class{_player;_element;_overlay;constructor(e){this._player=e,this._overlay=new G(this,this._player)}create(e){let t=document.createElement("video");t.srcObject=e,t.autoplay=!0,t.muted=!0,t.playsInline=!0,t.style.width="100%",t.style.height="100%",t.style.objectFit="contain",t.style.backgroundColor="black",t.style.touchAction="none",t.poster="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";let n=document.getElementById(this._player.getElementId());if(n===null)return;this._element=t,n.appendChild(this._element),getComputedStyle(n).position==="static"===!0&&(n.style.position="relative"),this._element.requestVideoFrameCallback(this.processVideoMetadata.bind(this))}processVideoMetadata(e,t){this._element!==void 0&&(this._element.requestVideoFrameCallback(this.processVideoMetadata.bind(this)),this._player._channels.input.queueMetadataFrame({serverDataKey:t.rtpTimestamp,firstFramePacketArrivalTimeMs:t.receiveTime,frameSubmittedTimeMs:t.receiveTime,frameDecodedTimeMs:t.expectedDisplayTime,frameRenderedTimeMs:t.expectedDisplayTime}))}getElement(){return this._element}toggleDebugOverlay(){this._overlay.toggleDebug()}destroy(){let t=document.getElementById(this._player.getElementId())?.querySelector("video");this._overlay!==void 0&&this._overlay.destroy(),t&&t.remove()}};var N=class{_player;_element;constructor(e){this._player=e}create(e){let t=document.createElement("audio");t.srcObject=e,t.autoplay=!0,t.muted=!1,this._element=t;let n=document.getElementById(this._player.getElementId());n!==null&&n.appendChild(this._element)}getElement(){return this._element}destroy(){let t=document.getElementById(this._player.getElementId())?.querySelector("audio");t&&t.remove()}};var U=class{_peerConnection=new RTCPeerConnection({});_channels={chat:new S(this),control:new w(this),input:new A(this),message:new M(this)};_elementId;_isDestoyed=!1;_iceHelper=new R(this);_sdpHelper=new I(this);_statsHelper=new P(this);_videoComponent;_audioComponent;constructor(e){console.log("xCloudPlayer constructing..."),this._elementId=e,this._peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this._peerConnection.addTransceiver("video",{direction:"recvonly"}).setCodecPreferences(this._sdpHelper.getDefaultCodecPreferences()),this._peerConnection.ontrack=n=>{n.track.kind==="video"?(this._videoComponent=new L(this),this._videoComponent.create(n.streams[0])):n.track.kind==="audio"?(this._audioComponent=new N(this),this._audioComponent.create(n.streams[0])):console.log("[xPlayer] Detected an unknown stream type: ",n.track.kind)},console.log("xCloudPlayer constructed.")}init(){console.log("xCloudPlayer init called.")}getElementId(){return this._elementId}async createOffer(){let e=await this._peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),t=this._sdpHelper.setLocalSDP(e);return this._peerConnection.setLocalDescription(t),t}async setRemoteSDP(e){let t=this._sdpHelper.setRemoteSDP(e);return await this._peerConnection.setRemoteDescription({type:"answer",sdp:t})}async getICECandidates(){return this._iceHelper.getCandidates()}async setRemoteIceCandidates(e){this._iceHelper.setRemoteCandidates(e)}getVideoElement(){if(this._videoComponent)return this._videoComponent.getElement()}getAudioElement(){if(this._audioComponent)return this._audioComponent.getElement()}toggleDebugOverlay(){this._videoComponent&&this._videoComponent.toggleDebugOverlay()}getStats(){return this._statsHelper}destroy(){if(this._isDestoyed===!1){this._peerConnection.close(),this._peerConnection.onconnectionstatechange&&this._peerConnection.onconnectionstatechange(new Event("connectionstatechanged"));for(let e in this._channels)this._channels[e].destroy();this._videoComponent&&this._videoComponent.destroy(),this._audioComponent&&this._audioComponent.destroy(),this._isDestoyed=!0}else console.log("Cannot destroy because the player is already destroyed.")}};function X(r){return r.brightness!==0||r.contrast!==0||Math.abs(r.gamma-1)>.001||r.saturation!==100||r.sharpen>0||r.deband>0||r.fxaa||r.toon||r.crt||r.ntsc||r.maxFps>0}var J=`#version 300 es
+in vec2 position;
+out vec2 vUV;
+void main() { vUV = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`,j=`attribute vec2 position;
+varying vec2 vUV;
+void main() { vUV = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`,Z=`#version 300 es
+precision mediump float;
+uniform sampler2D screenTexture;
+uniform vec2 resolution;
+uniform int filterId;
+uniform float sharpenFactor;
+uniform float brightness;
+uniform float contrast;
+uniform float gamma;
+uniform float saturation;
+uniform float deband;
+out vec4 fragColor;
+const float CAS_CONTRAST_PEAK = 0.8 * -3.0 + 8.0;
+
+vec3 sharpen(vec2 coord, vec3 e) {
+ vec2 px = 1.0 / resolution;
+ vec3 b = texture(screenTexture, coord + px * vec2(0, 1)).rgb;
+ vec3 d = texture(screenTexture, coord + px * vec2(-1, 0)).rgb;
+ vec3 f = texture(screenTexture, coord + px * vec2(1, 0)).rgb;
+ vec3 h = texture(screenTexture, coord + px * vec2(0, -1)).rgb;
+ vec3 a = texture(screenTexture, coord + px * vec2(-1, 1)).rgb;
+ vec3 c = texture(screenTexture, coord + px * vec2(1, 1)).rgb;
+ vec3 g = texture(screenTexture, coord + px * vec2(-1, -1)).rgb;
+ vec3 i = texture(screenTexture, coord + px * vec2(1, -1)).rgb;
+ if (filterId == 1) {
+ vec3 blur = ((a + c + g + i) + (b + d + f + h) * 2.0 + e * 4.0) / 16.0;
+ return e + (e - blur) * sharpenFactor / 3.0;
+ }
+ vec3 minRgb = min(min(min(d, e), min(f, b)), h) + min(min(a, c), min(g, i));
+ vec3 maxRgb = max(max(max(d, e), max(f, b)), h) + max(max(a, c), max(g, i));
+ vec3 amplify = inversesqrt(clamp(min(minRgb, 2.0 - maxRgb) / maxRgb, 0.0, 1.0));
+ vec3 weight = -(1.0 / (amplify * CAS_CONTRAST_PEAK));
+ vec3 outColor = clamp(((b + d + f + h) * weight + e) / (4.0 * weight + 1.0), 0.0, 1.0);
+ return mix(e, outColor, sharpenFactor / 2.0);
+}
+
+float ign(vec2 p) { return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); }
+
+void main() {
+ vec2 uv = gl_FragCoord.xy / resolution;
+ vec3 color = texture(screenTexture, uv).rgb;
+ if (sharpenFactor > 0.0) color = sharpen(uv, color);
+ color = clamp(color + brightness, 0.0, 1.0);
+ color = (color - 0.5) * clamp(contrast + 1.0, 0.5, 2.0) + 0.5;
+ color = mix(vec3(dot(color, vec3(0.2126, 0.7152, 0.0722))), color, saturation);
+ color = pow(max(color, 0.0), vec3(1.0 / gamma));
+ if (deband > 0.0) color += vec3(((ign(gl_FragCoord.xy) + ign(gl_FragCoord.xy + vec2(11.0, 17.0))) - 1.0) * (deband / 255.0));
+ fragColor = vec4(color, 1.0);
+}`,ee=`precision highp float;
+#define FXAA_MIN_REDUCE (1.0 / 128.0)
+#define FXAA_MUL_REDUCE (1.0 / 8.0)
+#define MAX_SPAN 8.0
+uniform sampler2D screenTexture;
+uniform vec2 resolution;
+const vec3 luma = vec3(0.299, 0.587, 0.114);
+void main() {
+ vec2 invResolution = 1.0 / resolution;
+ vec3 rgbNW = texture2D(screenTexture, (gl_FragCoord.xy + vec2(-1.0, -1.0)) * invResolution).rgb;
+ vec3 rgbNE = texture2D(screenTexture, (gl_FragCoord.xy + vec2( 1.0, -1.0)) * invResolution).rgb;
+ vec3 rgbSW = texture2D(screenTexture, (gl_FragCoord.xy + vec2(-1.0, 1.0)) * invResolution).rgb;
+ vec3 rgbSE = texture2D(screenTexture, (gl_FragCoord.xy + vec2( 1.0, 1.0)) * invResolution).rgb;
+ vec3 rgbM = texture2D(screenTexture, gl_FragCoord.xy * invResolution).rgb;
+ float lumaNW = dot(rgbNW, luma);
+ float lumaNE = dot(rgbNE, luma);
+ float lumaSW = dot(rgbSW, luma);
+ float lumaSE = dot(rgbSE, luma);
+ float lumaM = dot(rgbM, luma);
+ float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
+ float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
+ vec2 dir;
+ dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
+ dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));
+ float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * 0.25 * FXAA_MUL_REDUCE, FXAA_MIN_REDUCE);
+ float minDirFactor = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
+ dir = clamp(dir * minDirFactor, vec2(-MAX_SPAN), vec2(MAX_SPAN)) * invResolution;
+ vec4 rgbA = 0.5 * (
+ texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * (1.0 / 3.0 - 0.5)) +
+ texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * (2.0 / 3.0 - 0.5)));
+ vec4 rgbB = rgbA * 0.5 + 0.25 * (
+ texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * -0.5) +
+ texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * 0.5));
+ float lumaB = dot(rgbB, vec4(luma, 0.0));
+ gl_FragColor = lumaB < lumaMin || lumaB > lumaMax ? rgbA : rgbB;
+}`,te=`precision highp float;
+uniform sampler2D screenTexture;
+uniform vec2 resolution;
+void main() {
+ vec2 uv = gl_FragCoord.xy / resolution;
+ float edgeThreshold = 0.2;
+ vec2 offset = vec2(1.0) / resolution;
+ vec3 colorCenter = texture2D(screenTexture, uv).rgb;
+ vec3 colorLeft = texture2D(screenTexture, uv - vec2(offset.x, 0.0)).rgb;
+ vec3 colorRight = texture2D(screenTexture, uv + vec2(offset.x, 0.0)).rgb;
+ vec3 colorUp = texture2D(screenTexture, uv - vec2(0.0, offset.y)).rgb;
+ vec3 colorDown = texture2D(screenTexture, uv + vec2(0.0, offset.y)).rgb;
+ float diffHorizontal = length(colorRight - colorLeft);
+ float diffVertical = length(colorUp - colorDown);
+ float edgeFactor = step(edgeThreshold, diffHorizontal + diffVertical);
+ vec3 outlineColor = mix(colorCenter, vec3(0.0), edgeFactor);
+ gl_FragColor = vec4(outlineColor, 1.0);
+}`,ne=`precision highp float;
+#define CA_AMOUNT 1.0025
+#define SCANLINE_INTENSITY_X 0.125
+#define SCANLINE_INTENSITY_Y 0.375
+#define SCANLINE_SIZE 1024.0
+uniform sampler2D screenTexture;
+varying vec2 vUV;
+void main() {
+ vec4 finalColor = texture2D(screenTexture, vUV);
+ finalColor.rgb = vec3(
+ texture2D(screenTexture, (vUV - 0.5) * CA_AMOUNT + 0.5).r,
+ finalColor.g,
+ texture2D(screenTexture, (vUV - 0.5) / CA_AMOUNT + 0.5).b
+ );
+ float scanlineX = abs(sin(vUV.x * SCANLINE_SIZE) * 0.5 * SCANLINE_INTENSITY_X);
+ float scanlineY = abs(sin(vUV.y * SCANLINE_SIZE) * 0.5 * SCANLINE_INTENSITY_Y);
+ gl_FragColor = vec4(mix(finalColor.rgb, vec3(0.0), scanlineX + scanlineY), finalColor.a);
+}`,ie=`precision highp float;
+#define PI 3.14159265
+#define SCANLINE_INTENSITY 0.35
+#define CHROMA_OFFSET 0.005
+#define BLUR_RADIUS 0.002
+#define WARP_AMOUNT 0.01
+#define SCANLINE_DARKEN 0.5
+uniform sampler2D screenTexture;
+uniform int FrameCount;
+uniform vec2 TextureSize;
+uniform vec2 resolution;
+varying vec2 vUV;
+const mat3 yiq_mat = mat3(
+ 0.299, 0.587, 0.114,
+ 0.596, -0.275, -0.321,
+ 0.212, -0.523, 0.311
+);
+const mat3 yiq2rgb_mat = mat3(
+ 1.0, 0.956, 0.621,
+ 1.0, -0.272, -0.647,
+ 1.0, -1.106, 1.705
+);
+vec3 applyNTSC(vec2 uv) {
+ vec3 col = texture2D(screenTexture, uv).rgb;
+ vec3 yiq = col * yiq_mat;
+ float chromaPhase = PI * (mod(uv.y * TextureSize.y, 2.0) + float(FrameCount));
+ yiq.y *= cos(chromaPhase * 0.5);
+ yiq.z *= sin(chromaPhase * 0.5);
+ vec3 rgb = yiq * yiq2rgb_mat;
+ vec3 finalColor;
+ finalColor.r = texture2D(screenTexture, uv + vec2(CHROMA_OFFSET, 0.0)).r;
+ finalColor.g = texture2D(screenTexture, uv + vec2(0.0, BLUR_RADIUS)).g;
+ finalColor.b = texture2D(screenTexture, uv - vec2(CHROMA_OFFSET, 0.0)).b;
+ return finalColor;
+}
+vec3 applyScanlines(vec2 uv) {
+ vec3 col = texture2D(screenTexture, uv).rgb;
+ float scanline = abs(sin(uv.y * resolution.y * 2.0)) * SCANLINE_INTENSITY;
+ col *= 1.0 - (scanline * SCANLINE_DARKEN);
+ return col;
+}
+vec2 applyWarp(vec2 uv) {
+ uv = uv * 2.0 - 1.0;
+ float r = sqrt(uv.x * uv.x + uv.y * uv.y);
+ uv += uv * (r * r) * WARP_AMOUNT;
+ return uv * 0.5 + 0.5;
+}
+void main() {
+ vec2 warpedUV = applyWarp(vUV);
+ vec3 ntscColor = applyNTSC(warpedUV);
+ vec3 scanlineColor = applyScanlines(warpedUV);
+ vec3 finalColor = mix(ntscColor, scanlineColor, 0.7);
+ gl_FragColor = vec4(finalColor, 1.0);
+}`,H=class{constructor(e,t){this.video=e;this.effects=t;this.canvas=document.createElement("canvas"),Object.assign(this.canvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"contain",zIndex:"1"}),e.parentElement?.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,desynchronized:!0,powerPreference:"high-performance"});if(n===null)throw new Error("WebGL2 unavailable");this.gl=n;let i=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,i),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),n.STATIC_DRAW),this.passes.set("base",this.compile(J,Z,["screenTexture","resolution","filterId","sharpenFactor","brightness","contrast","gamma","saturation","deband"])),this.videoTexture=this.texture(),this.schedule()}canvas;gl;passes=new Map;videoTexture;targets=[];width=0;height=0;frame=0;lastDraw=0;stopped=!1;idle=!1;pending=!1;update(e){this.effects=e}pause(){this.idle||this.stopped||(this.idle=!0,this.canvas.style.display="none")}resume(e){this.effects=e,!(!this.idle||this.stopped)&&(this.idle=!1,this.canvas.style.display="",this.schedule())}schedule(){this.pending||(this.pending=!0,this.video.requestVideoFrameCallback(this.onFrame))}compile(e,t,n){let i=this.gl,a=(o,d)=>{let u=i.createShader(o);if(i.shaderSource(u,d),i.compileShader(u),!i.getShaderParameter(u,i.COMPILE_STATUS))throw new Error(`shader: ${i.getShaderInfoLog(u)}`);return u},s=i.createProgram();if(i.attachShader(s,a(i.VERTEX_SHADER,e)),i.attachShader(s,a(i.FRAGMENT_SHADER,t)),i.bindAttribLocation(s,0,"position"),i.linkProgram(s),!i.getProgramParameter(s,i.LINK_STATUS))throw new Error(`program: ${i.getProgramInfoLog(s)}`);return{program:s,uniforms:new Map(n.map(o=>[o,i.getUniformLocation(s,o)]))}}extra(e){let t=this.passes.get(e);if(t===void 0){let n={fxaa:ee,toon:te,crt:ne,ntsc:ie}[e];t=this.compile(j,n,["screenTexture","resolution","TextureSize","FrameCount"]),this.passes.set(e,t)}return t}texture(){let e=this.gl,t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t}resize(e,t){let n=this.gl;this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t;for(let i of this.targets)n.deleteFramebuffer(i.framebuffer),n.deleteTexture(i.texture);this.targets=[0,1].map(()=>{let i=this.texture();n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null);let a=n.createFramebuffer();return n.bindFramebuffer(n.FRAMEBUFFER,a),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0),{framebuffer:a,texture:i}}),n.bindFramebuffer(n.FRAMEBUFFER,null)}onFrame=e=>{if(this.pending=!1,this.stopped||this.idle)return;this.schedule();let t=this.effects.maxFps;if(!(t>0&&e-this.lastDraw<1e3/t-2)){this.lastDraw=e;try{this.draw()}catch(n){window.DDCloud?.log(`effects: ${String(n).slice(0,200)}`),this.destroy()}}};draw(){let e=this.gl,t=this.effects,n=this.video.videoWidth,i=this.video.videoHeight;if(n===0||i===0)return;(n!==this.width||i!==this.height)&&this.resize(n,i),this.frame++,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.videoTexture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.video);let a=["fxaa","toon","crt","ntsc"].filter(d=>t[d]);e.viewport(0,0,n,i),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0);let s=this.passes.get("base");e.bindFramebuffer(e.FRAMEBUFFER,a.length>0?this.targets[0].framebuffer:null),e.useProgram(s.program);let o=s.uniforms;e.uniform1i(o.get("screenTexture"),0),e.uniform2f(o.get("resolution"),n,i),e.uniform1i(o.get("filterId"),t.sharpenMode==="usm"?1:2),e.uniform1f(o.get("sharpenFactor"),t.sharpen),e.uniform1f(o.get("brightness"),t.brightness/100),e.uniform1f(o.get("contrast"),t.contrast/100),e.uniform1f(o.get("gamma"),Math.min(5,Math.max(.1,t.gamma))),e.uniform1f(o.get("saturation"),t.saturation/100),e.uniform1f(o.get("deband"),t.deband),e.drawArrays(e.TRIANGLES,0,3),a.forEach((d,u)=>{let h=this.extra(d),g=this.targets[u%2],p=u===a.length-1;e.bindFramebuffer(e.FRAMEBUFFER,p?null:this.targets[(u+1)%2].framebuffer),e.useProgram(h.program),e.bindTexture(e.TEXTURE_2D,g.texture);let c=h.uniforms;e.uniform1i(c.get("screenTexture")??null,0),e.uniform2f(c.get("resolution")??null,n,i),e.uniform2f(c.get("TextureSize")??null,n,i),e.uniform1i(c.get("FrameCount")??null,this.frame),e.drawArrays(e.TRIANGLES,0,3)})}destroy(){this.stopped=!0,this.canvas.remove(),this.gl.getExtension("WEBGL_lose_context")?.loseContext()}};var V=class{constructor(e){this.pc=e;this.element=document.createElement("div"),Object.assign(this.element.style,{position:"absolute",top:"8px",right:"8px",zIndex:"3",padding:"4px 8px",borderRadius:"6px",background:"rgba(0,0,0,0.55)",color:"#e8e8e8",font:"12px monospace",lineHeight:"16px",pointerEvents:"none",display:"none",whiteSpace:"pre",textAlign:"right"}),document.body.appendChild(this.element)}element;timer;level=0;vertical=!1;left=!1;server="";last={bytes:0,time:0,decode:0,frames:0,lost:0,received:0};show(e,t,n,i=!1){this.level=e,this.vertical=t,this.server=n,this.left=i,Object.assign(this.element.style,i?{left:"8px",right:"",textAlign:"left"}:{left:"",right:"8px",textAlign:"right"}),this.element.style.display=e>0?"block":"none",e>0&&this.timer===void 0&&(this.timer=setInterval(()=>this.update(),1e3),this.update()),e===0&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}async update(){let e=await this.pc.getStats(),t,n,i=new Map;if(e.forEach(c=>{c.type==="inbound-rtp"&&c.kind==="video"?t=c:c.type==="candidate-pair"&&c.state==="succeeded"&&c.nominated?n=c:c.type==="codec"&&i.set(c.id,c)}),t===void 0)return;let a=this.last.time>0?(t.timestamp-this.last.time)/1e3:0,s=a>0?(t.bytesReceived-this.last.bytes)*8/a/1e6:0,o=(t.framesDecoded??0)-this.last.frames,d=o>0?((t.totalDecodeTime??0)-this.last.decode)*1e3/o:0,u=(t.packetsLost??0)-this.last.lost,h=(t.packetsReceived??0)-this.last.received,g=u+h>0?u*100/(u+h):0;this.last={bytes:t.bytesReceived,time:t.timestamp,decode:t.totalDecodeTime??0,frames:t.framesDecoded??0,lost:t.packetsLost??0,received:t.packetsReceived??0};let p=["web",`${Math.round(t.framesPerSecond??0)} fps`];if(this.level>=2&&(n?.currentRoundTripTime!==void 0&&p.push(`ping ${Math.round(n.currentRoundTripTime*1e3)} ms`),p.push(`${t.frameWidth??"?"}x${t.frameHeight??"?"}`)),this.level>=3&&p.push(`${s.toFixed(1)} Mb/s`,`decode ${d.toFixed(1)} ms`,`loss ${g.toFixed(1)}%`),this.level>=4){let c=i.get(t.codecId);c&&p.push(String(c.mimeType??"").replace("video/","")),p.push(`jitter ${Math.round((t.jitter??0)*1e3)} ms`,`dropped ${t.framesDropped??0}`),this.server&&p.push(this.server)}this.element.textContent=p.join(this.vertical?`
+`:" \xB7 ")}destroy(){this.show(0,this.vertical,this.server,this.left),this.element.remove()}};function z(r,e){let t=e==="high"?"4d":e==="low"?"420":"42e",n=[];for(let d of r.matchAll(/a=fmtp:(\d+).*profile-level-id=([0-9a-f]{6})/g))d[2].startsWith(t)&&n.push(d[1]);if(n.length===0)return r;let i=r.split(`\r
+`),a=i.findIndex(d=>d.startsWith("m=video"));if(a<0)return r;let s=i[a].trim().split(" "),o=s.slice(3).filter(d=>!n.includes(d));return i[a]=s.slice(0,3).concat(n,o).join(" "),i.join(`\r
+`)}function K(r,e){let t=r.split(`\r
+`),n=t.findIndex(a=>a.startsWith("m=video"));if(n<0)return r;let i=`b=AS:${e}`;for(let a=n+1;a<=t.length;a++){let s=t[a];if(s===void 0||s.startsWith("m=")){t.splice(a,0,i);break}if(!(s.startsWith("i=")||s.startsWith("c="))){if(s.startsWith("b=AS:")){t[a]=i;break}t.splice(a,0,i);break}}return t.join(`\r
+`)}var m=JSON.parse(DDCloud.settings()),ae=RTCPeerConnection.prototype.setLocalDescription;RTCPeerConnection.prototype.setLocalDescription=function(r){return r?.sdp&&((m.codec==="high"||m.codec==="normal"||m.codec==="low")&&(r.sdp=z(r.sdp,m.codec)),m.bitrateMbps>0&&(r.sdp=K(r.sdp,m.bitrateMbps*1e3))),ae.call(this,r)};window.__ddRumble=m.rumble/100;window.addEventListener("error",r=>DDCloud.log(`error: ${r.message} @${r.lineno}`));window.addEventListener("unhandledrejection",r=>DDCloud.log(`rejection: ${String(r.reason).slice(0,200)}`));window.addEventListener("gamepadconnected",r=>DDCloud.log(`controller: ${r.gamepad.id.slice(0,60)} mapping=${r.gamepad.mapping||"none"} buttons=${r.gamepad.buttons.length} axes=${r.gamepad.axes.length}`));var W=new Map,re=1;window.__ddResolve=(r,e,t)=>{let n=W.get(r);W.delete(r),n&&n({status:e,body:t})};function C(r,e=""){return new Promise(t=>{let n=re++;W.set(n,t),DDCloud.call(n,r,typeof e=="string"?e:JSON.stringify(e))})}var B=r=>new Promise(e=>setTimeout(e,r)),se=r=>r.status>=200&&r.status<300;function x(r){let e=document.getElementById("status");e&&(e.textContent=r),DDCloud.status(r)}var T=class extends Error{constructor(t,n){super(t);this.stage=t;this.detail=n}};function k(r,e){if(!se(e))throw new T(r,`${e.status} ${e.body.slice(0,300)}`);return e}function oe(r,e){return new Promise(t=>{if(r.iceGatheringState==="complete")return t();let n=setTimeout(t,e);r.addEventListener("icegatheringstatechange",()=>{r.iceGatheringState==="complete"&&(clearTimeout(n),t())})})}async function de(){x("Starting the game on Xbox Cloud Gaming\u2026"),k("start",await C("start"));let r=!1,e=0;for(;;){let l=k("state",await C("state")),f=JSON.parse(l.body||"{}");if(f.state==="Provisioned")break;if(f.state==="Failed")throw new T("provision",JSON.stringify(f.errorDetails??{}).slice(0,300));f.state==="ReadyToConnect"&&!r?(r=!0,x("Signing in to the cloud console\u2026"),k("connect",await C("connect"))):f.state==="WaitingForResources"?x(`In the queue for a cloud console\u2026 ${Math.round(e/1e3)} s`):x(`Getting a cloud console ready\u2026 ${Math.round(e/1e3)} s`),await B(1e3),e+=1e3}x("Connecting\u2026");let t=new U("player");t.init();let n=t._peerConnection,i=t._channels.input,a=i.queueMetadataFrame.bind(i);i.queueMetadataFrame=l=>{if(m.preventDrops){let f=l.frameRenderedTimeMs-l.frameDecodedTimeMs;l.frameDecodedTimeMs=l.frameSubmittedTimeMs+10,l.frameRenderedTimeMs=l.frameDecodedTimeMs+f}a(l)};let s,o,d=()=>{if(!(o===void 0||s===void 0&&m.volume===100)){if(s===void 0){let l=new AudioContext;s=l.createGain(),l.createMediaStreamSource(o).connect(s).connect(l.destination);let f=document.querySelector("#player audio");f&&(f.muted=!0)}s.gain.value=m.volume/100}};n.addEventListener("track",l=>{l.track.kind==="audio"&&(o=l.streams[0],d())});let u=new V(n),h,g=()=>{let l=t.getVideoElement();if(l!==void 0){if(!X(m)){h?.pause();return}if(h===void 0)try{h=new H(l,m)}catch(f){DDCloud.log(`effects unavailable: ${String(f).slice(0,200)}`)}else h.resume(m)}};window.__ddApply=l=>{m=JSON.parse(l),window.__ddRumble=m.rumble/100,u.show(m.statsLevel,m.statsLayout==="vertical",m.server,m.statsCorner==="left"),d(),g()},n.addEventListener("connectionstatechange",()=>{n.connectionState==="connected"?(x(""),DDCloud.playing(),u.show(m.statsLevel,m.statsLayout==="vertical",m.server,m.statsCorner==="left"),setTimeout(g,500)):n.connectionState==="failed"?DDCloud.failed("webrtc","connection failed"):n.connectionState==="disconnected"&&x("Connection lost\u2026")});let p=await t.createOffer(),c=k("sdp",await C("sdp",p.sdp??"")),O=JSON.parse(JSON.parse(c.body).exchangeResponse);if(O.status&&O.status!=="success")throw new T("sdp-answer",JSON.stringify(O).slice(0,300));await t.setRemoteSDP(O.sdp),await oe(n,3e3);let Y=(await t.getICECandidates()).map(l=>JSON.stringify({candidate:l.candidate,sdpMid:l.sdpMid,sdpMLineIndex:l.sdpMLineIndex,usernameFragment:l.usernameFragment})),$=k("ice",await C("ice",Y));t.setRemoteIceCandidates(JSON.parse(JSON.parse($.body).exchangeResponse));let q=Date.now();for(;!t._channels.message._handshakeCompleted&&Date.now()-q<2e4;)await B(100);DDCloud.log(`handshake ${t._channels.message._handshakeCompleted?"done":"missing"} after ${Date.now()-q} ms`),await B(300);let b=new v(0,{enable_keyboard:!1});b.attach(t),DDCloud.log(`controllers at attach: ${Array.from(navigator.getGamepads()).filter(Boolean).length}`),window.__ddNexus=()=>{b.sendButtonState("Nexus",1),setTimeout(()=>b.sendButtonState("Nexus",0),200)},window.__ddButton=(l,f)=>b.sendButtonState(l,f),window.__ddInput=l=>{l?b.onWindowFocus():b.onWindowBlur()},setInterval(()=>{C("keepalive")},3e4),window.__ddStop=()=>{try{h?.destroy(),u.destroy(),b.detach(),t.destroy()}catch{}}}de().catch(r=>{r instanceof T?DDCloud.failed(r.stage,r.detail):DDCloud.failed("page",String(r).slice(0,300))});})();
diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt
index ab06f6a56..16c751605 100644
--- a/app/src/main/cpp/CMakeLists.txt
+++ b/app/src/main/cpp/CMakeLists.txt
@@ -8,7 +8,6 @@ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,max-page-size=16384
add_subdirectory(adrenotools)
-# DXVK's DXBC->SPIR-V translator is zlib licensed (vendored under thirdparty/dxbc).
add_subdirectory(thirdparty/dxbc)
set(DDFG_UPSTREAM "v0.3.0")
@@ -37,13 +36,14 @@ target_link_libraries(sdnative log)
add_library(deviceinfo SHARED deviceinfo/vkinfo.c)
target_link_libraries(deviceinfo dl)
+add_library(gpuclock SHARED gpuclock/kgsl_clock.c gpuclock/kgsl_busy.c)
+
add_library(termux SHARED termux/termux.c)
add_library(ddvenc SHARED venc/venc_server.cpp)
target_compile_features(ddvenc PRIVATE cxx_std_17)
target_link_libraries(ddvenc mediandk log)
-# The optional proprietary SDK is supplied locally; its headers/libraries are not vendored.
if(DROIDDECK_VITURE_SDK_DIR)
add_library(droiddeck_viture SHARED viture/sdk_bridge.cpp)
target_compile_features(droiddeck_viture PRIVATE cxx_std_17)
diff --git a/app/src/main/cpp/fakeinput_steam.cpp b/app/src/main/cpp/fakeinput_steam.cpp
index c446170fe..8906b01f7 100644
--- a/app/src/main/cpp/fakeinput_steam.cpp
+++ b/app/src/main/cpp/fakeinput_steam.cpp
@@ -78,7 +78,6 @@ static constexpr uint8_t GAMEPAD_AXIS_COUNT = 8;
static constexpr uint8_t GAMEPAD_BUTTON_COUNT = 11;
static constexpr uint32_t FAKE_INPUT_RING_MAGIC = 0x46494252;
static constexpr uint32_t FAKE_INPUT_RING_VERSION = 2;
-// Rings hold the 64-bit input_event layout that the arm64 writers use; 32-bit guests convert on read.
struct RingEvent {
int64_t sec;
int64_t usec;
@@ -93,6 +92,7 @@ static constexpr unsigned int FAKE_INPUT_MAJOR = 13;
static constexpr unsigned int FAKE_INPUT_EVENT_MINOR_BASE = 64;
static constexpr unsigned int FAKE_INPUT_JS_MINOR_BASE = 0;
static constexpr int UINPUT_EVENT_BASE = 16;
+static constexpr int MOUSE_EVENT_SLOT = 4;
static constexpr int UINPUT_EVENT_LIMIT = 64;
static constexpr uint32_t UINPUT_DESCRIPTION_MAGIC = 0x46495544;
@@ -121,6 +121,12 @@ static constexpr size_t FAKE_INPUT_RING_HEADER_SIZE =
static constexpr size_t FAKE_INPUT_RING_SIZE =
FAKE_INPUT_RING_HEADER_SIZE +
(FAKE_INPUT_RING_CAPACITY * FAKE_INPUT_EVENT_SIZE);
+static constexpr size_t DECK_IMU_BLOCK_SIZE = 64;
+static constexpr size_t FAKE_INPUT_RING_PAD_TYPE_OFFSET = 44;
+static constexpr uint32_t PAD_TYPE_DECK = 0, PAD_TYPE_STEAM = 1, PAD_TYPE_XBOX = 2, PAD_TYPE_DS4 = 3,
+ PAD_TYPE_DUALSENSE = 4, PAD_TYPE_LAST = PAD_TYPE_DUALSENSE,
+ PAD_TYPE_MOUSE = 5;
+static constexpr uint32_t PAD_TYPE_SET = 0x80000000u;
struct UinputDescription {
uint32_t magic;
@@ -149,6 +155,7 @@ struct FakeController {
size_t mapping_size = 0;
bool closed = false;
bool needs_keyframe = true;
+ bool mouse = false;
~FakeController() {
if (ring) munmap(ring, mapping_size);
@@ -383,7 +390,6 @@ send_vibration(int strong, int weak, uint16_t duration_ms, uint16_t slot) {
syscall(SYS_close, sock);
}
-// Must match RumbleComponent.HOLD_MS: play until the slot's next effect or stop.
static constexpr uint16_t RUMBLE_HOLD_MS = 0xffff;
__attribute__((visibility("hidden"))) static void send_ff_effect(const struct ff_effect &effect, uint16_t slot) {
@@ -607,7 +613,7 @@ open_fake_input_ring(const char *event, int flags) {
int slot = get_event_number(event);
bool virtual_pad = slot >= UINPUT_EVENT_BASE;
std::string ring_path = virtual_pad ? uinput_ring_path(slot) : get_ring_path_for_slot(slot);
- size_t mapping_size = virtual_pad ? UINPUT_FILE_SIZE : FAKE_INPUT_RING_SIZE;
+ size_t mapping_size = virtual_pad ? UINPUT_FILE_SIZE : FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE;
if (ring_path.empty()) {
Logger::log("No input ring is configured for %s (slot %d)\n", event, slot);
errno = ENODEV;
@@ -651,9 +657,22 @@ open_fake_input_ring(const char *event, int flags) {
controller->uinput = description;
controller->mapping_size = mapping_size;
controller->generation = ring_generation(ring);
+ if (!virtual_pad) {
+ uint32_t pad_type = __atomic_load_n(
+ reinterpret_cast(static_cast(mapping) + FAKE_INPUT_RING_SIZE +
+ FAKE_INPUT_RING_PAD_TYPE_OFFSET),
+ __ATOMIC_ACQUIRE);
+ controller->mouse = (pad_type & PAD_TYPE_SET) && (pad_type & ~PAD_TYPE_SET) == PAD_TYPE_MOUSE;
+ }
SnapshotState snap;
- if (read_snapshot(ring, snap) && snap.generation == controller->generation)
- capture_keyframe(*controller, snap);
+ if (read_snapshot(ring, snap) && snap.generation == controller->generation) {
+ if (controller->mouse) {
+ controller->read_seq = snap.write_seq;
+ controller->needs_keyframe = false;
+ } else {
+ capture_keyframe(*controller, snap);
+ }
+ }
{
std::lock_guard guard(controller_mutex());
controller_map()[fd] = controller;
@@ -1156,7 +1175,8 @@ struct DeckImu {
uint32_t pad_type;
uint32_t latency;
};
-static_assert(offsetof(DeckImu, pad_type) == 44, "DeckImu::pad_type matches FakeInputWriter");
+static_assert(offsetof(DeckImu, pad_type) == FAKE_INPUT_RING_PAD_TYPE_OFFSET,
+ "DeckImu::pad_type matches FakeInputWriter and the ring reader");
static_assert(offsetof(DeckImu, latency) == 48, "DeckImu::latency matches FakeInputWriter");
static constexpr uint32_t LATENCY_CONTROLLER = 1, LATENCY_TOUCH = 2;
static constexpr int LOW_LATENCY_REPORT_INTERVAL_US = 1000;
@@ -1173,7 +1193,6 @@ struct DeckExtras {
uint32_t controls = 0;
};
static constexpr uint32_t DECK_IMU_MAGIC = 0x31554D49;
-static constexpr size_t DECK_IMU_BLOCK_SIZE = 64;
static_assert(sizeof(DeckImu) <= DECK_IMU_BLOCK_SIZE, "the IMU block is 64 bytes in the ring file");
struct TritonSharedData {
@@ -1222,7 +1241,6 @@ static constexpr int TRITON_REPORT_ID_BYTES = 1;
static constexpr int TRITON_STATE_BYTES = 45;
static constexpr int TRITON_REPORT_INTERVAL_US = 4000;
static constexpr int TRITON_FEATURE_TIMEOUT_MS = 500;
-// The app clears output_length once it has taken a report; a writer waits this long for that before overwriting.
static constexpr int TRITON_OUTPUT_TIMEOUT_MS = 50;
static constexpr const char *TRITON_NAME = "Steam Controller";
static constexpr const char *TRITON_SERIAL = "DROIDDECKSC01";
@@ -1270,10 +1288,6 @@ static bool fake_deck_enabled() {
return enabled == 1;
}
-static constexpr uint32_t PAD_TYPE_DECK = 0, PAD_TYPE_STEAM = 1, PAD_TYPE_XBOX = 2, PAD_TYPE_DS4 = 3,
- PAD_TYPE_DUALSENSE = 4, PAD_TYPE_LAST = PAD_TYPE_DUALSENSE;
-static constexpr uint32_t PAD_TYPE_SET = 0x80000000u;
-
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
static int type = -1;
if (type < 0) {
@@ -1408,6 +1422,12 @@ __attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const ch
if (strncmp(event, "event", 5) && strncmp(event, "js", 2)) return false;
int number = get_event_number(event);
if (number < 0 || number >= UINPUT_EVENT_BASE) return false;
+ if (number == MOUSE_EVENT_SLOT && !strncmp(event, "event", 5)) {
+ char *fake = from_real_to_fake_path(pathname);
+ bool exposed = fake && path_exists(fake);
+ free(fake);
+ return !exposed;
+ }
return number == 0 || !process_is_steam_client();
}
@@ -2650,9 +2670,6 @@ __attribute__((visibility("hidden"))) static int triton_get_feature(DeckHidraw &
static constexpr uint32_t TRITON_HWID = 72;
static constexpr uint32_t TRITON_FW_TIMESTAMP = 0x6AC686B3;
-// Steam compares the controller's firmware with TRITON_FW_TS in its bundled hardwareupdater.cfg (and blocks
-// with a required update below MUST_UPDATE_TRITON_FW_TS), so the emulated pad reports at least the build
-// Steam ships.
static uint32_t triton_fw_timestamp() {
static const uint32_t timestamp = [] {
std::vector roots;
@@ -3351,6 +3368,85 @@ static int copy_ioctl_bits(int op, void *destination, const unsigned char (&bits
return static_cast(size);
}
+static constexpr uint16_t MOUSE_VENDOR_ID = 0x1dd1;
+static constexpr uint16_t MOUSE_PRODUCT_ID = 0x0004;
+
+static int ioctl_mouse(int op, void *argp) {
+ int type = (op >> 8 & 0xFF);
+ int number = (op >> 0 & 0xFF);
+ if (type != 0x45) {
+ errno = EINVAL;
+ return -1;
+ }
+ switch (number) {
+ case 0x01: {
+ int version = 65536;
+ memcpy(argp, &version, sizeof(int));
+ return 0;
+ }
+ case 0x02: {
+ struct input_id id;
+ memset(&id, 0, sizeof(id));
+ id.bustype = 0x03;
+ id.vendor = MOUSE_VENDOR_ID;
+ id.product = MOUSE_PRODUCT_ID;
+ id.version = 1;
+ memcpy(argp, &id, sizeof(id));
+ return 0;
+ }
+ case 0x06:
+ if (argp && _IOC_SIZE(op)) snprintf(static_cast(argp), _IOC_SIZE(op), "DroidDeck Mouse");
+ return 0;
+ case 0x07:
+ if (argp && _IOC_SIZE(op)) snprintf(static_cast(argp), _IOC_SIZE(op), "usb-droiddeck/mouse");
+ return 0;
+ case 0x08:
+ if (argp && _IOC_SIZE(op)) static_cast(argp)[0] = '\0';
+ return 0;
+ case 0x09: {
+ unsigned char bitmask[(INPUT_PROP_MAX + 8) / 8] = {};
+ bitmask[INPUT_PROP_POINTER / 8] |= 1 << (INPUT_PROP_POINTER % 8);
+ return copy_ioctl_bits(op, argp, bitmask);
+ }
+ case 0x18: {
+ unsigned char bitmask[(KEY_MAX + 8) / 8] = {};
+ return copy_ioctl_bits(op, argp, bitmask);
+ }
+ case 0x20: {
+ unsigned char bitmask[(EV_MAX + 8) / 8] = {};
+ bitmask[EV_SYN / 8] |= 1 << (EV_SYN % 8);
+ bitmask[EV_KEY / 8] |= 1 << (EV_KEY % 8);
+ bitmask[EV_REL / 8] |= 1 << (EV_REL % 8);
+ bitmask[EV_MSC / 8] |= 1 << (EV_MSC % 8);
+ return copy_ioctl_bits(op, argp, bitmask);
+ }
+ case 0x21: {
+ unsigned char bitmask[(KEY_MAX + 8) / 8] = {};
+ for (int button = BTN_LEFT; button <= BTN_TASK; button++)
+ if (button <= BTN_MIDDLE || button == BTN_SIDE || button == BTN_EXTRA)
+ bitmask[button / 8] |= 1 << (button % 8);
+ return copy_ioctl_bits(op, argp, bitmask);
+ }
+ case 0x22: {
+ unsigned char bitmask[(REL_MAX + 8) / 8] = {};
+ for (uint16_t code : {REL_X, REL_Y, REL_WHEEL, REL_HWHEEL, REL_WHEEL_HI_RES, REL_HWHEEL_HI_RES})
+ bitmask[code / 8] |= 1 << (code % 8);
+ return copy_ioctl_bits(op, argp, bitmask);
+ }
+ case 0x23: {
+ unsigned char bitmask[(ABS_MAX + 8) / 8] = {};
+ return copy_ioctl_bits(op, argp, bitmask);
+ }
+ case 0x35: {
+ unsigned char bitmask[(FF_MAX + 8) / 8] = {};
+ return copy_ioctl_bits(op, argp, bitmask);
+ }
+ default:
+ errno = EINVAL;
+ return -1;
+ }
+}
+
static bool wait_snapshot(std::shared_ptr fake,
std::unique_lock &guard,
SnapshotState &snap) {
@@ -3417,6 +3513,13 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
int event_number = controller->second->slot;
const UinputDescription *made = controller->second->uinput;
+ if (controller->second->mouse) {
+ int result = ioctl_mouse(op, argp);
+ if (result >= 0) return result;
+ guard.unlock();
+ return forward_ioctl(fd, op, argp);
+ }
+
if (type == 0x45 && number == 0x1) {
Logger::log("Hooking ioctl EVIOCGVERSION for event %s\n", event);
int version = 65536;
@@ -3570,7 +3673,6 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
Logger::log("Hooking ioctl EVIOCGRAB for event %s\n", event);
return 0;
} else if (type == 0x6A && !strncmp(event, "event", 5)) {
- // Older SDL2 builds treat any JSIOCGNAME answer as a joydev node and skip EVIOCGID, then drop the pad as 0000:0000.
Logger::log("Rejecting joydev ioctl %d for event %s\n", number, event);
guard.unlock();
errno = EINVAL;
@@ -3680,6 +3782,12 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
if (fake.needs_keyframe || snap.resync_seq != fake.resync_seq ||
snap.write_seq < fake.read_seq ||
snap.write_seq - fake.read_seq > FAKE_INPUT_RING_CAPACITY) {
+ if (fake.mouse) {
+ fake.read_seq = snap.write_seq;
+ fake.resync_seq = snap.resync_seq;
+ fake.needs_keyframe = false;
+ continue;
+ }
capture_keyframe(fake, snap);
} else {
size_t events = std::min(requested, snap.write_seq - fake.read_seq);
diff --git a/app/src/main/cpp/framegen/ddfg/framegen.cpp b/app/src/main/cpp/framegen/ddfg/framegen.cpp
index 82d0a764b..5200f6b09 100644
--- a/app/src/main/cpp/framegen/ddfg/framegen.cpp
+++ b/app/src/main/cpp/framegen/ddfg/framegen.cpp
@@ -184,8 +184,9 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) {
VkExtent2D e = levelExtent(extent, l);
if (!makeImage(pyrA_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
if (!makeImage(pyrB_[l], e, VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
- if (!makeImage(flowLvl_[l], e, VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
}
+ for (int l = flowFinest_; l < kLevels; ++l)
+ if (!makeImage(flowLvl_[l], levelExtent(extent, l), VK_FORMAT_R16G16B16A16_SFLOAT, flowUsage)) return false;
pyrAs_.resize(kLevels);
for (int l = flowFinest_; l < kLevels; ++l)
if (!makeImage(pyrAs_[l], levelExtent(extent, l), VK_FORMAT_R32_SFLOAT, lumaUsage)) return false;
diff --git a/app/src/main/cpp/framegen/ddfg/record_impl.inc b/app/src/main/cpp/framegen/ddfg/record_impl.inc
index 554c05c7f..f366d9a9c 100644
--- a/app/src/main/cpp/framegen/ddfg/record_impl.inc
+++ b/app/src/main/cpp/framegen/ddfg/record_impl.inc
@@ -267,8 +267,6 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
pFlowReg_, flowRegA_, flowRegB_, gmSsbo_, kLevels, cfg_);
}
- // Every generation of one real frame is recorded into the same command buffer, so the flow
- // between prev and curr is computed once and each generation gets its own synth UBO and set.
if (reuseFlow && !g_scratch.flowReady) return;
if (!reuseFlow) {
bool gmEngaged = updateGlobalMotion(gmSlot, extent_);
@@ -439,7 +437,7 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
makeUbo(dd, dev, mp, sizeof(FlowRegUBO), S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
if (S.flowRegUboPtr) { FlowRegUBO fu{cfg.frDt, cfg.frLambda, cfg.frEdge, cfg.frEps}; std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu)); }
S.flowUbo.resize(kLevels); S.flowUboMem.resize(kLevels); S.flowUboPtr.resize(kLevels);
- for (int l = 0; l < kLevels; ++l) {
+ for (int l = fg->flowFinest(); l < kLevels; ++l) {
makeUbo(dd, dev, mp, sizeof(FlowUBO), S.flowUbo[l], S.flowUboMem[l], S.flowUboPtr[l]);
if (S.flowUboPtr[l]) { FlowUBO u{cfg.flowScale, (uint32_t)l, 0.6f, 1.6f}; std::memcpy(S.flowUboPtr[l], &u, sizeof(u)); }
}
@@ -464,13 +462,12 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
}
S.sFlow.resize(kLevels);
- for (int l = 0; l < kLevels; ++l) {
+ for (int l = fg->flowFinest(); l < kLevels; ++l) {
S.sFlow[l] = allocSet(dd, dev, pool, pFlow.setLayout);
int pred = (l + 1 < kLevels) ? l + 1 : l;
- VkImageView currLvl = (l >= fg->flowFinest()) ? pyrAs[l].view : pyrA[l].view;
wUbo(dd, dev, S.sFlow[l], 0, S.flowUbo[l], sizeof(FlowUBO));
wImg(dd, dev, S.sFlow[l], 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrB[l].view, samp, GEN);
- wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currLvl, samp, GEN);
+ wImg(dd, dev, S.sFlow[l], 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, pyrAs[l].view, samp, GEN);
wImg(dd, dev, S.sFlow[l], 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, flowLvl[pred].view, samp, GEN);
wImg(dd, dev, S.sFlow[l], 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowLvl[l].view, VK_NULL_HANDLE, GEN);
}
diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_dll.cpp b/app/src/main/cpp/framegen/lsfg/lsfg_dll.cpp
index 3a37f032a..f9ee32463 100644
--- a/app/src/main/cpp/framegen/lsfg/lsfg_dll.cpp
+++ b/app/src/main/cpp/framegen/lsfg/lsfg_dll.cpp
@@ -1,5 +1,4 @@
-// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS).
-// Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
+// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS). Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
#include "lsfg_dll.h"
#include "lsfg_dxbc.h"
diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_dll.h b/app/src/main/cpp/framegen/lsfg/lsfg_dll.h
index a20a6c631..81bf6781d 100644
--- a/app/src/main/cpp/framegen/lsfg/lsfg_dll.h
+++ b/app/src/main/cpp/framegen/lsfg/lsfg_dll.h
@@ -1,5 +1,4 @@
-// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS).
-// Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
+// LSFG from Camille LaVey / the Eden Emulator Project, following upstream lsfg-vk (PancakeTAS). Ported to WinNative and DroidDeck by @maxjivi05. GPL-3.0-or-later.
#pragma once
diff --git a/app/src/main/cpp/framegen/lsfg/lsfg_dxbc.h b/app/src/main/cpp/framegen/lsfg/lsfg_dxbc.h
index 17ba1876d..2f5286b26 100644
--- a/app/src/main/cpp/framegen/lsfg/lsfg_dxbc.h
+++ b/app/src/main/cpp/framegen/lsfg/lsfg_dxbc.h
@@ -1,5 +1,4 @@
#pragma once
-// DXVK's dxbc subset is zlib licensed; vendored under cpp/thirdparty/dxbc.
#include
#include
diff --git a/app/src/main/cpp/gpuclock/kgsl_busy.c b/app/src/main/cpp/gpuclock/kgsl_busy.c
new file mode 100644
index 000000000..a61114793
--- /dev/null
+++ b/app/src/main/cpp/gpuclock/kgsl_busy.c
@@ -0,0 +1,121 @@
+// Whole-GPU busy share without root on Adreno (KGSL) devices whose kgsl sysfs is blocked for apps: a thread
+// samples the memstore ringbuffer timestamps (kgsl_busy.h) once a millisecond while running.
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "../adrenotools/src/hook/kgsl.h"
+#include "kgsl_busy.h"
+
+#define SAMPLE_NS 1000000L
+
+struct reader {
+ int fd;
+ void *map;
+ size_t bytes;
+ int first;
+ uint32_t last[KGSL_BUSY_SLOTS];
+ pthread_mutex_t lock;
+ pthread_t thread;
+ int thread_on;
+ atomic_int run;
+ atomic_uint_fast64_t busy, samples, moves;
+};
+
+static void *sample_loop(void *arg) {
+ struct reader *r = arg;
+ const struct timespec gap = {0, SAMPLE_NS};
+ while (atomic_load(&r->run)) {
+ int moved = 0;
+ int busy = kgsl_busy_sample(r->map, r->first, r->last, &moved);
+ if (busy) atomic_fetch_add(&r->busy, 1);
+ if (moved) atomic_fetch_add(&r->moves, 1);
+ atomic_fetch_add(&r->samples, 1);
+ nanosleep(&gap, NULL);
+ }
+ return NULL;
+}
+
+static void reader_run(struct reader *r, int on) {
+ pthread_mutex_lock(&r->lock);
+ if (on && !r->thread_on) {
+ atomic_store(&r->run, 1);
+ if (pthread_create(&r->thread, NULL, sample_loop, r) == 0) r->thread_on = 1;
+ else atomic_store(&r->run, 0);
+ } else if (!on && r->thread_on) {
+ atomic_store(&r->run, 0);
+ pthread_join(r->thread, NULL);
+ r->thread_on = 0;
+ }
+ pthread_mutex_unlock(&r->lock);
+}
+
+static void reader_close(struct reader *r) {
+ if (!r) return;
+ reader_run(r, 0);
+ if (r->map && r->map != MAP_FAILED) munmap(r->map, r->bytes);
+ if (r->fd >= 0) close(r->fd);
+ pthread_mutex_destroy(&r->lock);
+ free(r);
+}
+
+// Returns 0 or a negative errno; *out is set on success.
+static int reader_open(struct reader **out) {
+ struct reader *r = calloc(1, sizeof(*r));
+ if (!r) return -ENOMEM;
+ pthread_mutex_init(&r->lock, NULL);
+ r->fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
+ if (r->fd < 0) { int e = -errno; reader_close(r); return e; }
+ struct kgsl_shadowprop shadow;
+ memset(&shadow, 0, sizeof(shadow));
+ struct kgsl_device_getproperty prop = {.type = KGSL_PROP_DEVICE_SHADOW, .value = &shadow, .sizebytes = sizeof(shadow)};
+ if (ioctl(r->fd, IOCTL_KGSL_DEVICE_GETPROPERTY, &prop)) { int e = -errno; reader_close(r); return e; }
+ r->bytes = shadow.size;
+ r->first = kgsl_busy_first_slot(shadow.size);
+ if (r->first < 0) { reader_close(r); return -ERANGE; }
+ r->map = mmap(NULL, r->bytes, PROT_READ, MAP_SHARED, r->fd, (off_t)shadow.gpuaddr);
+ if (r->map == MAP_FAILED) { int e = -errno; reader_close(r); return e; }
+ int moved = 0, started = 0;
+ kgsl_busy_sample(r->map, r->first, r->last, &moved);
+ for (int i = 0; i < KGSL_BUSY_SLOTS; i++) started |= r->last[i] != 0;
+ if (!started) { reader_close(r); return -ENODATA; }
+ *out = r;
+ return 0;
+}
+
+#ifndef KGSL_BUSY_NO_JNI
+#include
+
+JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeOpen(JNIEnv *env, jclass cls, jintArray error) {
+ struct reader *r = NULL;
+ int e = reader_open(&r);
+ if (e && error && (*env)->GetArrayLength(env, error) > 0) {
+ jint v = e;
+ (*env)->SetIntArrayRegion(env, error, 0, 1, &v);
+ }
+ return e ? 0 : (jlong)(intptr_t)r;
+}
+
+JNIEXPORT void JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeRun(JNIEnv *env, jclass cls, jlong handle, jboolean on) {
+ if (handle) reader_run((struct reader *)(intptr_t)handle, on ? 1 : 0);
+}
+
+JNIEXPORT jboolean JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeRead(JNIEnv *env, jclass cls, jlong handle, jlongArray out) {
+ if (!handle || !out || (*env)->GetArrayLength(env, out) < 3) return JNI_FALSE;
+ struct reader *r = (struct reader *)(intptr_t)handle;
+ jlong v[3] = {(jlong)atomic_load(&r->busy), (jlong)atomic_load(&r->samples), (jlong)atomic_load(&r->moves)};
+ (*env)->SetLongArrayRegion(env, out, 0, 3, v);
+ return JNI_TRUE;
+}
+
+JNIEXPORT void JNICALL Java_com_droiddeck_launcher_session_KgslBusy_nativeClose(JNIEnv *env, jclass cls, jlong handle) {
+ reader_close((struct reader *)(intptr_t)handle);
+}
+#endif
diff --git a/app/src/main/cpp/gpuclock/kgsl_busy.h b/app/src/main/cpp/gpuclock/kgsl_busy.h
new file mode 100644
index 000000000..2179cf533
--- /dev/null
+++ b/app/src/main/cpp/gpuclock/kgsl_busy.h
@@ -0,0 +1,37 @@
+#ifndef DROIDDECK_KGSL_BUSY_H
+#define DROIDDECK_KGSL_BUSY_H
+// kgsl lets any client map its memstore read-only (KGSL_PROP_DEVICE_SHADOW). The CP writes a ringbuffer's
+// start-of-pipe timestamp there before each submission's command buffers and its end-of-pipe timestamp after them
+// (adreno_gen7_ringbuffer.c gen7_ringbuffer_addcmds), so start != end means that ringbuffer has work on the GPU.
+// Ringbuffer entries start at KGSL_MEMSTORE_MAX: entries - 2 - 4 levels, or entries - 1 - 4 on kernels without the
+// LPAC slot. Entries - 6 .. entries - 2 cover both; a context entry in that range follows the same start/end rule.
+#include
+#include
+
+#define KGSL_BUSY_ENTRY_WORDS 10
+#define KGSL_BUSY_SOP 0
+#define KGSL_BUSY_EOP 2
+#define KGSL_BUSY_SLOTS 5
+
+static inline int kgsl_busy_first_slot(size_t bytes) {
+ size_t entries = bytes / (KGSL_BUSY_ENTRY_WORDS * sizeof(uint32_t));
+ return entries < 8 ? -1 : (int)(entries - 6);
+}
+
+// 1 when a watched slot has a submission between its start and end timestamps. *moved is set when a start
+// timestamp differs from last[], which then holds the new ones.
+static inline int kgsl_busy_sample(const volatile uint32_t *memstore, int first, uint32_t last[KGSL_BUSY_SLOTS], int *moved) {
+ int busy = 0;
+ for (int i = 0; i < KGSL_BUSY_SLOTS; i++) {
+ const volatile uint32_t *entry = memstore + (size_t)(first + i) * KGSL_BUSY_ENTRY_WORDS;
+ uint32_t sop = entry[KGSL_BUSY_SOP], eop = entry[KGSL_BUSY_EOP];
+ if (sop != eop) busy = 1;
+ if (sop != last[i]) {
+ *moved = 1;
+ last[i] = sop;
+ }
+ }
+ return busy;
+}
+
+#endif
diff --git a/app/src/main/cpp/gpuclock/kgsl_clock.c b/app/src/main/cpp/gpuclock/kgsl_clock.c
new file mode 100644
index 000000000..b021208b4
--- /dev/null
+++ b/app/src/main/cpp/gpuclock/kgsl_clock.c
@@ -0,0 +1,156 @@
+// GPU clock without root on Adreno (KGSL) devices whose kgsl sysfs is blocked for apps.
+//
+// kgsl lets any app reserve a performance counter (IOCTL_KGSL_PERFCOUNTER_GET) but refuses to read it back while
+// /sys/class/kgsl/kgsl-3d0/perfcounter is 0, and clears the counters whenever the GPU switches to another process.
+// So the counter is read by the GPU itself: a small command buffer copies CP_ALWAYS_ON_COUNTER (19.2 MHz) and the
+// RBBM ALWAYS_COUNT counter (GPU core cycles) to memory, runs a block of NOP packets, and copies both again.
+// clock = cycles / always-on ticks * 19.2 MHz. Both reads sit in one command buffer, so a counter clear between
+// them only happens if the buffer is preempted; such samples fail the range checks and are dropped.
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "../adrenotools/src/hook/kgsl.h"
+
+#define CP_TYPE7_PKT 0x70000000u
+#define CP_NOP 0x10u
+#define CP_REG_TO_MEM 0x3eu
+#define CP_ALWAYS_ON_COUNTER 0x980u
+#define RBBM_ALWAYS_COUNT 0u
+// gen7 CP protection marks registers 0x000-0x4ff readable by command buffers (adreno-gpulist.h); a counter
+// kgsl places anywhere else is not read.
+#define READABLE_LAST 0x4ffu
+#define XO_HZ 19200000.0
+#define NOP_DWORDS 0x3fffu
+#define NOP_BLOCKS 4
+
+struct sampler {
+ int fd;
+ unsigned context;
+ unsigned counter_reg;
+ struct kgsl_gpumem_alloc_id ib, out;
+ uint32_t *ib_map;
+ volatile uint64_t *out_map;
+ size_t ib_bytes;
+};
+
+static unsigned odd_parity(unsigned v) {
+ v ^= v >> 16;
+ v ^= v >> 8;
+ v ^= v >> 4;
+ v &= 0xf;
+ return (~0x6996u >> v) & 1u;
+}
+
+static uint32_t pkt7(unsigned op, unsigned count) {
+ return CP_TYPE7_PKT | count | odd_parity(count) << 15 | (op & 0x7f) << 16 | odd_parity(op) << 23;
+}
+
+static void sampler_close(struct sampler *s) {
+ if (!s) return;
+ if (s->fd >= 0) {
+ if (s->ib_map && s->ib_map != MAP_FAILED) munmap(s->ib_map, s->ib.mmapsize);
+ if (s->out_map && s->out_map != MAP_FAILED) munmap((void *)s->out_map, s->out.mmapsize);
+ if (s->ib.id) { struct kgsl_gpumem_free_id f = {.id = s->ib.id}; ioctl(s->fd, IOCTL_KGSL_GPUMEM_FREE_ID, &f); }
+ if (s->out.id) { struct kgsl_gpumem_free_id f = {.id = s->out.id}; ioctl(s->fd, IOCTL_KGSL_GPUMEM_FREE_ID, &f); }
+ if (s->context) { struct kgsl_drawctxt_destroy d = {.drawctxt_id = s->context}; ioctl(s->fd, IOCTL_KGSL_DRAWCTXT_DESTROY, &d); }
+ if (s->counter_reg) {
+ struct kgsl_perfcounter_put p = {.groupid = KGSL_PERFCOUNTER_GROUP_RBBM, .countable = RBBM_ALWAYS_COUNT};
+ ioctl(s->fd, IOCTL_KGSL_PERFCOUNTER_PUT, &p);
+ }
+ close(s->fd);
+ }
+ free(s);
+}
+
+static void emit_reads(struct sampler *s, size_t *n, unsigned pass) {
+ const unsigned regs[2] = {CP_ALWAYS_ON_COUNTER, s->counter_reg};
+ for (unsigned k = 0; k < 2; k++) {
+ uint64_t dst = s->out.gpuaddr + (uint64_t)(pass * 2 + k) * sizeof(uint64_t);
+ s->ib_map[(*n)++] = pkt7(CP_REG_TO_MEM, 3);
+ s->ib_map[(*n)++] = regs[k] | (2u << 18) | (1u << 30); // two dwords, 64-bit read
+ s->ib_map[(*n)++] = (uint32_t)dst;
+ s->ib_map[(*n)++] = (uint32_t)(dst >> 32);
+ }
+}
+
+// Returns 0 or a negative errno; *out is set on success.
+static int sampler_open(struct sampler **out) {
+ struct sampler *s = calloc(1, sizeof(*s));
+ if (!s) return -ENOMEM;
+ s->fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
+ if (s->fd < 0) { int e = -errno; s->fd = -1; sampler_close(s); return e; }
+ struct kgsl_perfcounter_get get = {.groupid = KGSL_PERFCOUNTER_GROUP_RBBM, .countable = RBBM_ALWAYS_COUNT};
+ if (ioctl(s->fd, IOCTL_KGSL_PERFCOUNTER_GET, &get)) { int e = -errno; sampler_close(s); return e; }
+ s->counter_reg = get.offset;
+ if (!get.offset || get.offset > READABLE_LAST) { sampler_close(s); return -ERANGE; }
+ struct kgsl_drawctxt_create ctx = {.flags = KGSL_CONTEXT_NO_GMEM_ALLOC | KGSL_CONTEXT_PREAMBLE};
+ if (ioctl(s->fd, IOCTL_KGSL_DRAWCTXT_CREATE, &ctx)) { int e = -errno; sampler_close(s); return e; }
+ s->context = ctx.drawctxt_id;
+ s->ib_bytes = (16 + NOP_BLOCKS * (NOP_DWORDS + 1)) * sizeof(uint32_t);
+ s->ib.size = (s->ib_bytes + 4095) & ~(size_t)4095;
+ s->out.size = 4096;
+ if (ioctl(s->fd, IOCTL_KGSL_GPUMEM_ALLOC_ID, &s->ib)) { int e = -errno; s->ib.id = 0; sampler_close(s); return e; }
+ if (ioctl(s->fd, IOCTL_KGSL_GPUMEM_ALLOC_ID, &s->out)) { int e = -errno; s->out.id = 0; sampler_close(s); return e; }
+ s->ib_map = mmap(NULL, s->ib.mmapsize, PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, (off_t)s->ib.id << 12);
+ s->out_map = mmap(NULL, s->out.mmapsize, PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, (off_t)s->out.id << 12);
+ if (s->ib_map == MAP_FAILED || s->out_map == MAP_FAILED) { int e = -errno; sampler_close(s); return e; }
+ size_t n = 0;
+ emit_reads(s, &n, 0);
+ for (unsigned b = 0; b < NOP_BLOCKS; b++) {
+ s->ib_map[n++] = pkt7(CP_NOP, NOP_DWORDS);
+ memset(&s->ib_map[n], 0, NOP_DWORDS * sizeof(uint32_t));
+ n += NOP_DWORDS;
+ }
+ emit_reads(s, &n, 1);
+ s->ib_bytes = n * sizeof(uint32_t);
+ *out = s;
+ return 0;
+}
+
+// MHz, or a negative value: -errno from kgsl, or -1000 for a sample that failed the range checks.
+static int sampler_mhz(struct sampler *s) {
+ for (int i = 0; i < 4; i++) s->out_map[i] = 0;
+ struct kgsl_command_object cmd = {.gpuaddr = s->ib.gpuaddr, .size = s->ib_bytes, .flags = KGSL_CMDLIST_IB};
+ struct kgsl_gpu_command submit = {
+ .cmdlist = (uint64_t)(uintptr_t)&cmd, .cmdsize = sizeof(cmd), .numcmds = 1, .context_id = s->context,
+ };
+ if (ioctl(s->fd, IOCTL_KGSL_GPU_COMMAND, &submit)) return -errno;
+ struct kgsl_device_waittimestamp_ctxtid wait = {.context_id = s->context, .timestamp = submit.timestamp, .timeout = 250};
+ if (ioctl(s->fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait)) return -errno;
+ uint64_t xo0 = s->out_map[0], cyc0 = s->out_map[1], xo1 = s->out_map[2], cyc1 = s->out_map[3];
+ if (xo1 <= xo0 || cyc1 <= cyc0) return -1000;
+ uint64_t xo = xo1 - xo0, cycles = cyc1 - cyc0;
+ // 5 us .. 50 ms of always-on time, and a clock between 50 MHz and 2 GHz.
+ if (xo < 96 || xo > 960000) return -1000;
+ double mhz = (double)cycles / (double)xo * XO_HZ / 1e6;
+ if (mhz < 50 || mhz > 2000) return -1000;
+ return (int)(mhz + 0.5);
+}
+
+#ifndef KGSL_CLOCK_NO_JNI
+#include
+
+JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_session_KgslClock_nativeOpen(JNIEnv *env, jclass cls, jintArray error) {
+ struct sampler *s = NULL;
+ int r = sampler_open(&s);
+ if (r && error && (*env)->GetArrayLength(env, error) > 0) {
+ jint e = r;
+ (*env)->SetIntArrayRegion(env, error, 0, 1, &e);
+ }
+ return r ? 0 : (jlong)(intptr_t)s;
+}
+
+JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_session_KgslClock_nativeSample(JNIEnv *env, jclass cls, jlong handle) {
+ return handle ? sampler_mhz((struct sampler *)(intptr_t)handle) : -EBADF;
+}
+
+JNIEXPORT void JNICALL Java_com_droiddeck_launcher_session_KgslClock_nativeClose(JNIEnv *env, jclass cls, jlong handle) {
+ sampler_close((struct sampler *)(intptr_t)handle);
+}
+#endif
diff --git a/app/src/main/cpp/questxr/gpu_frames.h b/app/src/main/cpp/questxr/gpu_frames.h
index dc69dbbfb..77d7a6db6 100644
--- a/app/src/main/cpp/questxr/gpu_frames.h
+++ b/app/src/main/cpp/questxr/gpu_frames.h
@@ -76,7 +76,6 @@ public:
}
lastFrame_ = frame.header.frame_id;
if (state == XrGpuFrameState::Stale) {
- // No GPU read was submitted, so the producer can safely reclaim a dropped frame.
dropped_++;
if (!xr_gpu_send(peer_, &frame.header.frame_id, sizeof(frame.header.frame_id))) Disconnect();
return false;
@@ -88,7 +87,6 @@ public:
glBindImageTexture(0, raw_, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA8);
glDispatchCompute((width_ + 7) / 8, (height_ + 7) / 8, 1);
glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
- // The producer may overwrite this slot only after the native GPU has finished reading it.
glFinish();
if (glGetError() != GL_NO_ERROR) { rejected_++; Disconnect(); return false; }
if (!xr_gpu_send(peer_, &frame.header.frame_id, sizeof(frame.header.frame_id))) Disconnect();
diff --git a/app/src/main/cpp/venc/venc_proto.h b/app/src/main/cpp/venc/venc_proto.h
index 962257711..e69bbd822 100644
--- a/app/src/main/cpp/venc/venc_proto.h
+++ b/app/src/main/cpp/venc/venc_proto.h
@@ -3,13 +3,9 @@
#include
-/* SOCK_SEQPACKET between the guest's Remote Play hooks and the app: the emulated /dev/video-enc0 and
- * MediaCodec encoder, and remote touches. A config carries the buffer memfds (inputs first) as SCM_RIGHTS;
- * every frame gets one reply, touches get none. */
-
#define VENC_MAX_BUFFERS 16
-enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5 };
+enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5, VDEC_CONFIG = 6, VDEC_CAPTURE = 7, VDEC_PACKET = 8, VDEC_RESULT = 9 };
enum venc_touch_action { VENC_TOUCH_DOWN = 0, VENC_TOUCH_MOVE = 1, VENC_TOUCH_UP = 2 };
enum venc_codec { VENC_H264 = 0, VENC_HEVC = 1 };
@@ -45,11 +41,36 @@ struct venc_bitrate {
uint32_t bitrate;
};
-/* Remote Play's touch-as-mouse turned back into a touch; x and y are fractions of the screen in 1/65535. */
struct venc_touch {
uint32_t type;
uint32_t action;
uint32_t x, y;
};
+struct vdec_config {
+ uint32_t type;
+ uint32_t codec;
+ uint32_t width, height;
+ uint32_t stride, rows;
+ uint32_t bitstreams, bitstream_size;
+};
+
+struct vdec_capture {
+ uint32_t type;
+ uint32_t index;
+ uint32_t size;
+};
+
+struct vdec_packet {
+ uint32_t type;
+ uint32_t input, bytes, capture;
+ int64_t pts_us;
+};
+
+struct vdec_result {
+ uint32_t type;
+ int32_t status;
+ uint32_t frame;
+};
+
#endif
diff --git a/app/src/main/cpp/venc/venc_server.cpp b/app/src/main/cpp/venc/venc_server.cpp
index be484c898..fd3a9ad13 100644
--- a/app/src/main/cpp/venc/venc_server.cpp
+++ b/app/src/main/cpp/venc/venc_server.cpp
@@ -3,6 +3,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -11,6 +12,7 @@
#include
#include
+#include
#include
#include
#include
@@ -31,8 +33,8 @@ struct Mapping {
constexpr int32_t kColorFormatYuv420SemiPlanar = 21;
constexpr uint32_t kBufferFlagKeyFrame = 1;
constexpr uint32_t kBufferFlagCodecConfig = 2;
-constexpr int kTouchWidth = 1920, kTouchHeight = 1080; // InputSpace.kt
-constexpr int kRemoteTouchId = 31; // the compositor's last touch slot (MAX_TOUCH_POINTS 32)
+constexpr int kTouchWidth = 1920, kTouchHeight = 1080;
+constexpr int kRemoteTouchId = 31;
int32_t avc_profile(int32_t v4l2) {
switch (v4l2) {
@@ -45,6 +47,218 @@ int32_t avc_profile(int32_t v4l2) {
}
}
+struct DmaBufSync {
+ uint64_t flags;
+};
+constexpr unsigned long kDmaBufIoctlSync = _IOW('b', 0, DmaBufSync);
+constexpr uint64_t kDmaBufSyncWrite = 2, kDmaBufSyncStart = 0, kDmaBufSyncEnd = 4;
+constexpr int32_t kColorFormatYuv420Planar = 19;
+
+class Decoder {
+public:
+ ~Decoder() { release(); }
+
+ void release() {
+ if (codec_) {
+ AMediaCodec_stop(codec_);
+ AMediaCodec_delete(codec_);
+ codec_ = nullptr;
+ }
+ if (bitstream_) munmap((void *)bitstream_, bitstream_size_);
+ bitstream_ = nullptr;
+ for (auto &c : captures_) drop(c);
+ }
+
+ bool configure(const vdec_config &c, int fd) {
+ release();
+ if (c.width < 16 || c.height < 16 || c.stride < c.width || c.rows < c.height || c.bitstreams == 0 ||
+ c.bitstreams > VENC_MAX_BUFFERS || c.bitstream_size == 0) {
+ LOG("bad decoder config: %ux%u stride %u rows %u, %u bitstreams", c.width, c.height, c.stride, c.rows,
+ c.bitstreams);
+ return false;
+ }
+ bitstream_size_ = (size_t)c.bitstreams * c.bitstream_size;
+ void *p = mmap(nullptr, bitstream_size_, PROT_READ, MAP_SHARED, fd, 0);
+ if (p == MAP_FAILED) {
+ LOG("could not map the bitstream buffers: %s", strerror(errno));
+ return false;
+ }
+ bitstream_ = (const uint8_t *)p;
+ config_ = c;
+ codec_ = create(c, true);
+ if (!codec_) codec_ = create(c, false);
+ if (!codec_) {
+ LOG("no %s decoder for %ux%u", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height);
+ release();
+ return false;
+ }
+ src_stride_ = (int32_t)c.width;
+ src_rows_ = (int32_t)c.height;
+ src_width_ = (int32_t)c.width;
+ src_height_ = (int32_t)c.height;
+ src_planar_ = false;
+ shown_ = false;
+ using GetName = media_status_t (*)(AMediaCodec *, char **);
+ using ReleaseName = void (*)(AMediaCodec *, char *);
+ static auto get_name = (GetName)dlsym(RTLD_DEFAULT, "AMediaCodec_getName");
+ static auto release_name = (ReleaseName)dlsym(RTLD_DEFAULT, "AMediaCodec_releaseName");
+ char *name = nullptr;
+ if (get_name && get_name(codec_, &name) != AMEDIA_OK) name = nullptr;
+ LOG("decoding %s %ux%u with %s", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height,
+ name ? name : "MediaCodec");
+ if (name && release_name) release_name(codec_, name);
+ return true;
+ }
+
+ void capture(const vdec_capture &c, int fd) {
+ if (c.index >= VENC_MAX_BUFFERS) {
+ close(fd);
+ return;
+ }
+ Capture &cap = captures_[c.index];
+ drop(cap);
+ void *p = mmap(nullptr, c.size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ if (p == MAP_FAILED) {
+ LOG("could not map capture buffer %u: %s", c.index, strerror(errno));
+ close(fd);
+ return;
+ }
+ cap = {fd, (uint8_t *)p, c.size};
+ }
+
+ bool decode(const vdec_packet &p, bool *frame) {
+ *frame = false;
+ if (!codec_ || p.capture >= VENC_MAX_BUFFERS || !captures_[p.capture].data || p.input >= config_.bitstreams ||
+ p.bytes == 0 || p.bytes > config_.bitstream_size)
+ return false;
+ auto start = std::chrono::steady_clock::now();
+ ssize_t in = AMediaCodec_dequeueInputBuffer(codec_, 20000);
+ if (in < 0) return false;
+ size_t capacity = 0;
+ uint8_t *dst = AMediaCodec_getInputBuffer(codec_, (size_t)in, &capacity);
+ if (!dst || capacity < p.bytes) {
+ AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, 0, 0, 0);
+ return false;
+ }
+ memcpy(dst, bitstream_ + (size_t)p.input * config_.bitstream_size, p.bytes);
+ if (AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, p.bytes, (uint64_t)std::max(p.pts_us, 0), 0) !=
+ AMEDIA_OK)
+ return false;
+ auto wait = std::chrono::milliseconds(shown_ ? 25 : 250);
+ while (std::chrono::steady_clock::now() - start < wait) {
+ AMediaCodecBufferInfo info;
+ ssize_t o = AMediaCodec_dequeueOutputBuffer(codec_, &info, 2000);
+ if (o == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
+ read_format();
+ continue;
+ }
+ if (o < 0) continue;
+ size_t size = 0;
+ uint8_t *data = AMediaCodec_getOutputBuffer(codec_, (size_t)o, &size);
+ if (data && info.size > 0 && (size_t)info.offset + (size_t)info.size <= size)
+ *frame = copy(data + info.offset, (size_t)info.size, captures_[p.capture]) || *frame;
+ AMediaCodec_releaseOutputBuffer(codec_, (size_t)o, false);
+ if (info.presentationTimeUs >= p.pts_us) break;
+ }
+ shown_ = shown_ || *frame;
+ return true;
+ }
+
+private:
+ struct Capture {
+ int fd = -1;
+ uint8_t *data = nullptr;
+ size_t size = 0;
+ };
+
+ static void drop(Capture &c) {
+ if (c.data) munmap(c.data, c.size);
+ if (c.fd >= 0) close(c.fd);
+ c = Capture();
+ }
+
+ AMediaCodec *create(const vdec_config &c, bool low_latency) {
+ const char *mime = c.codec == VENC_HEVC ? "video/hevc" : "video/avc";
+ AMediaCodec *codec = AMediaCodec_createDecoderByType(mime);
+ if (!codec) return nullptr;
+ AMediaFormat *f = AMediaFormat_new();
+ AMediaFormat_setString(f, AMEDIAFORMAT_KEY_MIME, mime);
+ AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_WIDTH, (int32_t)c.width);
+ AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_HEIGHT, (int32_t)c.height);
+ AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, kColorFormatYuv420SemiPlanar);
+ AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, (int32_t)c.bitstream_size);
+ if (low_latency) {
+ AMediaFormat_setInt32(f, "low-latency", 1);
+ AMediaFormat_setInt32(f, "vendor.qti-ext-dec-low-latency.enable", 1);
+ AMediaFormat_setInt32(f, "vendor.qti-ext-dec-picture-order.enable", 1);
+ AMediaFormat_setInt32(f, "priority", 0);
+ AMediaFormat_setFloat(f, "operating-rate", 120.0f);
+ }
+ media_status_t s = AMediaCodec_configure(codec, f, nullptr, nullptr, 0);
+ AMediaFormat_delete(f);
+ if (s == AMEDIA_OK) s = AMediaCodec_start(codec);
+ if (s != AMEDIA_OK) {
+ AMediaCodec_delete(codec);
+ return nullptr;
+ }
+ return codec;
+ }
+
+ void read_format() {
+ AMediaFormat *f = AMediaCodec_getOutputFormat(codec_);
+ if (!f) return;
+ int32_t v;
+ if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_WIDTH, &v) && v > 0) src_width_ = v;
+ if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_HEIGHT, &v) && v > 0) src_height_ = v;
+ src_stride_ = AMediaFormat_getInt32(f, "stride", &v) && v >= src_width_ ? v : src_width_;
+ src_rows_ = AMediaFormat_getInt32(f, "slice-height", &v) && v >= src_height_ ? v : src_height_;
+ src_planar_ = AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, &v) && v == kColorFormatYuv420Planar;
+ LOG("decoder output %dx%d stride %d rows %d %s", src_width_, src_height_, src_stride_, src_rows_,
+ src_planar_ ? "planar" : "semi-planar");
+ AMediaFormat_delete(f);
+ }
+
+ bool copy(const uint8_t *src, size_t size, const Capture &cap) {
+ size_t luma = (size_t)src_stride_ * src_rows_;
+ size_t chroma = src_planar_ ? 2 * (size_t)(src_stride_ / 2) * (src_rows_ / 2) : (size_t)src_stride_ * (src_rows_ / 2);
+ if (size < luma + chroma) return false;
+ uint32_t w = std::min((uint32_t)src_width_, config_.stride);
+ uint32_t h = std::min((uint32_t)src_height_, config_.rows);
+ if ((size_t)config_.stride * config_.rows * 3 / 2 > cap.size) return false;
+ DmaBufSync sync = {kDmaBufSyncStart | kDmaBufSyncWrite};
+ ioctl(cap.fd, kDmaBufIoctlSync, &sync);
+ uint8_t *y = cap.data, *uv = cap.data + (size_t)config_.stride * config_.rows;
+ for (uint32_t row = 0; row < h; row++)
+ memcpy(y + (size_t)row * config_.stride, src + (size_t)row * src_stride_, w);
+ const uint8_t *su = src + luma;
+ for (uint32_t row = 0; row < h / 2; row++) {
+ uint8_t *d = uv + (size_t)row * config_.stride;
+ if (!src_planar_) {
+ memcpy(d, su + (size_t)row * src_stride_, w & ~1u);
+ continue;
+ }
+ const uint8_t *u = su + (size_t)row * (src_stride_ / 2);
+ const uint8_t *vv = su + (size_t)(src_stride_ / 2) * (src_rows_ / 2) + (size_t)row * (src_stride_ / 2);
+ for (uint32_t x = 0; x < w / 2; x++) {
+ d[2 * x] = u[x];
+ d[2 * x + 1] = vv[x];
+ }
+ }
+ sync.flags = kDmaBufSyncEnd | kDmaBufSyncWrite;
+ ioctl(cap.fd, kDmaBufIoctlSync, &sync);
+ return true;
+ }
+
+ AMediaCodec *codec_ = nullptr;
+ vdec_config config_ = {};
+ const uint8_t *bitstream_ = nullptr;
+ size_t bitstream_size_ = 0;
+ Capture captures_[VENC_MAX_BUFFERS];
+ int32_t src_width_ = 0, src_height_ = 0, src_stride_ = 0, src_rows_ = 0;
+ bool src_planar_ = false;
+ bool shown_ = false;
+};
+
class Session {
public:
explicit Session(int fd) : fd_(fd) {}
@@ -85,6 +299,24 @@ public:
memcpy(&b, buf, sizeof b);
set_bitrate(b.bitrate);
for (int i = 0; i < nfds; i++) close(fds[i]);
+ } else if (type == VDEC_CONFIG && n == (ssize_t)sizeof(vdec_config)) {
+ vdec_config c;
+ memcpy(&c, buf, sizeof c);
+ bool ok = nfds == 1 && decoder_.configure(c, fds[0]);
+ for (int i = 0; i < nfds; i++) close(fds[i]);
+ decoded(ok ? 0 : -1, false);
+ } else if (type == VDEC_CAPTURE && n == (ssize_t)sizeof(vdec_capture)) {
+ vdec_capture c;
+ memcpy(&c, buf, sizeof c);
+ if (nfds == 1) decoder_.capture(c, fds[0]);
+ else for (int i = 0; i < nfds; i++) close(fds[i]);
+ } else if (type == VDEC_PACKET && n == (ssize_t)sizeof(vdec_packet)) {
+ vdec_packet p;
+ memcpy(&p, buf, sizeof p);
+ bool frame = false;
+ bool ok = decoder_.decode(p, &frame);
+ for (int i = 0; i < nfds; i++) close(fds[i]);
+ decoded(ok ? 0 : -1, frame);
} else {
LOG("unexpected message %u of %zd bytes; closing", type, n);
for (int i = 0; i < nfds; i++) close(fds[i]);
@@ -117,7 +349,13 @@ private:
send(fd_, &d, sizeof d, MSG_NOSIGNAL);
}
+ void decoded(int32_t status, bool frame) {
+ vdec_result r = {VDEC_RESULT, status, frame ? 1u : 0u};
+ send(fd_, &r, sizeof r, MSG_NOSIGNAL);
+ }
+
void release() {
+ decoder_.release();
if (codec_) {
AMediaCodec_stop(codec_);
AMediaCodec_delete(codec_);
@@ -292,6 +530,7 @@ private:
int32_t dst_stride_ = 0, dst_rows_ = 0;
std::vector inputs_, outputs_;
std::vector header_;
+ Decoder decoder_;
};
std::atomic g_listener{-1};
@@ -310,7 +549,7 @@ void serve(int listener) {
}
}
-} // namespace
+}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_droiddeck_launcher_session_VideoEncodeBridge_nativeStart(JNIEnv *env, jobject, jstring jpath) {
diff --git a/app/src/main/cpp/viture/display_modes.h b/app/src/main/cpp/viture/display_modes.h
index 3a78e03ae..b6b2288e2 100644
--- a/app/src/main/cpp/viture/display_modes.h
+++ b/app/src/main/cpp/viture/display_modes.h
@@ -1,20 +1,18 @@
#pragma once
-// Our controller uses the standard display-mode vocabulary, even for Beast.
-// Native mode reuses some numbers with different meanings; never pass them through.
namespace droiddeck::viture {
constexpr int to_native_mode(int standard) {
switch (standard) {
- case 0x31: return 0x31; // 1080p 60
- case 0x33: return 0x32; // 1080p 90
- case 0x34: return 0x33; // 1080p 120
- case 0x32: return 0x37; // 1080p SBS 60
- case 0x35: return 0x38; // 1080p SBS 90
- case 0x41: return 0x34; // 1200p 60
- case 0x43: return 0x35; // 1200p 90
- case 0x44: return 0x36; // 1200p 120
- case 0x42: return 0x3a; // 1200p SBS 60
- case 0x45: return 0x3b; // 1200p SBS 90
+ case 0x31: return 0x31;
+ case 0x33: return 0x32;
+ case 0x34: return 0x33;
+ case 0x32: return 0x37;
+ case 0x35: return 0x38;
+ case 0x41: return 0x34;
+ case 0x43: return 0x35;
+ case 0x44: return 0x36;
+ case 0x42: return 0x3a;
+ case 0x45: return 0x3b;
default: return -4;
}
}
@@ -30,7 +28,7 @@ constexpr int from_native_mode(int native) {
case 0x36: return 0x44;
case 0x3a: return 0x42;
case 0x3b: return 0x45;
- default: return -4; // Ultrawide is not stereo.
+ default: return -4;
}
}
}
diff --git a/app/src/main/cpp/viture/mjpeg_payload.h b/app/src/main/cpp/viture/mjpeg_payload.h
index a451a4eee..470ecf550 100644
--- a/app/src/main/cpp/viture/mjpeg_payload.h
+++ b/app/src/main/cpp/viture/mjpeg_payload.h
@@ -5,7 +5,6 @@
inline std::size_t mjpeg_payload_size(const uint8_t* bytes, std::size_t size) {
if (!bytes || size < 4 || size > 4*1024*1024 || bytes[0] != 0xff || bytes[1] != 0xd8) return 0;
std::size_t end = size;
- // Luma Ultra UVC frames can pad the JPEG to an eight-byte boundary with zeros.
while (end > 4 && size-end < 7 && bytes[end-1] == 0) --end;
return bytes[end-2] == 0xff && bytes[end-1] == 0xd9 ? end : 0;
}
diff --git a/app/src/main/cpp/viture/sdk_bridge.cpp b/app/src/main/cpp/viture/sdk_bridge.cpp
index 053c28335..04ee47a35 100644
--- a/app/src/main/cpp/viture/sdk_bridge.cpp
+++ b/app/src/main/cpp/viture/sdk_bridge.cpp
@@ -30,7 +30,6 @@
#include "stereo_frame_gate.h"
namespace {
-// SDK callbacks have no user-data parameter. Only one provider may exist at a time.
std::mutex api_mutex;
std::mutex pose_mutex;
std::array latest_pose{};
@@ -64,7 +63,6 @@ void on_pose(float* data, uint64_t) {
std::lock_guard lock(pose_mutex);
if (!accepting_pose) return;
std::copy_n(data + 3, 4, latest_pose.begin());
- // SDK device ticks are not Android's elapsed-realtime clock.
latest_time = now_ns();
}
@@ -234,8 +232,6 @@ int set_display(Session& s, int standard) {
if (mode == 0) {
int rc = xr_device_provider_set_display_mode(s.device, standard);
if (rc != VITURE_GLASSES_ERROR_NOT_SUPPORTED) return rc;
- // Older Beast firmware exposes fewer bypass modes. Fall back to its
- // separate native table only when the SDK explicitly rejects the mode.
}
const int native = droiddeck::viture::to_native_mode(standard);
if (native < 0) return native;
diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt
index 33585818b..fd0b2f20a 100644
--- a/app/src/main/cpp/waylandcomp/CMakeLists.txt
+++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt
@@ -8,6 +8,7 @@ add_library(droiddeckwayland SHARED
src/sc_layer.c
src/ahb_swapchain.c
src/waylandcomp_jni.c
+ src/gpu_clock_pin.c
src/droiddeck_ext.c
src/wl_dmabuf.c
src/wl_clipboard.c
@@ -17,6 +18,7 @@ add_library(droiddeckwayland SHARED
src/wl_color_mgmt.c
src/hdr_compose.c
src/blend_pass.c
+ src/gpu_busy.c
generated/color-management-v1-protocol.c
generated/xdg-shell-protocol.c
generated/linux-dmabuf-v1-protocol.c
@@ -32,6 +34,8 @@ add_library(droiddeckwayland SHARED
generated/banner-ahb-v1-protocol.c
src/framegen_bridge.c
src/framegen_jni.c
+ src/hudframes.c
+ src/hudframes_jni.c
)
target_compile_options(droiddeckwayland PRIVATE
$<$:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>)
@@ -40,6 +44,7 @@ target_include_directories(droiddeckwayland PRIVATE
prebuilt/include
src
${CMAKE_CURRENT_SOURCE_DIR}/../shaders
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../tools/gpuload/src
)
set(DROIDDECK_FRAMEGEN_LSFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/lsfg)
@@ -94,4 +99,5 @@ target_link_libraries(droiddeckwayland
dl
log
android
+ nativewindow
)
diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c
index 6cf0c8037..cb4447835 100644
--- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c
+++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c
@@ -371,8 +371,8 @@ void ahb_swapchain_set_mode(int on, int live) {
: "; gralloc frames still in flight stay on the layer (or take the copy path) until then");
else
droiddeck_log("layer", "zero-copy: %s at launch (%s)", on ? "on" : "off",
- on ? "DROIDDECK_WAYLAND_ZERO_COPY=1: games present their own gralloc buffers on the display layer"
- : "the drawer's Zero-copy presentation switch turns it on live");
+ on ? "HDR session: games present their own gralloc buffers on the display layer"
+ : "only HDR sessions turn it on");
if (live) wl_display_flush_clients(droiddeck_get_display());
droiddeck_request_redraw();
}
diff --git a/app/src/main/cpp/waylandcomp/src/cardboard.c b/app/src/main/cpp/waylandcomp/src/cardboard.c
index fc09d2f03..982c3bc47 100644
--- a/app/src/main/cpp/waylandcomp/src/cardboard.c
+++ b/app/src/main/cpp/waylandcomp/src/cardboard.c
@@ -34,7 +34,6 @@ void cardboard_clamp(struct cardboard_params *p) {
p->screen_width_m = clampf(p->screen_width_m, 0.2f, 60.0f);
p->k1 = clampf(p->k1, -1.0f, 2.0f);
p->k2 = clampf(p->k2, -1.0f, 2.0f);
- // Optical vertical FOV on supported glasses can be as low as ~22 degrees.
p->fov_deg = clampf(p->fov_deg, 20.0f, 140.0f);
p->lens_inset = clampf(p->lens_inset, -0.25f, 0.25f);
p->chroma = clampf(p->chroma, 0.0f, 0.05f);
@@ -186,6 +185,13 @@ int vkp_cardboard_active(void) {
return on;
}
+int vkp_cardboard_source(void) {
+ pthread_mutex_lock(&g_lock);
+ const int source = g_set.enabled ? g_set.source : CARDBOARD_SOURCE_SCREEN;
+ pthread_mutex_unlock(&g_lock);
+ return source;
+}
+
int vkp_cardboard_pose_changed(void) {
if (!g_changed) return 0;
g_changed = 0;
diff --git a/app/src/main/cpp/waylandcomp/src/cardboard.h b/app/src/main/cpp/waylandcomp/src/cardboard.h
index 88d5ea3ff..2950faec2 100644
--- a/app/src/main/cpp/waylandcomp/src/cardboard.h
+++ b/app/src/main/cpp/waylandcomp/src/cardboard.h
@@ -27,6 +27,7 @@ void vkp_cardboard_set_render_height(int height);
void vkp_cardboard_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops);
int vkp_cardboard_active(void);
+int vkp_cardboard_source(void);
int vkp_cardboard_pose_changed(void);
void vkp_cardboard_begin_frame(void);
VkImage vkp_cardboard_run(VkCommandBuffer cmd, VkImage src, int src_w, int src_h, int out_w, int out_h);
diff --git a/app/src/main/cpp/waylandcomp/src/cardboard_frag.h b/app/src/main/cpp/waylandcomp/src/cardboard_frag.h
index f74676d6a..fb098c4a3 100644
--- a/app/src/main/cpp/waylandcomp/src/cardboard_frag.h
+++ b/app/src/main/cpp/waylandcomp/src/cardboard_frag.h
@@ -1,4 +1,3 @@
- // 1115.1.0
#pragma once
const uint32_t cardboard_frag_code[] = {
0x07230203,0x00010000,0x0008000b,0x000001ba,0x00000000,0x00020011,0x00000001,0x0006000b,
diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c
index 95a8bf83a..471748a6d 100644
--- a/app/src/main/cpp/waylandcomp/src/compositor.c
+++ b/app/src/main/cpp/waylandcomp/src/compositor.c
@@ -16,6 +16,7 @@
#include
#include
#include
+#include
#include
#include "xdg-shell-server-protocol.h"
@@ -185,6 +186,9 @@ static void on_client_created(struct wl_listener *l, void *data) {
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP, ROLE_CURSOR };
+#define DAMAGE_RECTS 8
+struct damage_list { int32_t r[DAMAGE_RECTS][4]; int n; };
+
struct surface {
struct wl_resource *resource;
struct wl_list link;
@@ -203,9 +207,11 @@ struct surface {
struct wl_resource *dmabuf;
struct dmabuf_buffer *dmabuf_buf;
struct wl_listener dmabuf_destroy;
+ const void *last_dmabuf;
int buf_w, buf_h, has_content;
int buf_alpha;
int opaque[4], pending_opaque[4], pending_opaque_set;
+ struct damage_list damage_buf, pending_damage_buf, damage_local, pending_damage_local;
int src_set, dst_set;
float src[4];
int dst[2];
@@ -256,6 +262,26 @@ static struct wl_event_source *g_render_idle, *g_frame_timer;
static int g_dirty;
+static int64_t g_dirty_since_ns;
+volatile int g_render_on_commit = 1;
+static int64_t g_rendered_tick_ns;
+static int g_tick_held;
+static int64_t g_hold_missed_ns;
+#define HOLD_RETRY_NS 1000000000LL
+#define PACE_BUFFERS 32
+static struct {
+ unsigned ticks, ticks_late_2ms, renders, commit_renders, null_attaches, reattaches, presented, replaced, undrawn, distinct;
+ int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns;
+ const void *buffers[PACE_BUFFERS];
+ uint64_t game_frames_seen;
+} g_pace;
+
+static void pace_note_buffer(const void *buffer) {
+ for (unsigned i = 0; i < g_pace.distinct && i < PACE_BUFFERS; i++)
+ if (g_pace.buffers[i] == buffer) return;
+ if (g_pace.distinct < PACE_BUFFERS) g_pace.buffers[g_pace.distinct] = buffer;
+ g_pace.distinct++;
+}
static int64_t g_last_vsync_ns;
static int64_t g_tick_vsync_ns;
static int64_t g_refresh_ns = 16666667;
@@ -263,6 +289,7 @@ static struct wl_event_source *g_fallback_timer;
static int g_fallback_armed;
volatile int g_fps_limit;
+volatile int g_release_unpaced;
volatile int g_hide_shell;
@@ -304,6 +331,7 @@ static struct {
} g_perf;
static void schedule_render(void);
+static void on_commit_idle(void *data);
static int64_t now_ns(void) {
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
@@ -370,7 +398,7 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
const int limit = g_fps_limit;
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
- if (interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
+ if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
int64_t now = now_ns();
int64_t at = s->next_release_ns + interval;
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
@@ -417,6 +445,12 @@ static int g_cursor_w, g_cursor_h;
static int g_cursor_hidden = 1;
static int g_cursor_serial;
+#define CURSOR_MAX_DRAWS 2
+static struct vkp_image *g_cursor_img;
+static int g_cursor_img_w, g_cursor_img_h, g_cursor_img_serial = -1;
+static atomic_int g_cursor_composite;
+static atomic_int g_cursor_composite_want;
+
static void cursor_publish_shown(void) {
pthread_mutex_lock(&g_cursor_lock);
if (g_cursor_w > 0) { g_cursor_hidden = 0; g_cursor_serial++; }
@@ -474,6 +508,7 @@ struct active_touch { struct surface *surface; int pointer_fallback; };
static struct active_touch g_touch_points[MAX_TOUCH_POINTS];
static void touch_cancel_surface(struct surface *surface);
static struct surface *g_grab;
+static void publish_query_state(void);
static struct surface *g_key_target;
static struct surface *g_ime_click;
static int g_input_pipe[2] = {-1, -1};
@@ -567,6 +602,7 @@ static void map_toplevel(struct surface *s) {
raise_kept_on_top();
if (!g_desktop) g_key_target = s;
apply_zorder();
+ publish_query_state();
}
static void unmap_toplevel(struct surface *s) {
@@ -621,6 +657,68 @@ static void fire_frames(struct wl_list *frames) {
}
}
+static void scene_size(int *w, int *h);
+static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h);
+static struct surface *g_hud_surface, *g_hud_shm;
+static int64_t g_hud_shm_ns;
+static int64_t g_hud_last_ns, g_hud_alive_ns;
+static int g_hud_fresh;
+static int g_hud_new;
+#define HUD_TIMES 256
+static pthread_mutex_t g_hud_times_lock = PTHREAD_MUTEX_INITIALIZER;
+static float g_hud_times[HUD_TIMES];
+static int64_t g_hud_times_total, g_hud_shown_ns;
+
+static void hud_frame_shown(int64_t t) {
+ const int64_t previous = g_hud_shown_ns;
+ g_hud_shown_ns = t;
+ if (!previous || t <= previous) return;
+ pthread_mutex_lock(&g_hud_times_lock);
+ g_hud_times[g_hud_times_total % HUD_TIMES] = (float)((t - previous) / 1e6);
+ g_hud_times_total++;
+ pthread_mutex_unlock(&g_hud_times_lock);
+}
+
+static int tree_rank(const struct surface *s, const struct surface *want, int *rank, int depth) {
+ const struct surface *c;
+ if (depth > 8) return 0;
+ wl_list_for_each(c, &s->children, child_link)
+ if (c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1;
+ if (s == want) return 1;
+ (*rank)++;
+ wl_list_for_each(c, &s->children, child_link)
+ if (!c->below_parent && tree_rank(c, want, rank, depth + 1)) return 1;
+ return 0;
+}
+
+static int render_rank(const struct surface *want) {
+ const struct surface *s;
+ int rank = 0;
+ if (g_desktop && tree_rank(g_desktop, want, &rank, 0)) return rank;
+ wl_list_for_each(s, &g_toplevels, toplevel_link)
+ if (tree_rank(s, want, &rank, 0)) return rank;
+ return -1;
+}
+
+static int below_surface(const struct surface *s, const struct surface *other) {
+ const int a = render_rank(s), b = render_rank(other);
+ return a >= 0 && b >= 0 && a < b;
+}
+
+int droiddeck_hud_frame_times(float *out, int len, int64_t *total) {
+ pthread_mutex_lock(&g_hud_times_lock);
+ *total = g_hud_times_total;
+ int64_t n = *total < len ? *total : len;
+ if (n > HUD_TIMES) n = HUD_TIMES;
+ for (int64_t i = 0; i < n; i++) out[i] = g_hud_times[(*total - n + i) % HUD_TIMES];
+ pthread_mutex_unlock(&g_hud_times_lock);
+ return (int)n;
+}
+static uint64_t g_game_frames;
+extern void droiddeck_on_game_surface(const char *window, const char *gpu);
+extern void droiddeck_on_game_frame(void);
+extern void droiddeck_on_game_program(int pid, const char *program);
+
static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_resource *buffer) {
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
int32_t stride = wl_shm_buffer_get_stride(shm);
@@ -643,6 +741,33 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
g_stat_shm++;
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
if (ci && ci->asked_feedback) ci->shm_frames++;
+ int local_w, local_h;
+ surface_size(s, &local_w, &local_h);
+ const double region = s->src_set ? (double)s->src[2] * s->src[3] : (double)w * h;
+ const int64_t local_max = damage_area(&s->damage_local, local_w, local_h);
+ const int64_t local = local_w > 0 && local_h > 0
+ ? (int64_t)((double)local_max * region / ((double)local_w * local_h)) : local_max;
+ const int64_t buffer_max = damage_area(&s->damage_buf, w, h);
+ const int64_t area = (int64_t)w * h;
+ int64_t damaged = buffer_max > local ? buffer_max : local;
+ if (damaged > area) damaged = area;
+ const int64_t now = now_ns();
+ if (damaged * 16 >= area && (!g_hud_surface || now - g_hud_last_ns > 1000000000LL) &&
+ (s == g_hud_shm || !g_hud_shm || now - g_hud_shm_ns > 1000000000LL)) {
+ const struct surface *top = s;
+ int scene_w, scene_h, top_w, top_h, depth = 0;
+ while (top->parent && depth++ < 8) top = top->parent;
+ scene_size(&scene_w, &scene_h);
+ surface_size(top, &top_w, &top_h);
+ int64_t shown = (int64_t)local_w * local_h;
+ if ((int64_t)top_w * top_h > shown) shown = (int64_t)top_w * top_h;
+ if (top->role == ROLE_TOPLEVEL && top->mapped && shown * 2 >= (int64_t)scene_w * scene_h) {
+ g_hud_shm = s;
+ g_hud_shm_ns = now;
+ g_hud_new = 1;
+ droiddeck_on_game_frame();
+ }
+ }
}
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
@@ -659,17 +784,12 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
s->has_content = s->shm_img != NULL;
}
-static struct surface *g_hud_surface;
-static int64_t g_hud_last_ns, g_hud_alive_ns;
-static int g_hud_fresh;
-static uint64_t g_game_frames;
-extern void droiddeck_on_game_surface(const char *window, const char *gpu);
-extern void droiddeck_on_game_frame(void);
-extern void droiddeck_on_game_program(int pid, const char *program);
-
static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) {
const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b;
if (!repeat) {
+ if (!s->dmabuf && s->last_dmabuf == buffer) g_pace.reattaches++;
+ s->last_dmabuf = buffer;
+ pace_note_buffer(buffer);
drop_dmabuf(s, 1);
s->dmabuf = buffer;
s->dmabuf_buf = b;
@@ -721,8 +841,9 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
name, b->width, b->height, (unsigned long long)b->modifier);
}
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
- (!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL ||
- (announced_now && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
+ (!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) ||
+ (announced_now && !below_surface(g_hud_surface, s) &&
+ (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
char name[160];
describe(s, name, sizeof(name));
g_hud_surface = s;
@@ -746,7 +867,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
}
if (s == g_hud_surface) {
g_hud_alive_ns = now_ns();
- if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_game_frames++; droiddeck_on_game_frame(); }
+ if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; droiddeck_on_game_frame(); }
}
}
@@ -783,8 +904,45 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r,
wl_resource_add_destroy_listener(buffer, &s->pending_buffer_destroy);
}
}
+static int64_t rect_area(const int32_t *r, int bound_w, int bound_h) {
+ int64_t x0 = r[0], y0 = r[1], x1 = (int64_t)r[0] + r[2], y1 = (int64_t)r[1] + r[3];
+ if (bound_w > 0 && bound_h > 0) {
+ if (x0 < 0) x0 = 0;
+ if (y0 < 0) y0 = 0;
+ if (x1 > bound_w) x1 = bound_w;
+ if (y1 > bound_h) y1 = bound_h;
+ }
+ if (x1 <= x0 || y1 <= y0) return 0;
+ const int64_t w = x1 - x0, h = y1 - y0;
+ return (w < 65536 ? w : 65536) * (h < 65536 ? h : 65536);
+}
+static void note_damage(struct damage_list *d, int32_t x, int32_t y, int32_t w, int32_t h) {
+ if (w <= 0 || h <= 0) return;
+ const int32_t rect[4] = { x, y, w, h };
+ int slot = d->n;
+ if (slot == DAMAGE_RECTS) {
+ slot = 0;
+ for (int i = 1; i < DAMAGE_RECTS; i++)
+ if (rect_area(d->r[i], 0, 0) < rect_area(d->r[slot], 0, 0)) slot = i;
+ if (rect_area(rect, 0, 0) <= rect_area(d->r[slot], 0, 0)) return;
+ } else {
+ d->n++;
+ }
+ memcpy(d->r[slot], rect, sizeof(rect));
+}
+static int64_t damage_area(const struct damage_list *d, int bound_w, int bound_h) {
+ int64_t max = 0;
+ for (int i = 0; i < d->n; i++) {
+ const int64_t area = rect_area(d->r[i], bound_w, bound_h);
+ if (area > max) max = area;
+ }
+ return max;
+}
static void surface_damage(struct wl_client *c, struct wl_resource *r,
- int32_t x, int32_t y, int32_t w, int32_t h) {}
+ int32_t x, int32_t y, int32_t w, int32_t h) {
+ struct surface *s = wl_resource_get_user_data(r);
+ note_damage(&s->pending_damage_local, x, y, w, h);
+}
static void frame_callback_destroy(struct wl_resource *r) {
wl_list_remove(wl_resource_get_link(r));
}
@@ -793,12 +951,15 @@ static void feedback_resource_destroy(struct wl_resource *r) {
wl_list_remove(wl_resource_get_link(r));
}
-static void feedback_discard_all(struct wl_list *list) {
+static unsigned feedback_discard_all(struct wl_list *list) {
struct wl_resource *fb, *tmp;
+ unsigned n = 0;
wl_resource_for_each_safe(fb, tmp, list) {
wp_presentation_feedback_send_discarded(fb);
wl_resource_destroy(fb);
+ n++;
}
+ return n;
}
static uint32_t nominal_refresh_ns(void) {
@@ -808,10 +969,14 @@ static uint32_t nominal_refresh_ns(void) {
}
static int64_t presented_ns(int64_t render_ns) {
- if (!g_tick_vsync_ns || render_ns - g_last_vsync_ns > (int64_t)nominal_refresh_ns() ||
- render_ns < g_tick_vsync_ns)
+ int64_t tick = g_tick_vsync_ns;
+ int64_t refresh = (int64_t)nominal_refresh_ns();
+ if (!tick || render_ns - g_last_vsync_ns > refresh)
return render_ns;
- return g_tick_vsync_ns;
+ int64_t delta = render_ns - tick;
+ if (delta > refresh || -delta > refresh)
+ return render_ns;
+ return tick;
}
static void feedback_present_all(struct wl_list *list, int64_t t) {
@@ -823,6 +988,7 @@ static void feedback_present_all(struct wl_list *list, int64_t t) {
nominal_refresh_ns(), 0, 0,
WP_PRESENTATION_FEEDBACK_KIND_VSYNC);
wl_resource_destroy(fb);
+ g_pace.presented++;
}
}
@@ -980,13 +1146,18 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
s->pending_opaque_set = 0;
}
+ s->damage_buf = s->pending_damage_buf;
+ s->damage_local = s->pending_damage_local;
+ s->pending_damage_buf.n = s->pending_damage_local.n = 0;
if (s->pending_attach) {
struct wl_resource *buffer = s->pending_buffer;
struct dmabuf_buffer *db = get_dmabuf(buffer);
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
uint8_t pixel[4];
- feedback_discard_all(&s->feedback);
+ g_pace.replaced += feedback_discard_all(&s->feedback);
+ if (!buffer) g_pace.null_attaches++;
+ else if (!db) s->last_dmabuf = NULL;
if (buffer) {
wl_list_remove(&s->pending_buffer_destroy.link);
@@ -1044,7 +1215,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {}
static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {}
static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r,
- int32_t x, int32_t y, int32_t w, int32_t h) {}
+ int32_t x, int32_t y, int32_t w, int32_t h) {
+ struct surface *s = wl_resource_get_user_data(r);
+ note_damage(&s->pending_damage_buf, x, y, w, h);
+}
static void surface_offset(struct wl_client *c, struct wl_resource *r, int32_t x, int32_t y) {}
static const struct wl_surface_interface surface_impl = {
@@ -1087,6 +1261,7 @@ static void surface_resource_destroy(struct wl_resource *r) {
droiddeck_text_input_surface_gone(r);
if (g_desktop == s) { g_desktop = NULL; droiddeck_log("desktop", "the desktop closed"); }
if (g_hud_surface == s) { g_hud_surface = NULL; droiddeck_on_game_surface(NULL, NULL); }
+ if (g_hud_shm == s) g_hud_shm = NULL;
constraints_surface_gone(s);
unmap_toplevel(s);
@@ -1566,6 +1741,8 @@ static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t
struct draw_list { struct vkp_draw *d; int n, cap; };
+static int add_cursor(struct draw_list *dl, int scene_w);
+
static struct vkp_image *surface_image(struct surface *s) {
if (!s->has_content) return NULL;
if (s->shm_img) return s->shm_img;
@@ -1739,7 +1916,7 @@ static int hdr_plan(const struct draw_list *dl, int w, int h, int fx_on, int fra
}
if (un && g_zero_copy) { hs->color = droiddeck_color_of(un->resource); hs->who = un; return 3; }
hs->hf.tonemap = !droiddeck_color_output();
- if (dl->n <= 0 || !(hs->is_hdr = calloc((size_t)dl->n, 1))) return 0;
+ if (dl->n <= 0 || !(hs->is_hdr = calloc((size_t)dl->n + CURSOR_MAX_DRAWS, 1))) return 0;
for (int i = 0; i < dl->n; i++) {
struct surface *s = surface_for_image(dl->d[i].img);
if (!is_hdr_surface(s)) continue;
@@ -1841,14 +2018,143 @@ static void hdr_count_copied(const struct draw_list *dl, const char *reason) {
}
}
+#define STREAM_SLOTS 6
+static pthread_mutex_t g_stream_lock = PTHREAD_MUTEX_INITIALIZER;
+static atomic_int g_stream_on;
+static AHardwareBuffer *g_stream_pending;
+static struct { AHardwareBuffer *ahb; struct vkp_image *img; uint64_t used; } g_stream_slots[STREAM_SLOTS];
+static struct vkp_image *g_stream_img;
+static uint64_t g_stream_seq;
+static atomic_uint g_stream_frames;
+
+static void stream_forget_all(void) {
+ vkp_wait_idle();
+ for (int i = 0; i < STREAM_SLOTS; i++) {
+ if (g_stream_slots[i].img) vkp_image_destroy(g_stream_slots[i].img);
+ if (g_stream_slots[i].ahb) AHardwareBuffer_release(g_stream_slots[i].ahb);
+ g_stream_slots[i].img = NULL; g_stream_slots[i].ahb = NULL; g_stream_slots[i].used = 0;
+ }
+ g_stream_img = NULL;
+}
+
+static void stream_take(void) {
+ pthread_mutex_lock(&g_stream_lock);
+ AHardwareBuffer *ahb = g_stream_pending;
+ g_stream_pending = NULL;
+ pthread_mutex_unlock(&g_stream_lock);
+ if (!ahb) return;
+ if (!atomic_load(&g_stream_on)) { AHardwareBuffer_release(ahb); return; }
+ int slot = -1, oldest = 0;
+ for (int i = 0; i < STREAM_SLOTS; i++) {
+ if (g_stream_slots[i].ahb == ahb) { slot = i; break; }
+ if (g_stream_slots[i].used < g_stream_slots[oldest].used) oldest = i;
+ }
+ if (slot >= 0) {
+ AHardwareBuffer_release(ahb);
+ } else {
+ struct vkp_image *img = vkp_image_from_ahb(ahb);
+ if (!img) {
+ static int said;
+ if (!said) { said = 1; droiddeck_log("stream", "a decoded frame could not be imported: nothing to show"); }
+ AHardwareBuffer_release(ahb);
+ return;
+ }
+ droiddeck_log("stream", "decoded frame buffer imported (%dx%d)", vkp_image_width(img), vkp_image_height(img));
+ slot = oldest;
+ if (g_stream_slots[slot].img) {
+ vkp_wait_idle();
+ if (g_stream_img == g_stream_slots[slot].img) g_stream_img = NULL;
+ vkp_image_destroy(g_stream_slots[slot].img);
+ }
+ if (g_stream_slots[slot].ahb) AHardwareBuffer_release(g_stream_slots[slot].ahb);
+ g_stream_slots[slot].ahb = ahb;
+ g_stream_slots[slot].img = img;
+ }
+ g_stream_slots[slot].used = ++g_stream_seq;
+ g_stream_img = g_stream_slots[slot].img;
+ atomic_fetch_add(&g_stream_frames, 1);
+ schedule_render();
+}
+
+static void render_stream(void) {
+ g_dirty = 0;
+ struct vkp_image *img = g_stream_img;
+ if (!img) return;
+ int w = vkp_image_width(img), h = vkp_image_height(img);
+ if (w != g_scene_w || h != g_scene_h) {
+ droiddeck_log("stream", "picture %dx%d", w, h);
+ g_scene_w = w;
+ g_scene_h = h;
+ }
+ struct vkp_draw d = {.img = img, .sx = 0, .sy = 0, .sw = (float)w, .sh = (float)h, .dx = 0, .dy = 0, .dw = w, .dh = h, .blend = 0};
+ vkp_apply_window_request();
+ sc_layer_hide();
+ int r = vkp_render(w, h, &d, 1);
+ if (r == 0) {
+ g_stat_frames++;
+ static int first;
+ if (!first) { first = 1; droiddeck_log("stream", "first stream frame presented"); }
+ } else {
+ static int failed;
+ if (failed++ % 600 == 0) droiddeck_log("stream", "presenting a stream frame failed (%d, %d times)", r, failed);
+ }
+}
+
+void droiddeck_stream_set(int on) {
+ atomic_store(&g_stream_on, on ? 1 : 0);
+ if (g_input_pipe[1] < 0) return;
+ struct input_msg m = { 21, on ? 1 : 0, 0, 0, 0 };
+ ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
+ (void)n;
+}
+
+void droiddeck_stream_frame(AHardwareBuffer *ahb) {
+ if (!ahb || !atomic_load(&g_stream_on) || g_input_pipe[1] < 0) return;
+ AHardwareBuffer_acquire(ahb);
+ pthread_mutex_lock(&g_stream_lock);
+ AHardwareBuffer *dropped = g_stream_pending;
+ g_stream_pending = ahb;
+ pthread_mutex_unlock(&g_stream_lock);
+ if (dropped) { AHardwareBuffer_release(dropped); return; }
+ struct input_msg m = { 20, 0, 0, 0, 0 };
+ ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
+ (void)n;
+}
+
+unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); }
+
+static int64_t g_scene_due_ns;
+
+static int scene_held_for_limit(int64_t now, int64_t due, int limit, int unpaced) {
+ if (limit <= 0 || unpaced || due <= 0) return 0;
+ return now < due - 1000000LL;
+}
+
+static int64_t scene_next_due(int64_t now, int64_t due, int limit) {
+ if (limit <= 0) return 0;
+ const int64_t interval = 1000000000LL / limit;
+ return due > 0 && now - due < interval ? due + interval : now + interval;
+}
+
static void render_scene(void) {
+ g_scene_due_ns = scene_next_due(now_ns(), g_scene_due_ns, g_fps_limit);
+ if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
struct draw_list dl = {0};
struct surface *s;
int w, h;
const int64_t t_scene = now_ns();
int copy = 0;
+ if (g_dirty_since_ns) {
+ const int64_t wait = t_scene - g_dirty_since_ns;
+ g_pace.wait_ns += wait;
+ if (wait > g_pace.wait_max_ns) g_pace.wait_max_ns = wait;
+ g_pace.renders++;
+ g_dirty_since_ns = 0;
+ }
g_dirty = 0;
+ g_rendered_tick_ns = g_tick_vsync_ns;
+ g_tick_held = 0;
g_hud_fresh = 0;
g_hdr_unimported = NULL;
wl_list_for_each(s, &g_surfaces, link) s->drawn = 0;
@@ -1878,6 +2184,28 @@ static void render_scene(void) {
hdr_note_precedence(hdr_route == 3 ? hs.who : NULL, fx_on, framegen);
}
if (hdr_route == 3) { fx_on = 0; framegen = 0; }
+ struct surface *ahb_only = ahb_layer_only_candidate(w, h);
+ struct surface *layer_only = ahb_only ? ahb_only : hdr_unimported_fullscreen(&dl, w, h);
+ const int cursor_on = hdr_route == 3 || layer_only ? 0 : add_cursor(&dl, w);
+ static int cursor_layer_said;
+ if (layer_only && atomic_load(&g_cursor_composite) && !cursor_layer_said) {
+ cursor_layer_said = 1;
+ droiddeck_log("cursor", "the pointer stays out of the picture: the game's frames cannot be imported, "
+ "so the game is shown on its own display layer");
+ } else if (!layer_only) {
+ cursor_layer_said = 0;
+ }
+ static int cursor_hdr_said;
+ if (cursor_on && hdr_route == 0 && hs.n_hdr > 0 && !cardboard) {
+ hdr_route = 2;
+ if (!cursor_hdr_said) {
+ cursor_hdr_said = 1;
+ droiddeck_log("cursor", "the pointer needs a composed scene: the HDR picture goes through the screen "
+ "swapchain instead of the game's own display layer");
+ }
+ } else {
+ cursor_hdr_said = 0;
+ }
if (hdr_route == 1) {
static int fell_back;
vkp_apply_window_request();
@@ -1903,21 +2231,19 @@ static void render_scene(void) {
else if (rendered && how == 2) droiddeck_color_frame_shown(hs.color, DROIDDECK_HDR_TONEMAPPED, 0);
else if (rendered) hdr_copy = "the HDR composition pass is unavailable on this driver";
}
- if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard &&
- !ahb_layer_only_candidate(w, h)) {
- /* The complete SDR scene stays on one display layer. Do not hide/re-show GAME
- * on each desktop frame just because it is not a single fullscreen window. */
+ if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
+ !ahb_only) {
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
} else if (hdr_route == 0 || hdr_route == 3) {
const int pass_on = fx_on || framegen;
- int li = (g_zero_copy && !framegen && !cardboard) ? layer_candidate(&dl, w, h) : -1;
+ int li = (g_zero_copy && !framegen && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
int over = li >= 0 ? dl.n - 1 - li : 0;
const int fx_blocks = (li >= 0 && fx_on && over > 0);
if (fx_blocks) { li = -1; over = 0; }
const int ov_blocks = (li >= 0 && over > 0 && !fx_blocks && !sc_layer_overlay_affordable());
if (ov_blocks) { li = -1; over = 0; }
const int blocked = framegen ? 1 : (fx_blocks ? 2 : (ov_blocks ? 3 : 0));
- if (g_zero_copy && blocked != g_zero_copy_paused) {
+ if (g_zero_copy && !cursor_on && blocked != g_zero_copy_paused) {
g_zero_copy_paused = blocked;
if (blocked == 1)
droiddeck_log("framegen", "zero-copy paused: frame generation needs the compositor pass");
@@ -1930,9 +2256,9 @@ static void render_scene(void) {
droiddeck_log("effects", "zero-copy resumed: the game is back on its own display layer");
}
struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL;
- if (li < 0) ls = ahb_layer_only_candidate(w, h);
- if (li < 0 && !ls) ls = hdr_unimported_fullscreen(&dl, w, h);
+ if (li < 0) ls = layer_only;
if (cardboard) ls = NULL;
+ if (cursor_on) ls = NULL;
if (ls && pass_on && li < 0 && !g_zero_copy_fx_skip_said) {
g_zero_copy_fx_skip_said = 1;
droiddeck_log(framegen ? "framegen" : "effects",
@@ -1982,9 +2308,13 @@ static void render_scene(void) {
if (rendered) {
int64_t t = presented_ns(t_scene);
g_stat_frames++;
+ if (g_hud_new) {
+ g_hud_new = 0;
+ hud_frame_shown(t);
+ }
wl_list_for_each(s, &g_surfaces, link) {
if (s->drawn) feedback_present_all(&s->feedback, t);
- else feedback_discard_all(&s->feedback);
+ else g_pace.undrawn += feedback_discard_all(&s->feedback);
}
fire_all_frames();
} else {
@@ -2005,14 +2335,29 @@ static void render_scene(void) {
static int on_fallback_timer(void *data) {
g_fallback_armed = 0;
- if (g_dirty) render_scene();
+ if (!g_dirty) return 0;
+ if (scene_held_for_limit(now_ns(), g_scene_due_ns, g_fps_limit, g_release_unpaced)) schedule_render();
+ else render_scene();
return 0;
}
+static int commit_renders_on(void) {
+ return g_render_on_commit && g_release_unpaced && !atomic_load(&g_stream_on) && !vkp_framegen_active();
+}
+
+static int render_on_commit(void) {
+ return commit_renders_on() && !g_render_idle && g_rendered_tick_ns != g_tick_vsync_ns;
+}
+
static void schedule_render(void) {
+ if (!g_dirty && !g_dirty_since_ns) g_dirty_since_ns = now_ns();
g_dirty = 1;
if (!g_display) return;
- if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) return;
+ if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) {
+ if (render_on_commit())
+ g_render_idle = wl_event_loop_add_idle(wl_display_get_event_loop(g_display), on_commit_idle, NULL);
+ return;
+ }
if (g_fallback_armed) return;
if (!g_fallback_timer)
g_fallback_timer = wl_event_loop_add_timer(wl_display_get_event_loop(g_display),
@@ -2026,18 +2371,42 @@ static int scene_waits_for_game(int64_t now) {
return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active();
}
+static void on_commit_idle(void *data) {
+ g_render_idle = NULL;
+ if (!g_dirty || !commit_renders_on() || g_rendered_tick_ns == g_tick_vsync_ns || scene_waits_for_game(now_ns())) return;
+ g_pace.commit_renders++;
+ render_scene();
+}
+
static void on_vsync(int64_t frame_time_ns) {
int64_t now = now_ns();
g_perf.ticks++;
+ if (frame_time_ns > 0 && now >= frame_time_ns) {
+ const int64_t late = now - frame_time_ns;
+ g_pace.ticks++;
+ g_pace.tick_late_ns += late;
+ if (late > g_pace.tick_late_max_ns) g_pace.tick_late_max_ns = late;
+ if (late > 2000000LL) g_pace.ticks_late_2ms++;
+ }
if (g_last_vsync_ns) {
int64_t d = now - g_last_vsync_ns;
if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8;
}
g_last_vsync_ns = now;
g_tick_vsync_ns = frame_time_ns;
- if (vkp_apply_window_request()) g_dirty = 1;
- if (vkp_effects_sync()) g_dirty = 1;
- if (vkp_cardboard_pose_changed()) g_dirty = 1;
+ int tick_change = 0;
+ if (vkp_apply_window_request()) tick_change = 1;
+ if (vkp_effects_sync()) tick_change = 1;
+ if (vkp_cardboard_pose_changed()) tick_change = 1;
+ if (tick_change) g_dirty = 1;
+ if (g_tick_held && g_dirty) g_hold_missed_ns = now;
+ g_tick_held = 0;
+ if (!tick_change && commit_renders_on() && g_dirty_since_ns && now - g_dirty_since_ns < g_refresh_ns &&
+ now - g_hold_missed_ns >= HOLD_RETRY_NS) {
+ g_tick_held = 1;
+ return;
+ }
+ if (g_dirty && scene_held_for_limit(now, g_scene_due_ns, g_fps_limit, g_release_unpaced)) return;
if (g_dirty && !scene_waits_for_game(now)) render_scene();
}
@@ -2053,6 +2422,7 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
if (g_cursor_surface) g_cursor_surface->role = ROLE_NONE;
g_cursor_surface = NULL;
cursor_publish_hidden();
+ if (atomic_load(&g_cursor_composite)) schedule_render();
return;
}
struct surface *s = wl_resource_get_user_data(surface);
@@ -2060,8 +2430,10 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
if (s->role != ROLE_NONE && s->role != ROLE_CURSOR) return;
s->role = ROLE_CURSOR;
g_cursor_surface = s;
+ pthread_mutex_lock(&g_cursor_lock);
g_cursor_hx = hx;
g_cursor_hy = hy;
+ pthread_mutex_unlock(&g_cursor_lock);
struct wl_resource *buffer = surface_take_idle(s);
if (buffer) {
cursor_publish_buffer(s, buffer);
@@ -2072,6 +2444,7 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
cursor_publish_pixels((const uint8_t *)s->idle_px, s->idle_w, s->idle_h, (size_t)s->idle_w * 4, hx, hy);
g_cursor_shown = s;
}
+ if (atomic_load(&g_cursor_composite)) schedule_render();
}
static void pointer_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static const struct wl_pointer_interface pointer_impl = {
@@ -2095,6 +2468,7 @@ static const struct wl_touch_interface touch_impl = { .release = touch_release }
static void touch_res_destroy(struct wl_resource *r) {
for (int i = 0; i < g_ntouches; i++)
if (g_touches[i].touch == r) { g_touches[i] = g_touches[--g_ntouches]; break; }
+ publish_query_state();
}
static void seat_get_pointer(struct wl_client *c, struct wl_resource *r, uint32_t id) {
@@ -2132,6 +2506,7 @@ static void seat_get_touch(struct wl_client *c, struct wl_resource *r, uint32_t
g_touches[g_ntouches].focus = NULL;
g_ntouches++;
}
+ publish_query_state();
}
static void seat_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static const struct wl_seat_interface seat_impl = {
@@ -2247,9 +2622,101 @@ struct relative_pointer {
static struct wl_list g_relative_pointers;
static double g_ptr_x, g_ptr_y;
+static int g_ptr_known;
static double g_raw_x, g_raw_y;
static int g_raw_valid;
+static int pointer_locked_for_cursor(void) {
+ return g_active_constraint && g_active_constraint->is_lock;
+}
+
+static int cursor_scene_positions(int scene_w, int source, int ptr_x, int hx, int out[2]) {
+ out[0] = ptr_x - hx; out[1] = -1;
+ if (source != CARDBOARD_SOURCE_SBS || scene_w <= 1) return 1;
+ const int half = scene_w / 2;
+ out[1] = (ptr_x < half ? ptr_x + half : ptr_x - half) - hx;
+ return 2;
+}
+
+static int cursor_clip_to_eye(int scene_w, int eye, int x0, int w, int *dx, int *sx, int *dw) {
+ int left = x0, right = x0 + w;
+ if (eye >= 0 && scene_w > 1) {
+ const int half = scene_w / 2;
+ const int band = eye ? half : 0;
+ if (left < band) left = band;
+ if (right > band + half) right = band + half;
+ }
+ if (right <= left) return 0;
+ *dx = left;
+ *sx = left - x0;
+ *dw = right - left;
+ return 1;
+}
+
+static int add_cursor(struct draw_list *dl, int scene_w) {
+ if (!atomic_load(&g_cursor_composite) || !g_ptr_known || pointer_locked_for_cursor()) return 0;
+
+ int hidden, w, h, hx, hy, serial;
+ uint32_t *copy = NULL;
+ pthread_mutex_lock(&g_cursor_lock);
+ hidden = g_cursor_hidden;
+ w = g_cursor_w; h = g_cursor_h;
+ hx = g_cursor_hx; hy = g_cursor_hy;
+ serial = g_cursor_serial;
+ if (!hidden && w > 0 && h > 0 && serial != g_cursor_img_serial) {
+ copy = malloc((size_t)w * (size_t)h * 4);
+ if (copy) memcpy(copy, g_cursor_px, (size_t)w * (size_t)h * 4);
+ }
+ pthread_mutex_unlock(&g_cursor_lock);
+ if (hidden || w <= 0 || h <= 0) return 0;
+
+ if (copy) {
+ if (g_cursor_img && (g_cursor_img_w != w || g_cursor_img_h != h)) {
+ vkp_wait_idle();
+ vkp_image_destroy(g_cursor_img);
+ g_cursor_img = NULL;
+ }
+ if (!g_cursor_img) g_cursor_img = vkp_image_create_shm(w, h);
+ if (g_cursor_img) {
+ g_cursor_img_w = w; g_cursor_img_h = h;
+ vkp_image_upload_shm(g_cursor_img, copy, w * 4);
+ g_cursor_img_serial = serial;
+ }
+ free(copy);
+ }
+ if (!g_cursor_img || g_cursor_img_serial != serial) return 0;
+
+ int xs[CURSOR_MAX_DRAWS];
+ const int source = vkp_cardboard_source();
+ const int ptr_x = (int)(g_ptr_x + 0.5);
+ const int count = cursor_scene_positions(scene_w, source, ptr_x, hx, xs);
+ static int said_w = -1, said_source = -1, said_count = -1;
+ if (scene_w != said_w || source != said_source || count != said_count) {
+ said_w = scene_w; said_source = source; said_count = count;
+ droiddeck_log("cursor", "pointer drawn %d time(s) in a %d wide scene (%s picture)", count, scene_w,
+ source == CARDBOARD_SOURCE_SBS ? "side-by-side" : "single");
+ }
+ if (dl->n + count > dl->cap) {
+ int cap = dl->cap ? dl->cap : 32;
+ while (cap < dl->n + count) cap *= 2;
+ struct vkp_draw *d = realloc(dl->d, (size_t)cap * sizeof(*d));
+ if (!d) return 0;
+ dl->d = d; dl->cap = cap;
+ }
+ const int sbs = source == CARDBOARD_SOURCE_SBS && scene_w > 1;
+ const int pointer_eye = ptr_x < scene_w / 2 ? 0 : 1;
+ int appended = 0;
+ for (int i = 0; i < count; i++) {
+ int dx, sx, cw;
+ const int eye = sbs ? (i ? 1 - pointer_eye : pointer_eye) : -1;
+ if (!cursor_clip_to_eye(scene_w, eye, xs[i], w, &dx, &sx, &cw)) continue;
+ dl->d[dl->n++] = (struct vkp_draw){g_cursor_img, (float)sx, 0, (float)cw, (float)h,
+ dx, (int)(g_ptr_y + 0.5) - hy, cw, h, 1};
+ appended++;
+ }
+ return appended ? 1 : 0;
+}
+
extern void droiddeck_on_pointer_lock(int locked, int x, int y);
static void sync_lock_notify(void) {
@@ -2258,6 +2725,7 @@ static void sync_lock_notify(void) {
if (locked == last) return;
last = locked;
droiddeck_on_pointer_lock(locked, (int)g_ptr_x, (int)g_ptr_y);
+ if (atomic_load(&g_cursor_composite)) schedule_render();
}
static void constraint_describe(const struct constraint *k, char *out, size_t size) {
@@ -2311,6 +2779,7 @@ static void constraint_end(struct constraint *k, int tell_client, const char *wh
constraint_origin(k, &ox, &oy);
g_ptr_x = ox + k->hint_x;
g_ptr_y = oy + k->hint_y;
+ g_ptr_known = 1;
}
g_raw_valid = 0;
if (k->gave_keys) {
@@ -2336,7 +2805,10 @@ static void constraint_activate(struct constraint *k) {
constraint_end(g_active_constraint, 1, "replaced by a newer request");
k->active = 1;
g_active_constraint = k;
+ const double was_x = g_ptr_x, was_y = g_ptr_y;
if (!k->is_lock) confine_clamp(k, &g_ptr_x, &g_ptr_y);
+ if ((g_ptr_x != was_x || g_ptr_y != was_y) && atomic_load(&g_cursor_composite))
+ schedule_render();
constraint_origin(k, &ox, &oy);
pointer_focus(k->surface->resource, wl_fixed_from_double(g_ptr_x - ox), wl_fixed_from_double(g_ptr_y - oy));
int focused = 0;
@@ -2395,6 +2867,7 @@ static void constraints_pointer_gone(struct wl_resource *pointer) {
static void constraints_surface_commit(struct surface *s) {
struct constraint *k;
+ const double was_x = g_ptr_x, was_y = g_ptr_y;
wl_list_for_each(k, &g_constraints, link) {
if (k->surface != s) continue;
if (k->pending_hint_set) {
@@ -2407,6 +2880,7 @@ static void constraints_surface_commit(struct surface *s) {
constraint_origin(k, &ox, &oy);
g_ptr_x = ox + k->hint_x;
g_ptr_y = oy + k->hint_y;
+ g_ptr_known = 1;
if (log_budget())
droiddeck_log("pointer", "position hint: pointer moved to %d,%d", (int)g_ptr_x, (int)g_ptr_y);
}
@@ -2417,6 +2891,8 @@ static void constraints_surface_commit(struct surface *s) {
if (k->active && !k->is_lock) confine_clamp(k, &g_ptr_x, &g_ptr_y);
}
}
+ if ((g_ptr_x != was_x || g_ptr_y != was_y) && atomic_load(&g_cursor_composite))
+ schedule_render();
}
static void constraint_resource_destroy(struct wl_resource *r) {
@@ -2601,6 +3077,8 @@ static void pointer_input(double x, double y, int relative, uint32_t button, int
}
if (k) confine_clamp(k, &x, &y);
g_ptr_x = x; g_ptr_y = y;
+ g_ptr_known = 1;
+ if (atomic_load(&g_cursor_composite)) schedule_render();
if (k) {
target = k->surface;
} else if (g_desktop) {
@@ -2611,6 +3089,7 @@ static void pointer_input(double x, double y, int relative, uint32_t button, int
if (button && !pressed) g_grab = NULL;
}
}
+ publish_query_state();
if (!target) return;
struct wl_client *client = wl_resource_get_client(target->resource);
@@ -2622,13 +3101,9 @@ static void pointer_input(double x, double y, int relative, uint32_t button, int
uint32_t t = now_ms();
pointer_focus(target->resource, fx, fy);
- // A button-only input must not replay a cached absolute position. A game
- // may have warped its cursor since the last motion (before taking lock,
- // or while releasing it), so that replay can become an unintended pan.
- // Absolute touch events still carry their position, including on clicks.
- if (!(k && k->is_lock) && (!relative || dx != 0 || dy != 0))
+ int rel_consumed = send_relative_motion(client, dx, dy);
+ if (!(k && k->is_lock) && !(relative && rel_consumed) && (!relative || dx != 0 || dy != 0))
for_each_pointer_of(client, sp) wl_pointer_send_motion(sp->ptr, t, fx, fy);
- send_relative_motion(client, dx, dy);
for_each_pointer_of(client, sp) {
if (button)
wl_pointer_send_button(sp->ptr, wl_display_next_serial(g_display), t, button,
@@ -2657,9 +3132,6 @@ static void pointer_button(uint32_t button, int pressed) {
pointer_input(0, 0, 1, button, pressed);
return;
}
- // Releases also clean up interrupted gestures. Deliver them to the existing
- // pointer focus without motion or hit-testing: native touch has independent
- // coordinates, so replaying g_ptr_x/y here can warp the game cursor.
uint32_t t = now_ms();
for (int i = 0; i < g_nptrs; i++) {
struct seat_pointer *sp = &g_ptrs[i];
@@ -2767,6 +3239,63 @@ static struct surface *touch_target_at(double x, double y) {
return g_grab ? g_grab : g_key_target;
}
+static pthread_mutex_t g_query_lock = PTHREAD_MUTEX_INITIALIZER;
+struct query_snapshot {
+ int has_position;
+ int input_x, input_y;
+ int focus_takes_touch;
+};
+static struct query_snapshot g_query = { 0, 0, 0, 1 };
+
+static void publish_query_state(void) {
+ struct surface *target = g_key_target ? g_key_target : (g_grab ? g_grab : toplevel_at(g_ptr_x, g_ptr_y));
+ int takes_touch = 1;
+ if (target) {
+ struct wl_client *client = wl_resource_get_client(target->resource);
+ struct seat_touch *st;
+ takes_touch = 0;
+ for_each_touch_of(client, st) takes_touch = 1;
+ }
+ int w = 0, h = 0, ow = 0, oh = 0, input_x = 0, input_y = 0, has_position = 0;
+ scene_size(&w, &h);
+ vkp_output_size(&ow, &oh);
+ if (g_ptr_known && w > 0 && h > 0) {
+ double ox, oy;
+ if (ow > 0 && oh > 0 && vkp_scene_to_output(g_ptr_x, g_ptr_y, &ox, &oy)) {
+ input_x = (int)(ox * INPUT_SPACE_W / ow);
+ input_y = (int)(oy * INPUT_SPACE_H / oh);
+ } else {
+ input_x = (int)(g_ptr_x * INPUT_SPACE_W / w);
+ input_y = (int)(g_ptr_y * INPUT_SPACE_H / h);
+ }
+ has_position = 1;
+ }
+ pthread_mutex_lock(&g_query_lock);
+ g_query.focus_takes_touch = takes_touch;
+ g_query.has_position = has_position;
+ g_query.input_x = input_x;
+ g_query.input_y = input_y;
+ pthread_mutex_unlock(&g_query_lock);
+}
+
+int droiddeck_focus_takes_touch(void) {
+ pthread_mutex_lock(&g_query_lock);
+ int takes_touch = g_query.focus_takes_touch;
+ pthread_mutex_unlock(&g_query_lock);
+ return takes_touch;
+}
+
+int droiddeck_cursor_input_pos(int *x, int *y) {
+ pthread_mutex_lock(&g_query_lock);
+ int has_position = g_query.has_position;
+ int input_x = g_query.input_x, input_y = g_query.input_y;
+ pthread_mutex_unlock(&g_query_lock);
+ if (!has_position) return 0;
+ *x = input_x;
+ *y = input_y;
+ return 1;
+}
+
static void touch_down(int id, double x, double y) {
if (id < 0 || id >= MAX_TOUCH_POINTS) return;
struct surface *target = touch_target_at(x, y);
@@ -2866,6 +3395,7 @@ static void deliver_touch(const struct input_msg *m) {
else if (m->p1 == 1) touch_motion(m->p2, x, y);
else if (m->p1 == 2) touch_up(m->p2, x, y);
else if (m->p1 == 3) touch_cancel_all();
+ publish_query_state();
}
static void key_event(uint32_t evdev, int pressed);
@@ -2883,10 +3413,10 @@ static void send_axis(struct seat_pointer *sp, uint32_t t, uint32_t axis, int va
wl_pointer_send_axis(sp->ptr, t, axis, wl_fixed_from_double(value120 / 12.0));
}
-static void axis_event(int vertical120, int horizontal120) {
+static void axis_event(int vertical120, int horizontal120, int finger) {
struct surface *target = g_active_constraint ? g_active_constraint->surface
: g_desktop ? g_desktop : (g_grab ? g_grab : toplevel_at(g_ptr_x, g_ptr_y));
- if (!target || (!vertical120 && !horizontal120)) return;
+ if (!target || (!finger && !vertical120 && !horizontal120)) return;
struct wl_client *client = wl_resource_get_client(target->resource);
struct seat_pointer *sp;
if (!pointer_for(client)) return;
@@ -2895,16 +3425,33 @@ static void axis_event(int vertical120, int horizontal120) {
uint32_t t = now_ms();
pointer_focus(target->resource, wl_fixed_from_double(g_ptr_x - tx), wl_fixed_from_double(g_ptr_y - ty));
for_each_pointer_of(client, sp) {
- send_axis(sp, t, WL_POINTER_AXIS_VERTICAL_SCROLL, vertical120);
- send_axis(sp, t, WL_POINTER_AXIS_HORIZONTAL_SCROLL, horizontal120);
- if (wl_resource_get_version(sp->ptr) >= WL_POINTER_FRAME_SINCE_VERSION)
+ int version = wl_resource_get_version(sp->ptr);
+ if (!finger) {
+ send_axis(sp, t, WL_POINTER_AXIS_VERTICAL_SCROLL, vertical120);
+ send_axis(sp, t, WL_POINTER_AXIS_HORIZONTAL_SCROLL, horizontal120);
+ } else {
+ if (version >= WL_POINTER_AXIS_SOURCE_SINCE_VERSION)
+ wl_pointer_send_axis_source(sp->ptr, WL_POINTER_AXIS_SOURCE_FINGER);
+ if (!vertical120 && !horizontal120) {
+ if (version >= WL_POINTER_AXIS_STOP_SINCE_VERSION) {
+ wl_pointer_send_axis_stop(sp->ptr, t, WL_POINTER_AXIS_VERTICAL_SCROLL);
+ wl_pointer_send_axis_stop(sp->ptr, t, WL_POINTER_AXIS_HORIZONTAL_SCROLL);
+ }
+ } else {
+ if (vertical120)
+ wl_pointer_send_axis(sp->ptr, t, WL_POINTER_AXIS_VERTICAL_SCROLL, wl_fixed_from_double(vertical120 / 12.0));
+ if (horizontal120)
+ wl_pointer_send_axis(sp->ptr, t, WL_POINTER_AXIS_HORIZONTAL_SCROLL, wl_fixed_from_double(horizontal120 / 12.0));
+ }
+ }
+ if (version >= WL_POINTER_FRAME_SINCE_VERSION)
wl_pointer_send_frame(sp->ptr);
}
wl_display_flush_clients(g_display);
}
static void scroll_event(int steps) {
- axis_event(steps * 120, 0);
+ axis_event(steps * 120, 0, 0);
}
static int update_modifiers(uint32_t evdev, int pressed) {
@@ -3000,7 +3547,11 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
schedule_render();
break;
case 10: break;
- case 11: axis_event(m.p1, m.p2); break;
+ case 11: axis_event(m.p1, m.p2, 0); break;
+ case 12: axis_event(m.p1, m.p2, 1); break;
+ case 20: stream_take(); break;
+ case 21: if (!m.p1) stream_forget_all(); schedule_render(); break;
+ case 22: schedule_render(); break;
default: deliver_pointer(&m); break;
}
}
@@ -3075,6 +3626,17 @@ void droiddeck_wayland_send_scene_input(int type, int a, int b) {
(void)n;
}
+void droiddeck_wayland_set_cursor_composite(int on) {
+ const int want = on ? 1 : 0;
+ if (atomic_exchange(&g_cursor_composite_want, want) == want) return;
+ atomic_store(&g_cursor_composite, want);
+ droiddeck_log("cursor", "compositing the pointer into the output: %s", on ? "on" : "off");
+ if (g_input_pipe[1] < 0) return;
+ struct input_msg m = { 22, on ? 1 : 0, 0, 0, 0 };
+ ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
+ (void)n;
+}
+
const char *droiddeck_client_name(struct wl_client *client) { return client_name(client); }
struct wl_display *droiddeck_get_display(void) { return g_display; }
@@ -3139,6 +3701,24 @@ static int on_stats_timer(void *data) {
#undef PERF_MS
memset(&g_perf, 0, sizeof(g_perf));
}
+ const uint64_t game = g_game_frames - g_pace.game_frames_seen;
+ if (g_pace.ticks || g_pace.renders || game || g_pace.reattaches || g_pace.null_attaches || g_pace.distinct ||
+ g_pace.presented || g_pace.replaced || g_pace.undrawn) {
+ droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | "
+ "new frame waits %.2f/%.2f ms to be drawn (%u scenes, %u on arrival) | %llu game frames, %u re-attached after an "
+ "empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, "
+ "%u not drawn",
+ g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6,
+ g_pace.ticks, g_pace.ticks_late_2ms,
+ g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6,
+ g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct,
+ g_pace.presented, g_pace.replaced, g_pace.undrawn);
+ }
+ {
+ const uint64_t seen = g_game_frames;
+ memset(&g_pace, 0, sizeof(g_pace));
+ g_pace.game_frames_seen = seen;
+ }
g_stat_frames = g_stat_dmabuf = g_stat_shm = 0;
droiddeck_color_stats_tick();
@@ -3236,8 +3816,6 @@ int droiddeck_wayland_run(void) {
open_session_log();
if (vkp_ready() != 0) WLOGE("renderer unavailable; clients will connect but nothing is drawn");
- /* Presentation compatibility is not HDR capability. Set the initial layer mode before
- * clients bind, including when Desktop is the first session in this app process. */
if (vkp_quest_layer_presentation() && sc_layer_available()) g_zero_copy = 1;
struct wl_display *display = wl_display_create();
diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c
index 94bb581a0..eceb79639 100644
--- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c
+++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c
@@ -238,7 +238,7 @@ static int ensure_ring(uint32_t w, uint32_t h, VkFormat fmt, uint32_t n) {
}
g_ring_w = w; g_ring_h = h; g_ring_fmt = fmt;
LOGD("framegen: generation ring %ux%u x%u", w, h, n);
- return 1;
+ return 2;
}
@@ -350,6 +350,7 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
fge_configure((uint32_t)mult, (uint32_t)atomic_load(&g_target), flow, hz,
atomic_load(&g_model), atomic_load(&g_preset));
}
+ const int size_changed = g_built_w != (uint32_t)w || g_built_h != (uint32_t)h || g_built_fmt != fmt;
if (!fge_prepare((uint32_t)w, (uint32_t)h, fmt)) {
if (fmt != VK_FORMAT_R8G8B8A8_UNORM && fge_unavailable()) {
refuse_format(fmt, kind, w, h, "build its chain");
@@ -361,20 +362,23 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
}
return 0;
}
- if (g_built_w != (uint32_t)w || g_built_h != (uint32_t)h || g_built_fmt != fmt) {
+ if (size_changed) {
g_built_w = (uint32_t)w; g_built_h = (uint32_t)h; g_built_fmt = fmt;
g_generating_logged = 0;
}
uint32_t want = (uint32_t)(mult - 1);
- if (!ensure_ring((uint32_t)w, (uint32_t)h, fmt, want)) {
+ const int ring = ensure_ring((uint32_t)w, (uint32_t)h, fmt, want);
+ if (!ring) {
if (fmt != VK_FORMAT_R8G8B8A8_UNORM) { refuse_format(fmt, kind, w, h, "make its generation ring"); return 0; }
FGLOG("no memory for the generation ring (%dx%d x%u); frame generation stays off", w, h, want);
mark_failed(kind);
return 0;
}
+ if (size_changed || ring == 2) {
+ FGLOG("frame generation catches up at %dx%d; this frame is shown as it is", w, h);
+ return 0;
+ }
- /* The pacer's source rate must be the game's, not this loop's: a loop slowed by its own
- * generations would otherwise read as a slower game and justify even more generations. */
++g_source_frames;
const uint64_t game_frames = droiddeck_game_frames();
uint32_t n_gen = fge_plan(g_ring_n, game_frames ? game_frames : g_source_frames, g_presented_rate);
diff --git a/app/src/main/cpp/waylandcomp/src/gpu_busy.c b/app/src/main/cpp/waylandcomp/src/gpu_busy.c
new file mode 100644
index 000000000..48d565c20
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/gpu_busy.c
@@ -0,0 +1,89 @@
+#include "gpu_busy.h"
+
+#include
+#include
+#include
+
+#include "gpuload_ring.h"
+
+static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
+static struct gpuload_vk g_v;
+static struct gpuload_ring g_ring;
+static uint32_t g_family, g_bits;
+static PFN_vkQueueSubmit g_submit;
+static int g_was_on;
+static _Atomic int g_on, g_lost, g_timing;
+static _Atomic uint64_t g_busy_ns;
+
+static VkResult VKAPI_CALL timed_submit(VkQueue queue, uint32_t count, const VkSubmitInfo *infos, VkFence fence) {
+ if (!count || !atomic_load(&g_on) || atomic_load(&g_lost)) return g_submit(queue, count, infos, fence);
+ pthread_mutex_lock(&g_lock);
+ if (!atomic_load(&g_on) || atomic_load(&g_lost)) {
+ pthread_mutex_unlock(&g_lock);
+ return g_submit(queue, count, infos, fence);
+ }
+ if (g_ring.state == 0 && gpuload_ring_setup(&g_ring, &g_v, g_family, g_bits)) atomic_store(&g_timing, 1);
+ VkSubmitInfo *mine = NULL;
+ uint32_t used = 0;
+ if (g_ring.state == 1) {
+ uint64_t ns = gpuload_ring_harvest(&g_ring, &g_v);
+ if (g_was_on) atomic_fetch_add(&g_busy_ns, ns); // the first harvest after a pause holds work timed before it
+ g_was_on = 1;
+ mine = gpuload_ring_wrap(&g_ring, count, infos, &used);
+ }
+ VkResult r = g_submit(queue, count, mine ? mine : infos, fence);
+ if (mine && r != VK_SUCCESS) gpuload_ring_unwind(&g_ring, used);
+ pthread_mutex_unlock(&g_lock);
+ free(mine);
+ return r;
+}
+
+void vkp_gpu_busy_device(VkPhysicalDevice pd, VkDevice dev, uint32_t family) {
+ pthread_mutex_lock(&g_lock);
+ memset(&g_ring, 0, sizeof(g_ring));
+ g_was_on = 0;
+ atomic_store(&g_timing, 0);
+ atomic_store(&g_lost, 0);
+ PFN_vkGetDeviceProcAddr gdpa = g_vk.GetDeviceProcAddr;
+ g_v = (struct gpuload_vk){
+ .device = dev,
+ .create_pool = g_vk.CreateCommandPool,
+ .destroy_pool = (PFN_vkDestroyCommandPool)gdpa(dev, "vkDestroyCommandPool"),
+ .alloc_cmds = g_vk.AllocateCommandBuffers,
+ .begin = g_vk.BeginCommandBuffer,
+ .end = g_vk.EndCommandBuffer,
+ .cmd_reset = (PFN_vkCmdResetQueryPool)gdpa(dev, "vkCmdResetQueryPool"),
+ .cmd_timestamp = (PFN_vkCmdWriteTimestamp)gdpa(dev, "vkCmdWriteTimestamp"),
+ .create_queries = (PFN_vkCreateQueryPool)gdpa(dev, "vkCreateQueryPool"),
+ .destroy_queries = (PFN_vkDestroyQueryPool)gdpa(dev, "vkDestroyQueryPool"),
+ .results = (PFN_vkGetQueryPoolResults)gdpa(dev, "vkGetQueryPoolResults"),
+ };
+ VkPhysicalDeviceProperties props;
+ g_vk.GetPhysicalDeviceProperties(pd, &props);
+ gpuload_vk_period(&g_v, props.limits.timestampPeriod);
+ VkQueueFamilyProperties families[16];
+ uint32_t n = 16;
+ g_vk.GetPhysicalDeviceQueueFamilyProperties(pd, &n, families);
+ g_family = family;
+ g_bits = family < n ? families[family].timestampValidBits : 0;
+ // vk_loader_load_device has just put the driver's function back.
+ if (g_vk.QueueSubmit != timed_submit) g_submit = g_vk.QueueSubmit;
+ if (g_submit) g_vk.QueueSubmit = timed_submit;
+ pthread_mutex_unlock(&g_lock);
+}
+
+void vkp_gpu_busy_device_lost(void) {
+ atomic_store(&g_lost, 1);
+ atomic_store(&g_timing, 0);
+}
+
+JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeGpuBusyNs(JNIEnv *env, jclass cls) {
+ return atomic_load(&g_timing) ? (jlong)atomic_load(&g_busy_ns) : -1;
+}
+
+JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTiming(JNIEnv *env, jclass cls, jboolean on) {
+ pthread_mutex_lock(&g_lock);
+ if (!on) g_was_on = 0;
+ atomic_store(&g_on, on ? 1 : 0);
+ pthread_mutex_unlock(&g_lock);
+}
diff --git a/app/src/main/cpp/waylandcomp/src/gpu_busy.h b/app/src/main/cpp/waylandcomp/src/gpu_busy.h
new file mode 100644
index 000000000..a477d5236
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/gpu_busy.h
@@ -0,0 +1,9 @@
+#ifndef GPU_BUSY_H
+#define GPU_BUSY_H
+#include "vk_loader.h"
+
+// Times the compositor's own GPU work for the HUD (tools/gpuload/src/gpuload_ring.h); call after the device and its
+// functions are loaded. Off until WaylandCompositor.nativeSetGpuTiming(true).
+void vkp_gpu_busy_device(VkPhysicalDevice pd, VkDevice dev, uint32_t family);
+void vkp_gpu_busy_device_lost(void);
+#endif
diff --git a/app/src/main/cpp/waylandcomp/src/gpu_clock_pin.c b/app/src/main/cpp/waylandcomp/src/gpu_clock_pin.c
new file mode 100644
index 000000000..8ce226922
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/gpu_clock_pin.c
@@ -0,0 +1,168 @@
+#include "gpu_clock_pin.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "../../adrenotools/src/hook/kgsl.h"
+
+static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_t worker;
+static bool joinable;
+static atomic_bool running;
+
+struct pin {
+ int fd;
+ unsigned int context;
+ unsigned int memory;
+ unsigned int timestamp;
+ unsigned long gpuaddr;
+ uint32_t nop;
+ void *commands;
+ size_t size;
+};
+
+static struct pin pin = { .fd = -1 };
+
+static void release_pin(void) {
+ if (pin.context) {
+ struct kgsl_drawctxt_destroy destroy = { .drawctxt_id = pin.context };
+ ioctl(pin.fd, IOCTL_KGSL_DRAWCTXT_DESTROY, &destroy);
+ }
+ if (pin.commands) munmap(pin.commands, pin.size);
+ if (pin.memory) {
+ struct kgsl_gpumem_free_id free_memory = { .id = pin.memory };
+ ioctl(pin.fd, IOCTL_KGSL_GPUMEM_FREE_ID, &free_memory);
+ }
+ if (pin.fd >= 0) close(pin.fd);
+ pin = (struct pin) { .fd = -1 };
+}
+
+static bool submit_pin(void) {
+ struct kgsl_command_object object = {
+ .gpuaddr = pin.gpuaddr,
+ .size = 2 * sizeof(uint32_t),
+ .flags = KGSL_CMDLIST_IB,
+ .id = pin.memory,
+ };
+ struct kgsl_gpu_command command = {
+ .flags = KGSL_CMDBATCH_PWR_CONSTRAINT,
+ .cmdlist = (uintptr_t)&object,
+ .cmdsize = sizeof(object),
+ .numcmds = 1,
+ .context_id = pin.context,
+ };
+ if (ioctl(pin.fd, IOCTL_KGSL_GPU_COMMAND, &command) < 0) return false;
+ pin.timestamp = command.timestamp;
+ return true;
+}
+
+static bool prepare_pin(void) {
+ pin.fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
+ if (pin.fd < 0) return false;
+ struct kgsl_devinfo info = {0};
+ struct kgsl_device_getproperty device_info = {
+ .type = KGSL_PROP_DEVICE_INFO, .value = &info, .sizebytes = sizeof(info),
+ };
+ if (ioctl(pin.fd, IOCTL_KGSL_DEVICE_GETPROPERTY, &device_info) < 0) return false;
+ unsigned int core = info.chip_id >> 24;
+ if (!core) core = info.gpu_id / 100;
+ if (core < 3) { errno = ENODEV; return false; }
+ pin.nop = core >= 5 ? 0x70100001 : 0xc0001000;
+ struct kgsl_drawctxt_create context = {
+ .flags = KGSL_CONTEXT_NO_GMEM_ALLOC | KGSL_CONTEXT_PREAMBLE | KGSL_CONTEXT_PWR_CONSTRAINT,
+ };
+ if (ioctl(pin.fd, IOCTL_KGSL_DRAWCTXT_CREATE, &context) < 0) return false;
+ pin.context = context.drawctxt_id;
+ struct kgsl_device_constraint_pwrlevel level = { .level = KGSL_CONSTRAINT_PWR_MAX };
+ struct kgsl_device_constraint constraint = {
+ .type = KGSL_CONSTRAINT_PWRLEVEL,
+ .context_id = pin.context,
+ .data = &level,
+ .size = sizeof(level),
+ };
+ struct kgsl_device_getproperty property = {
+ .type = KGSL_PROP_PWR_CONSTRAINT,
+ .value = &constraint,
+ .sizebytes = sizeof(constraint),
+ };
+ if (ioctl(pin.fd, IOCTL_KGSL_SETPROPERTY, &property) < 0) return false;
+ struct kgsl_gpumem_alloc_id memory = { .size = 4096 };
+ if (ioctl(pin.fd, IOCTL_KGSL_GPUMEM_ALLOC_ID, &memory) < 0) return false;
+ pin.memory = memory.id;
+ pin.gpuaddr = memory.gpuaddr;
+ pin.size = memory.mmapsize;
+ void *commands = mmap(NULL, pin.size, PROT_READ | PROT_WRITE, MAP_SHARED, pin.fd,
+ (off_t)pin.memory << 12);
+ if (commands == MAP_FAILED) return false;
+ pin.commands = commands;
+ uint32_t *words = commands;
+ words[0] = pin.nop;
+ words[1] = 0;
+ struct kgsl_gpumem_sync_cache sync = { .id = pin.memory, .op = KGSL_GPUMEM_CACHE_CLEAN };
+ if (ioctl(pin.fd, IOCTL_KGSL_GPUMEM_SYNC_CACHE, &sync) < 0) return false;
+ return submit_pin();
+}
+
+static void *hold_pin(void *unused) {
+ (void)unused;
+ while (atomic_load(&running)) {
+ struct kgsl_device_waittimestamp_ctxtid wait = {
+ .context_id = pin.context,
+ .timestamp = pin.timestamp,
+ .timeout = 100,
+ };
+ if (ioctl(pin.fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait) < 0) {
+ if (errno == EINTR || errno == ETIMEDOUT) continue;
+ break;
+ }
+ usleep(25000);
+ if (atomic_load(&running) && !submit_pin()) break;
+ }
+ if (atomic_exchange(&running, false))
+ __android_log_print(ANDROID_LOG_WARN, "GpuClockPin", "constraint stopped: %s", strerror(errno));
+ release_pin();
+ return NULL;
+}
+
+bool gpu_clock_pin_set(bool on) {
+ pthread_mutex_lock(&lock);
+ if (joinable) {
+ if (on && atomic_load(&running)) {
+ pthread_mutex_unlock(&lock);
+ return true;
+ }
+ atomic_store(&running, false);
+ pthread_join(worker, NULL);
+ joinable = false;
+ }
+ bool ok = true;
+ if (on) {
+ ok = prepare_pin();
+ if (ok) {
+ atomic_store(&running, true);
+ int error = pthread_create(&worker, NULL, hold_pin, NULL);
+ if (error) {
+ atomic_store(&running, false);
+ errno = error;
+ ok = false;
+ } else {
+ joinable = true;
+ }
+ }
+ if (!ok) {
+ int error = errno;
+ release_pin();
+ errno = error;
+ }
+ }
+ pthread_mutex_unlock(&lock);
+ return ok;
+}
diff --git a/app/src/main/cpp/waylandcomp/src/gpu_clock_pin.h b/app/src/main/cpp/waylandcomp/src/gpu_clock_pin.h
new file mode 100644
index 000000000..5fe17d102
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/gpu_clock_pin.h
@@ -0,0 +1,5 @@
+#pragma once
+
+#include
+
+bool gpu_clock_pin_set(bool on);
diff --git a/app/src/main/cpp/waylandcomp/src/headpose_shm.h b/app/src/main/cpp/waylandcomp/src/headpose_shm.h
index 824232b43..22088dc6b 100644
--- a/app/src/main/cpp/waylandcomp/src/headpose_shm.h
+++ b/app/src/main/cpp/waylandcomp/src/headpose_shm.h
@@ -24,7 +24,6 @@ struct droiddeck_headpose {
float eye_aspect;
uint32_t eye_w, eye_h;
float display_hz;
- // Uses a formerly reserved word; older publishers leave this zero.
uint32_t render_height;
uint32_t reserved[10];
};
diff --git a/app/src/main/cpp/waylandcomp/src/hudframes.c b/app/src/main/cpp/waylandcomp/src/hudframes.c
new file mode 100644
index 000000000..ffbb657a5
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/hudframes.c
@@ -0,0 +1,97 @@
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "hudframes.h"
+
+#define HUD_FRAMES_MAGIC 0x46484444u
+#define HUD_FRAMES_HEADER 128u
+#define HUD_FRAMES_ENTRY 16u
+
+struct hud_frames {
+ const uint8_t *map;
+ size_t size;
+ uint64_t seen;
+};
+
+static uint32_t load32(const uint8_t *p) { return __atomic_load_n((const uint32_t *)p, __ATOMIC_ACQUIRE); }
+static uint64_t load64(const uint8_t *p) { return __atomic_load_n((const uint64_t *)p, __ATOMIC_ACQUIRE); }
+
+struct hud_frames *hud_frames_open(const char *path) {
+ int fd = open(path, O_RDONLY | O_CLOEXEC);
+ if (fd < 0) return NULL;
+ struct stat st;
+ void *map = MAP_FAILED;
+ if (fstat(fd, &st) == 0 && st.st_size >= (off_t)HUD_FRAMES_HEADER)
+ map = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_SHARED, fd, 0);
+ close(fd);
+ if (map == MAP_FAILED) return NULL;
+ struct hud_frames *h = calloc(1, sizeof(*h));
+ if (!h) {
+ munmap(map, (size_t)st.st_size);
+ return NULL;
+ }
+ h->map = map;
+ h->size = (size_t)st.st_size;
+ return h;
+}
+
+void hud_frames_close(struct hud_frames *h) {
+ if (!h) return;
+ munmap((void *)h->map, h->size);
+ free(h);
+}
+
+static uint32_t capacity(const struct hud_frames *h) {
+ if (load32(h->map) != HUD_FRAMES_MAGIC) return 0;
+ uint32_t cap;
+ memcpy(&cap, h->map + 8, 4);
+ if (cap == 0 || HUD_FRAMES_HEADER + (size_t)cap * HUD_FRAMES_ENTRY > h->size) return 0;
+ return cap;
+}
+
+int hud_frames_poll(struct hud_frames *h, int64_t *frametimes, int64_t *times, int max) {
+ uint32_t cap = capacity(h);
+ if (!cap || max <= 0) return -1;
+ uint64_t count = load64(h->map + 16);
+ if (count < h->seen) h->seen = 0;
+ uint64_t from = h->seen;
+ if (count - from > cap) from = count - cap;
+ if (count - from > (uint64_t)max) from = count - (uint64_t)max;
+ int n = 0;
+ for (uint64_t i = from; i < count; i++, n++) {
+ const uint8_t *e = h->map + HUD_FRAMES_HEADER + (i % cap) * HUD_FRAMES_ENTRY;
+ memcpy(&frametimes[n], e, 8);
+ memcpy(×[n], e + 8, 8);
+ }
+ uint64_t after = load64(h->map + 16);
+ uint64_t valid = after > cap ? after - cap : 0;
+ if (from < valid) {
+ int skip = (int)(valid - from < (uint64_t)n ? valid - from : (uint64_t)n);
+ memmove(frametimes, frametimes + skip, (size_t)(n - skip) * sizeof(int64_t));
+ memmove(times, times + skip, (size_t)(n - skip) * sizeof(int64_t));
+ n -= skip;
+ }
+ h->seen = count;
+ return n;
+}
+
+int hud_frames_info(const struct hud_frames *h, int32_t *info, char *engine, size_t engine_len) {
+ if (!capacity(h) || engine_len == 0) return 0;
+ for (int tries = 0; tries < 8; tries++) {
+ uint32_t seq = load32(h->map + 24);
+ if (seq & 1u) continue;
+ memcpy(&info[0], h->map + 12, 4);
+ memcpy(&info[1], h->map + 28, 16);
+ size_t n = engine_len - 1 < 40 ? engine_len - 1 : 40;
+ memcpy(engine, h->map + 44, n);
+ engine[n] = '\0';
+ __atomic_thread_fence(__ATOMIC_ACQUIRE);
+ if (__atomic_load_n((const uint32_t *)(h->map + 24), __ATOMIC_RELAXED) == seq) return 1;
+ }
+ return 0;
+}
diff --git a/app/src/main/cpp/waylandcomp/src/hudframes.h b/app/src/main/cpp/waylandcomp/src/hudframes.h
new file mode 100644
index 000000000..518f7be52
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/hudframes.h
@@ -0,0 +1,14 @@
+#ifndef DROIDDECK_HUDFRAMES_H
+#define DROIDDECK_HUDFRAMES_H
+
+#include
+#include
+
+struct hud_frames;
+
+struct hud_frames *hud_frames_open(const char *path);
+void hud_frames_close(struct hud_frames *h);
+int hud_frames_poll(struct hud_frames *h, int64_t *frametimes, int64_t *times, int max);
+int hud_frames_info(const struct hud_frames *h, int32_t *info, char *engine, size_t engine_len);
+
+#endif
diff --git a/app/src/main/cpp/waylandcomp/src/hudframes_jni.c b/app/src/main/cpp/waylandcomp/src/hudframes_jni.c
new file mode 100644
index 000000000..7bd9149d9
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/hudframes_jni.c
@@ -0,0 +1,55 @@
+#include
+#include
+#include
+
+#include "hudframes.h"
+
+JNIEXPORT jlong JNICALL
+Java_com_droiddeck_launcher_hud_HudFrames_nativeOpen(JNIEnv *env, jclass clazz, jstring path) {
+ (void)clazz;
+ const char *p = path ? (*env)->GetStringUTFChars(env, path, NULL) : NULL;
+ if (!p) return 0;
+ struct hud_frames *h = hud_frames_open(p);
+ (*env)->ReleaseStringUTFChars(env, path, p);
+ return (jlong)(intptr_t)h;
+}
+
+JNIEXPORT void JNICALL
+Java_com_droiddeck_launcher_hud_HudFrames_nativeClose(JNIEnv *env, jclass clazz, jlong handle) {
+ (void)env; (void)clazz;
+ hud_frames_close((struct hud_frames *)(intptr_t)handle);
+}
+
+JNIEXPORT jint JNICALL
+Java_com_droiddeck_launcher_hud_HudFrames_nativePoll(JNIEnv *env, jclass clazz, jlong handle,
+ jlongArray frametimes, jlongArray times) {
+ (void)clazz;
+ struct hud_frames *h = (struct hud_frames *)(intptr_t)handle;
+ if (!h || !frametimes || !times) return -1;
+ jsize max = (*env)->GetArrayLength(env, frametimes);
+ jsize max2 = (*env)->GetArrayLength(env, times);
+ if (max2 < max) max = max2;
+ if (max <= 0) return -1;
+ int64_t *ft = malloc(sizeof(int64_t) * (size_t)max);
+ int64_t *tm = malloc(sizeof(int64_t) * (size_t)max);
+ int n = ft && tm ? hud_frames_poll(h, ft, tm, max) : -1;
+ if (n > 0) {
+ (*env)->SetLongArrayRegion(env, frametimes, 0, n, (const jlong *)ft);
+ (*env)->SetLongArrayRegion(env, times, 0, n, (const jlong *)tm);
+ }
+ free(ft);
+ free(tm);
+ return n;
+}
+
+JNIEXPORT jstring JNICALL
+Java_com_droiddeck_launcher_hud_HudFrames_nativeInfo(JNIEnv *env, jclass clazz, jlong handle, jintArray info) {
+ (void)clazz;
+ const struct hud_frames *h = (const struct hud_frames *)(intptr_t)handle;
+ if (!h || !info || (*env)->GetArrayLength(env, info) < 5) return NULL;
+ int32_t values[5];
+ char engine[41];
+ if (!hud_frames_info(h, values, engine, sizeof(engine))) return NULL;
+ (*env)->SetIntArrayRegion(env, info, 0, 5, (const jint *)values);
+ return (*env)->NewStringUTF(env, engine);
+}
diff --git a/app/src/main/cpp/waylandcomp/src/quest_device.h b/app/src/main/cpp/waylandcomp/src/quest_device.h
index ee9c37b10..bcdcee239 100644
--- a/app/src/main/cpp/waylandcomp/src/quest_device.h
+++ b/app/src/main/cpp/waylandcomp/src/quest_device.h
@@ -3,7 +3,6 @@
#include
#include
-/* Presentation only; this does not select a GPU driver or expand driver support. */
static inline int quest_device_matches(const char *model, const char *device, const char *maker) {
return !strcasecmp(model, "Quest 2") || !strcasecmp(model, "Quest 3") ||
!strcasecmp(model, "Quest 3S") ||
diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c
index f9d203ba1..ff90d37dc 100644
--- a/app/src/main/cpp/waylandcomp/src/sc_layer.c
+++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c
@@ -291,7 +291,7 @@ int sc_layer_base_black(int width, int height) {
ARect src = {0, 0, 16, 16}, dst = {0, 0, width, height};
api.setBuffer(tx, g_base_sc, black, -1);
api.setBufferTransparency(tx, g_base_sc, ASC_TRANSPARENCY_OPAQUE);
- api.setZOrder(tx, g_base_sc, 0); /* GAME = 1, OVERLAY = 2 */
+ api.setZOrder(tx, g_base_sc, 0);
api.setGeometry(tx, g_base_sc, &src, &dst, 0);
api.setVisibility(tx, g_base_sc, ASC_VISIBILITY_SHOW);
api.txApply(tx); api.txDelete(tx);
@@ -973,7 +973,7 @@ void sc_layer_hide_overlay(void) {
}
void sc_layer_window_gone(void) {
- base_hide(1); /* the backdrop belongs to the old window, just like GAME and OVERLAY */
+ base_hide(1);
if (api.state != 1) return;
layers_init();
for (int i = SC_LAYER_COUNT - 1; i >= 0; i--) retire_sc(&g_layers[i]);
diff --git a/app/src/main/cpp/waylandcomp/src/vk_loader.h b/app/src/main/cpp/waylandcomp/src/vk_loader.h
index e10950d0d..54cb88881 100644
--- a/app/src/main/cpp/waylandcomp/src/vk_loader.h
+++ b/app/src/main/cpp/waylandcomp/src/vk_loader.h
@@ -21,7 +21,7 @@
X(BindImageMemory) X(DestroyImage) X(FreeMemory) X(AcquireNextImageKHR) \
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
- X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) \
+ X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \
\
X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \
diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c
index 96d0b415d..df1c0d817 100644
--- a/app/src/main/cpp/waylandcomp/src/vk_present.c
+++ b/app/src/main/cpp/waylandcomp/src/vk_present.c
@@ -7,6 +7,7 @@
#include "framegen_bridge.h"
#include "hdr_compose.h"
#include "blend_pass.h"
+#include "gpu_busy.h"
#include "droiddeck_color.h"
#include "quest_device.h"
#include
@@ -19,6 +20,7 @@
#include
#include
#include
+#include
#define TAG "DroidDeckWayland"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
@@ -39,6 +41,7 @@ struct vkp_image {
};
static ANativeWindow *g_window;
+static int g_ahb_import;
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
static int g_dev_state;
static VkInstance g_inst;
@@ -68,8 +71,6 @@ static int g_first_frame_done;
static int g_base_black;
int vkp_quest_layer_presentation(void) {
- /* Compositor thread only; this is a process-wide device property, not a session setting.
- * Quest 2 still needs its separate A6xx driver: this gate only chooses presentation. */
static int enabled = -1;
if (enabled < 0) {
char model[PROP_VALUE_MAX] = {0}, device[PROP_VALUE_MAX] = {0}, maker[PROP_VALUE_MAX] = {0};
@@ -382,6 +383,13 @@ int vkp_output_to_scene(double ox, double oy, double *sx, double *sy) {
return 1;
}
+int vkp_scene_to_output(double sx, double sy, double *ox, double *oy) {
+ if (!g_map.valid || g_map.kx <= 0 || g_map.ky <= 0) return 0;
+ *ox = sx * g_map.kx + g_map.off_x;
+ *oy = sy * g_map.ky + g_map.off_y;
+ return 1;
+}
+
void vkp_output_size(int *w, int *h) {
*w = (int)g_extent.width;
*h = (int)g_extent.height;
@@ -459,17 +467,18 @@ static int dev_init(void) {
}
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
- const char *dev_exts[7] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
- "VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier",
- "VK_KHR_image_format_list", NULL, NULL};
- uint32_t n_dev_exts = 5;
+ static const char *const import_exts[4] = {"VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf",
+ "VK_EXT_image_drm_format_modifier", "VK_KHR_image_format_list"};
+ const char *dev_exts[9] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
+ uint32_t n_dev_exts = 1;
uint32_t ne = 0;
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
- for (unsigned i = 0; i < 5; i++)
- if (!has_ext(exts, ne, dev_exts[i]))
- LOGE("present: driver MISSING %s (dmabuf import will fail)", dev_exts[i]);
+ for (unsigned i = 0; i < 4; i++) {
+ if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i];
+ else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
+ }
int want_hdr_md = 0;
if (droiddeck_color_requested()) {
want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME);
@@ -477,6 +486,12 @@ static int dev_init(void) {
}
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
+ g_ahb_import = has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
+ has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
+ if (g_ahb_import) {
+ dev_exts[n_dev_exts++] = VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;
+ dev_exts[n_dev_exts++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;
+ }
free(exts);
float prio = 1.0f;
@@ -499,6 +514,7 @@ static int dev_init(void) {
}
vk_loader_load_device(g_dev);
g_vk.GetDeviceQueue(g_dev, g_qfam, 0, &g_queue);
+ vkp_gpu_busy_device(g_pd, g_dev, g_qfam);
if (want_sem_fd) {
g_import_sem_fd = (PFN_vkImportSemaphoreFdKHR)g_vk.GetDeviceProcAddr(g_dev, "vkImportSemaphoreFdKHR");
VkSemaphoreCreateInfo wsci = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
@@ -987,6 +1003,60 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
return img;
}
+void vkp_wait_idle(void) {
+ if (g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
+}
+
+struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
+ if (!ahb || dev_init() != 0) return NULL;
+ if (!g_ahb_import || !g_vk.GetAndroidHardwareBufferPropertiesANDROID) {
+ static int said;
+ if (!said) { said = 1; LOGE("ahb: the driver cannot import AHardwareBuffers (VK_ANDROID_external_memory_android_hardware_buffer)"); }
+ return NULL;
+ }
+ AHardwareBuffer_Desc desc;
+ AHardwareBuffer_describe(ahb, &desc);
+ VkAndroidHardwareBufferFormatPropertiesANDROID fp = {
+ .sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
+ VkAndroidHardwareBufferPropertiesANDROID props = {
+ .sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &fp};
+ VkResult pr = g_vk.GetAndroidHardwareBufferPropertiesANDROID(g_dev, ahb, &props);
+ if (pr != VK_SUCCESS || fp.format == VK_FORMAT_UNDEFINED) {
+ LOGE("ahb: %ux%u format %u: properties %s, Vulkan format %d", desc.width, desc.height, desc.format,
+ vk_result_name(pr), (int)fp.format);
+ return NULL;
+ }
+ struct vkp_image *img = calloc(1, sizeof(*img));
+ if (!img) return NULL;
+ img->w = (int)desc.width; img->h = (int)desc.height; img->dmabuf = 1; img->fmt = fp.format; img->sampled = 1;
+ VkExternalMemoryImageCreateInfo ext = {
+ .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
+ .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
+ VkImageCreateInfo ici = {
+ .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &ext,
+ .imageType = VK_IMAGE_TYPE_2D, .format = fp.format, .extent = {desc.width, desc.height, 1},
+ .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
+ .usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
+ .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
+ VkResult cr = g_vk.CreateImage(g_dev, &ici, NULL, &img->image);
+ if (cr != VK_SUCCESS) { LOGE("ahb: vkCreateImage %ux%u -> %s", desc.width, desc.height, vk_result_name(cr)); free(img); return NULL; }
+ int idx = -1;
+ for (int i = 0; i < 32; i++) if (props.memoryTypeBits & (1u << i)) { idx = i; break; }
+ VkImportAndroidHardwareBufferInfoANDROID imp = {
+ .sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = ahb};
+ VkMemoryDedicatedAllocateInfo ded = {.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
+ .pNext = &imp, .image = img->image};
+ VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &ded,
+ .allocationSize = props.allocationSize, .memoryTypeIndex = (uint32_t)(idx < 0 ? 0 : idx)};
+ VkResult mr = idx < 0 ? VK_ERROR_FEATURE_NOT_PRESENT : g_vk.AllocateMemory(g_dev, &mai, NULL, &img->mem);
+ if (mr != VK_SUCCESS || g_vk.BindImageMemory(g_dev, img->image, img->mem, 0) != VK_SUCCESS) {
+ LOGE("ahb: importing %ux%u -> %s", desc.width, desc.height, vk_result_name(mr));
+ if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
+ g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return NULL;
+ }
+ return img;
+}
+
static int shm_sampled(void) {
static int known;
if (!known) {
@@ -1239,6 +1309,7 @@ static void device_lost(const char *where) {
g_dev_state = -2;
g_base_black = 0;
vkp_framegen_device_lost();
+ vkp_gpu_busy_device_lost();
droiddeck_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
"restart the session", where);
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
@@ -1626,6 +1697,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
VkImageLayout result_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
if (fx) {
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
+ if (fg) { mapped_w = scene_w; mapped_h = scene_h; }
vkp_effects_set_formats(scene_fmt, scene_fmt);
result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h, &rw, &rh);
result_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
@@ -1724,9 +1796,6 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int vkp_render(int scene_w, int scene_h, const struct vkp_draw *draws, int n) {
if (vkp_quest_layer_presentation() && !vkp_framegen_active() && !vkp_cardboard_active()) {
- /* The desktop (multiple windows), overlays and an empty scene must also avoid WSI.
- * Merely enabling zero-copy handles only a single fullscreen window and leaves both
- * the letterbox and every fallback frame going through the corrupted swapchain. */
vkp_apply_window_request();
sc_layer_hide_overlay();
if (n > 0) {
@@ -1738,9 +1807,6 @@ int vkp_render(int scene_w, int scene_h, const struct vkp_draw *draws, int n) {
} else {
sc_layer_hide();
}
- /* sc_layer_present_pass signals only after submitting client content.
- * A backdrop alone, or a successful no-op while a layer slot is unavailable,
- * must not dismiss the app's loading UI or mark Steam's window as shown. */
return vkp_base_black(scene_w, scene_h);
}
return render_impl(scene_w, scene_h, draws, n, NULL, NULL);
@@ -1777,8 +1843,6 @@ void vkp_signal_first_frame(void) {
int vkp_update_map(int scene_w, int scene_h) {
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
if (vkp_quest_layer_presentation()) {
- /* Layer geometry needs the window size, not a Vulkan swapchain. In particular, do
- * not create/present a swapchain just to paint black under an otherwise clean layer. */
int w = ANativeWindow_getWidth(g_window), h = ANativeWindow_getHeight(g_window);
if (w <= 0 || h <= 0) return -1;
g_extent = (VkExtent2D){(uint32_t)w, (uint32_t)h};
diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.h b/app/src/main/cpp/waylandcomp/src/vk_present.h
index 48d32ab4d..5cc06ddb3 100644
--- a/app/src/main/cpp/waylandcomp/src/vk_present.h
+++ b/app/src/main/cpp/waylandcomp/src/vk_present.h
@@ -16,6 +16,7 @@ enum vkp_align { VKP_ALIGN_CENTER = 0, VKP_ALIGN_TOP = 1, VKP_ALIGN_BOTTOM = 2,
void vk_present_set_scale_mode(int mode, int alignment);
int vkp_game_picture_rect(float rect[4]);
int vkp_output_to_scene(double ox, double oy, double *sx, double *sy);
+int vkp_scene_to_output(double sx, double sy, double *ox, double *oy);
void vkp_output_size(int *w, int *h);
struct vkp_image;
@@ -34,6 +35,9 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
int vkp_image_is_dmabuf(const struct vkp_image *img);
struct vkp_image *vkp_image_create_shm(int w, int h);
+struct AHardwareBuffer;
+struct vkp_image *vkp_image_from_ahb(struct AHardwareBuffer *ahb);
+void vkp_wait_idle(void);
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride);
int vkp_image_width(const struct vkp_image *img);
diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
index 6a407088b..5d69098a6 100644
--- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
+++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
@@ -9,6 +9,7 @@
#include
#include
#include
+#include
#include "vk_present.h"
#include "droiddeck_ext.h"
#include "ahb_swapchain.h"
@@ -16,6 +17,7 @@
#include "effects_chain.h"
#include "cardboard.h"
#include "droiddeck_color.h"
+#include "gpu_clock_pin.h"
extern int droiddeck_wayland_run(void);
extern void droiddeck_wayland_set_scale_mode(int mode, int alignment);
@@ -23,12 +25,21 @@ extern void droiddeck_wayland_send_pointer(int action, int x, int y);
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
extern int droiddeck_cursor_snapshot(int *out, int cap);
extern int droiddeck_cursor_serial(void);
+extern int droiddeck_hud_frame_times(float *out, int len, int64_t *total);
extern void droiddeck_wayland_send_key(int evdev, int state);
+extern int droiddeck_focus_takes_touch(void);
+extern int droiddeck_cursor_input_pos(int *x, int *y);
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
+extern void droiddeck_wayland_set_cursor_composite(int on);
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
+extern void droiddeck_stream_set(int on);
+extern void droiddeck_stream_frame(AHardwareBuffer *ahb);
+extern unsigned droiddeck_stream_frames(void);
extern void droiddeck_wayland_output_resized(void);
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
extern volatile int g_fps_limit;
+extern volatile int g_release_unpaced;
+extern volatile int g_render_on_commit;
extern volatile int g_hide_shell;
extern volatile int g_zero_copy;
extern volatile unsigned g_zero_copy_last;
@@ -262,18 +273,58 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
return n;
}
+JNIEXPORT jlong JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHudFrameTimes(JNIEnv *env, jclass clazz, jfloatArray out) {
+ (void)clazz;
+ if (!out) return 0;
+ jint cap = (*env)->GetArrayLength(env, out);
+ float *buf = cap > 0 ? malloc(sizeof(float) * (size_t)cap) : NULL;
+ if (!buf) return 0;
+ int64_t total = 0;
+ int n = droiddeck_hud_frame_times(buf, cap, &total);
+ if (n > 0) (*env)->SetFloatArrayRegion(env, out, 0, n, buf);
+ free(buf);
+ return (jlong)total;
+}
+
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) {
(void)env; (void)clazz;
return droiddeck_cursor_serial();
}
+JNIEXPORT void JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCursorComposite(
+ JNIEnv *env, jclass clazz, jboolean on) {
+ (void)env; (void)clazz;
+ droiddeck_wayland_set_cursor_composite(on ? 1 : 0);
+}
+
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey(
JNIEnv *env, jclass clazz, jint evdev, jint state) {
droiddeck_wayland_send_key(evdev, state);
}
+JNIEXPORT jboolean JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFocusTakesTouch(
+ JNIEnv *env, jclass clazz) {
+ (void)env; (void)clazz;
+ return droiddeck_focus_takes_touch() ? JNI_TRUE : JNI_FALSE;
+}
+
+JNIEXPORT jboolean JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorInputPos(
+ JNIEnv *env, jclass clazz, jintArray out) {
+ (void)clazz;
+ if (!out || (*env)->GetArrayLength(env, out) < 2) return JNI_FALSE;
+ int pos[2];
+ if (!droiddeck_cursor_input_pos(&pos[0], &pos[1])) return JNI_FALSE;
+ jint jpos[2] = {pos[0], pos[1]};
+ (*env)->SetIntArrayRegion(env, out, 0, 2, jpos);
+ return JNI_TRUE;
+}
+
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendSceneInput(
JNIEnv *env, jclass clazz, jint type, jint a, jint b) {
@@ -566,9 +617,16 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv *
free(s);
}
+JNIEXPORT void JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetRenderOnCommit(JNIEnv *env, jclass clazz, jboolean on) {
+ g_render_on_commit = on ? 1 : 0;
+ __android_log_print(ANDROID_LOG_INFO, TAG, "render on commit %s", on ? "on" : "off");
+}
+
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) {
g_fps_limit = fps > 0 ? fps : 0;
+ g_release_unpaced = fps < 0;
__android_log_print(ANDROID_LOG_INFO, TAG, "fps limit %d", fps);
}
@@ -634,8 +692,13 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIE
extern void adrenotools_set_turbo(bool turbo);
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) {
- (void)env; (void)clazz;
- adrenotools_set_turbo(on == JNI_TRUE);
+ (void)clazz;
+ if (!gpu_clock_pin_set(on == JNI_TRUE)) {
+ int saved_errno = errno;
+ jclass error = (*env)->FindClass(env, "java/lang/IllegalStateException");
+ if (error) (*env)->ThrowNew(env, error, strerror(saved_errno));
+ }
+ if (on != JNI_TRUE) adrenotools_set_turbo(false);
}
JNIEXPORT jint JNICALL
@@ -660,3 +723,20 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardSpatialP
(*env)->GetFloatArrayRegion(env, pos, 0, 3, p);
vkp_cardboard_set_spatial_pose(m, p, live ? 1 : 0);
}
+
+JNIEXPORT void JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamMode(JNIEnv *env, jclass clazz, jboolean on) {
+ droiddeck_stream_set(on ? 1 : 0);
+}
+
+JNIEXPORT void JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrame(JNIEnv *env, jclass clazz, jobject hardwareBuffer) {
+ if (!hardwareBuffer) return;
+ AHardwareBuffer *ahb = AHardwareBuffer_fromHardwareBuffer(env, hardwareBuffer);
+ if (ahb) droiddeck_stream_frame(ahb);
+}
+
+JNIEXPORT jint JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv *env, jclass clazz) {
+ return (jint)droiddeck_stream_frames();
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt
index 3fc438377..0cfb32fe7 100644
--- a/app/src/main/java/com/droiddeck/launcher/App.kt
+++ b/app/src/main/java/com/droiddeck/launcher/App.kt
@@ -17,7 +17,8 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
- // Helper processes must not initialize the main USB provider or guest graphics context.
+ com.droiddeck.launcher.ui.BuildWatermark.install(this)
+ HomeApp.trackRecents(this)
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
.runningAppProcesses?.firstOrNull { it.pid == android.os.Process.myPid() }?.processName
@@ -25,9 +26,20 @@ class App : Application() {
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xbox")
return
}
- if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
+ if (process == "$packageName:xboxcloud") {
+ if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xboxcloud")
+ return
+ }
+ if (process == "$packageName:xcloudnative") {
+ com.droiddeck.launcher.stores.StoresState.init(this)
+ return
+ }
+ if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" ||
+ process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return
CrashHandler.install(this)
+ com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
+ com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.update.AppUpdates.init(this)
com.droiddeck.launcher.core.DownloadSource.init(this)
@@ -36,6 +48,7 @@ class App : Application() {
com.droiddeck.launcher.glasses.Glasses.init(this)
com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this)
BwrapSpawner.start(this)
+ com.droiddeck.launcher.runtime.RootSpawner.start(this)
com.droiddeck.launcher.frontend.GameFileSync.start(this)
com.droiddeck.launcher.stores.StoresState.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend)
@@ -43,15 +56,16 @@ class App : Application() {
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
+ com.droiddeck.launcher.sync.Syncthing.init(this)
+ com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
}
- /** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
private fun prefetchAddonPacks() {
val app = this
Thread({
runCatching {
if (com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).isDirectory) {
- com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
+ if (!com.droiddeck.launcher.runtime.LinuxRuntime.patchedProot(app)) com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
com.droiddeck.launcher.core.AddonPack.DIRECTAUDIO.ensure(app)
}
if (com.droiddeck.launcher.stores.gog.GogComet.enabled(app)) com.droiddeck.launcher.core.AddonPack.COMET.ensure(app)
diff --git a/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt b/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt
index 7ccbba7f5..344aa7452 100644
--- a/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt
+++ b/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt
@@ -55,6 +55,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
private set
private var runtimePending by mutableStateOf(false)
private var sessionRunning by mutableStateOf(false)
+ var tpUbwcMode: String by mutableStateOf(SessionPrefs.TP_UBWC_AUTO)
+ private set
val uiMode: String get() = when (mode) {
SessionPrefs.GPU_DRIVERS_AUTO -> GPU_MODE_AUTO
@@ -73,8 +75,16 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
mode = uiMode, display = displaySlot(), runtime = runtimeSlot(),
canRestart = !sessionRunning,
checkedAt = TurnipReleases.cached(activity)?.checkedAt ?: 0L,
+ tpUbwcMode = tpUbwcMode.takeIf { gpu.model == 740 },
+ tpUbwcRestartRequired = com.droiddeck.launcher.gpu.TpUbwcHint.restartRequired(activity),
)
+ fun chooseTpUbwcMode(mode: String) {
+ if (gpu.model != 740) return
+ SessionPrefs.setTpUbwcMode(activity, mode)
+ tpUbwcMode = mode
+ }
+
private fun slotSource(chosenDefault: Boolean, defaultLabel: Int): String = activity.getString(when {
uiMode == GPU_MODE_AUTO -> R.string.gpu_src_auto
uiMode == GPU_MODE_PAIR && pairRows.any { it.active } -> R.string.gpu_src_pair
@@ -124,6 +134,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
var androidSelected by mutableStateOf("")
fun refreshDrivers() {
+ tpUbwcMode = SessionPrefs.tpUbwcMode(activity)
val lm = LinuxVulkanDriverManager(activity)
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
val bundles = DriverBundle.all(activity)
diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
index c27fc3d32..1d9e32577 100644
--- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt
@@ -44,6 +44,7 @@ import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.ComponentsPage
import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.session.SessionLogShare
+import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.core.CpuCores
@@ -52,6 +53,7 @@ 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
import com.droiddeck.launcher.core.WirelessAdbPairingService
import com.droiddeck.launcher.ui.CoreRow
import com.droiddeck.launcher.ui.PerformancePage
@@ -77,6 +79,7 @@ import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.GameStorage
+import com.droiddeck.launcher.session.SteamLibraries
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
@@ -91,17 +94,24 @@ class FrontEndActivity : ComponentActivity() {
private val components = ComponentsMenu(this, ui)
private val decky = DeckyMenu(this, ui)
private val updates = UpdatesMenu(this, ui)
- private val protons = ProtonMenu(this, ui)
+ private val protons = ProtonMenu(this, ui) { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null }
private var installed by mutableStateOf(null)
private var flood by mutableStateOf(null)
private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f)
private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent)
+ private class CompatLaunch(val intent: Intent, val loading: com.droiddeck.launcher.session.LoadingState, var menuInstall: Boolean)
+ private var compatLaunch by mutableStateOf(null)
+ private var compatFlood by mutableStateOf(null)
+ private var compatLaunchPoll: Runnable? = null
+ private var compatLaunchVisible = false
private var returning by mutableStateOf(null)
private class ReturningFlood(val color: Int, val to: androidx.compose.ui.geometry.Rect?)
private var ready by mutableStateOf(false)
private var removalPending by mutableStateOf(false)
private var available by mutableStateOf(null)
+ private var catalogFresh = false
+ private var componentsQueueBusy by mutableStateOf(false)
private var busy by mutableStateOf(false)
private var stage by mutableStateOf("")
private var percent by mutableIntStateOf(-1)
@@ -120,6 +130,7 @@ class FrontEndActivity : ComponentActivity() {
private var glThread by mutableStateOf(true)
private var noGlError by mutableStateOf(true)
private var returnAfterGame by mutableStateOf(true)
+ private var shaderPrecache by mutableStateOf(null)
private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true)
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
@@ -133,11 +144,17 @@ class FrontEndActivity : ComponentActivity() {
private var catalog by mutableStateOf?>(null)
private var catalogLoading by mutableStateOf(false)
private var packageRows by mutableStateOf?>(null)
- private var pkgId by mutableStateOf(null)
- private var pkgStage by mutableStateOf(null)
- private var pkgPercent by mutableIntStateOf(-1)
+ private object PackageOperation {
+ val id = mutableStateOf(null)
+ val stage = mutableStateOf(null)
+ val percent = mutableIntStateOf(-1)
+ }
+ private var pkgId by PackageOperation.id
+ private var pkgStage by PackageOperation.stage
+ private var pkgPercent by PackageOperation.percent
private var desktopInstalled by mutableStateOf(false)
private var desktopPresent by mutableStateOf(false)
+ private var battleNetInstalled by mutableStateOf(false)
private var offlineAccount by mutableStateOf(null)
private var offline by mutableStateOf(false)
private var showPerformance by mutableStateOf(false)
@@ -151,9 +168,13 @@ class FrontEndActivity : ComponentActivity() {
private var syncFallback by mutableStateOf(true)
private var fsyncFirst by mutableStateOf(false)
private var gamescopeRealtime by mutableStateOf(false)
+ private var ramCapMb by mutableStateOf(0)
+ private var zramClient by mutableStateOf(true)
+ private var vramCapMb by mutableStateOf(0)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
+ private var cursorComposite by mutableStateOf(false)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf(null)
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
@@ -161,26 +182,29 @@ class FrontEndActivity : ComponentActivity() {
private var directAudio by mutableStateOf(false)
private var picturePosition by mutableStateOf("center")
private var stretch16x9 by mutableStateOf(false)
- private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
+ private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
+ private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
private var launcherFullscreen by mutableStateOf(true)
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("")
private var downloadPrefix by mutableStateOf("")
+ private var downloadProxy by mutableStateOf("")
private var animationsEnabled by mutableStateOf(true)
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast")
- private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
private var navRequest by mutableStateOf(null)
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
- private var storesView by mutableStateOf(SessionPrefs.STORES_VIEWS.first())
+ private var storesView by mutableStateOf(SessionPrefs.DEFAULT_STORES_VIEW)
private var mic by mutableStateOf(false)
private var wifiDiscovery by mutableStateOf(false)
private var wifiDiscoveryPermission by mutableStateOf(false)
private var wifiDiscoveryLocation by mutableStateOf(false)
private var wifiDiscoveryAsked by mutableStateOf(false)
private var wifiDiscoveryBlocked by mutableStateOf(false)
+ private var integrationState by mutableStateOf(SteamIntegration.State())
+ private var integrationFocus by mutableStateOf(null)
private val wifiLocationReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
refreshWifiDiscovery()
@@ -192,6 +216,7 @@ class FrontEndActivity : ComponentActivity() {
}
private val mediaReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
+ usbScan++
ui.removeCallbacks(mediaRefresh)
ui.postDelayed(mediaRefresh, MEDIA_SETTLE_MS)
}
@@ -249,8 +274,68 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.setWifiDiscoveryEnabled(this, false)
}
wifiDiscovery = SessionPrefs.wifiDiscoveryEnabled(this)
+ integrationState = readIntegration()
}
+ private var shortcutsTried = false
+
+ private fun readIntegration() = SteamIntegration.read(this)
+ .copy(locationBlocked = wifiDiscoveryBlocked, shortcutsTried = shortcutsTried)
+
+ private fun openIntegration(feature: SteamIntegration.Feature? = null) {
+ SteamIntegration.dismissSuggestion(this)
+ refreshWifiDiscovery()
+ integrationState = readIntegration()
+ integrationFocus = feature
+ navRequest = "setup:integration"
+ }
+
+ private fun readIntegrationIntent(incoming: Intent) {
+ if (incoming.action != SteamIntegration.ACTION_SETUP) return
+ openIntegration(incoming.getStringExtra(SteamIntegration.EXTRA_FEATURE)?.let {
+ runCatching { SteamIntegration.Feature.valueOf(it) }.getOrNull()
+ })
+ }
+
+ private fun integrationSettings(intent: Intent, fallback: String = android.provider.Settings.ACTION_SETTINGS) {
+ try { startActivity(intent) }
+ catch (_: android.content.ActivityNotFoundException) { startActivity(Intent(fallback)) }
+ catch (_: SecurityException) { startActivity(Intent(fallback)) }
+ }
+
+ private fun configureIntegration(feature: SteamIntegration.Feature) {
+ when (feature) {
+ SteamIntegration.Feature.WIFI -> {
+ if (wifiDiscovery && wifiDiscoveryPermission) {
+ SessionPrefs.setWifiDiscoveryEnabled(this, false)
+ } else if (wifiDiscoveryPermission) {
+ SessionPrefs.setWifiDiscoveryEnabled(this, true)
+ } else {
+ SessionPrefs.setWifiDiscoveryAsked(this)
+ wifiLocationPermission.launch(WifiDiscovery.permissions)
+ }
+ refreshWifiDiscovery()
+ }
+ SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
+ SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else {
+ HomeApp.setHomeScreenEnabled(this, true)
+ refreshHomeAppState()
+ manageHomeApp()
+ }
+ SteamIntegration.Feature.SHORTCUTS -> {
+ if (!integrationState.shortcuts) shortcutsTried = true
+ if (!HomeApp.isDefault(this)) configureIntegration(SteamIntegration.Feature.HOME)
+ else {
+ SteamIntegration.setShortcutsListed(this, true)
+ integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
+ }
+ }
+ }
+ }
+
+ private fun openAppInfo() =
+ integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
+
private fun openWifiDiscoverySettings() {
if (!WifiDiscovery.permissionGranted(this)) {
wifiPermissionSettings.launch(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
@@ -385,7 +470,6 @@ class FrontEndActivity : ComponentActivity() {
private var theme by mutableStateOf("graphite")
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
private var hdrOn by mutableStateOf(false)
- private var fpsLimit by mutableStateOf(0)
private var upscaler by mutableStateOf(0)
private var upscaleSharpness by mutableStateOf(75)
private var hdrReason by mutableStateOf(null)
@@ -393,13 +477,38 @@ class FrontEndActivity : ComponentActivity() {
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
+ private var backHold by mutableStateOf(true)
private var backActionsInverted by mutableStateOf(false)
private var gameStorage by mutableStateOf("")
+ private var slowUsb by mutableStateOf(null)
+ private var usbScan = 0
+ private var slowUsbNever by mutableStateOf(false)
+
+ private fun showSlowUsb(drive: com.droiddeck.launcher.session.UsbLink.SlowDrive?) {
+ val off = slowUsbNever
+ if (off) SessionPrefs.setSlowUsbWarningOff(this)
+ slowUsbNever = false
+ slowUsb = drive.takeUnless { off }
+ }
private var storageDiagnostics by mutableStateOf(false)
private var storageOptions by mutableStateOf>(emptyList())
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
}
+ private var steamLibraries by mutableStateOf>(emptyList())
+ private val pickSteamLibrary = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
+ val path = if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data) else null
+ if (path != null) Thread({
+ val result = SteamLibraries.add(this, path)
+ ui.post {
+ steamLibraries = SteamLibraries.list(this)
+ refresh()
+ if (result is SteamLibraries.AddResult.Refused) {
+ android.widget.Toast.makeText(this, getString(R.string.main_storage_not_usable, result.reason), android.widget.Toast.LENGTH_LONG).show()
+ }
+ }
+ }, "steam-library-add").start()
+ }
private var romsDir by mutableStateOf(null)
private var steamGames by mutableStateOf>(emptyList())
private var steamGamesX64 by mutableStateOf(false)
@@ -408,38 +517,74 @@ class FrontEndActivity : ComponentActivity() {
private var emulatorList by mutableStateOf>(emptyList())
private var runningLabel by mutableStateOf(null)
private var logsEnabled by mutableStateOf(true)
+ private var gameDebugLogsEnabled by mutableStateOf(false)
+ private var gameDebugLogsNeedsRestart by mutableStateOf(false)
private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false)
private var bluetoothAllowed by mutableStateOf(null)
private var allFilesAllowed by mutableStateOf(null)
+ private var localNetworkAllowed by mutableStateOf(null)
+ private var clearCachedApps by mutableStateOf(false)
+ private var adbPaired by mutableStateOf(false)
+ private var memoryHud by mutableStateOf(SessionPrefs.MEMORY_HUD_OFF)
+ private var backgroundAppLimit by mutableStateOf(com.droiddeck.launcher.core.BackgroundAppLimit.OFF)
private var showRoms by mutableStateOf(false)
private var homeAppSelected by mutableStateOf(false)
private var homeScreenEnabled by mutableStateOf(false)
private var defaultHomeLabel by mutableStateOf(null)
private var androidApps by mutableStateOf>(emptyList())
+ private var androidAppsListing = 0
+ private val packageCallback = object : android.content.pm.LauncherApps.Callback() {
+ private fun changed() {
+ refreshAndroidApps()
+ if (HomeWidgets.providers != null) HomeWidgets.refreshProviders(this@FrontEndActivity)
+ }
+ override fun onPackageRemoved(packageName: String, user: android.os.UserHandle) = changed()
+ override fun onPackageAdded(packageName: String, user: android.os.UserHandle) = changed()
+ override fun onPackageChanged(packageName: String, user: android.os.UserHandle) = changed()
+ override fun onPackagesAvailable(packageNames: Array, user: android.os.UserHandle, replacing: Boolean) = changed()
+ override fun onPackagesUnavailable(packageNames: Array, user: android.os.UserHandle, replacing: Boolean) = changed()
+ override fun onShortcutsChanged(packageName: String, shortcuts: MutableList, user: android.os.UserHandle) {
+ if (homeAppSelected) HomePins.refresh(this@FrontEndActivity)
+ }
+ }
private var secondScreenDisplays by mutableStateOf>(emptyList())
+ private var dualDisplayId by mutableStateOf(-1)
+ private var dualScreenDevice by mutableStateOf(false)
+ private var dualScreenMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
+ private var dualScreenLauncher by mutableStateOf(true)
+ private var dualScreenControls by mutableStateOf(true)
+ private var launcherStarted = false
private lateinit var displayManager: DisplayManager
private val secondScreenDisplayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays()
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays()
}
+ private val secondScreenTouchListener = object : android.hardware.input.InputManager.InputDeviceListener {
+ override fun onInputDeviceAdded(deviceId: Int) = refreshSecondScreenDisplays()
+ override fun onInputDeviceRemoved(deviceId: Int) = refreshSecondScreenDisplays()
+ override fun onInputDeviceChanged(deviceId: Int) = refreshSecondScreenDisplays()
+ }
private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
refreshHomeAppState()
}
override fun startActivity(intent: Intent?) {
+ val compat = protons.protonBusyId != null || ProtonExtras.installInProgress
if (intent?.component?.className == SessionActivity::class.java.name) {
+ if (compatLaunch != null) return
when {
busy || LinuxRuntimeInstaller.isBusy() -> {
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show()
return
}
- protons.protonBusyId != null || ProtonExtras.installInProgress -> {
- android.widget.Toast.makeText(this, R.string.main_wait_proton_install, android.widget.Toast.LENGTH_SHORT).show()
+ SessionState.installing != null && !SessionState.running -> {
+ android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
return
}
+ compat -> Unit
pkgStage != null -> {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
return
@@ -454,22 +599,119 @@ class FrontEndActivity : ComponentActivity() {
return
}
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
+ if (compat) {
+ waitForCompat(intent)
+ return
+ }
}
super.startActivity(intent)
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
}
private fun launchFlooded(f: PendingFlood) {
- if (busy || LinuxRuntimeInstaller.isBusy()) { flood = null; floodProgress = 0f; return }
+ if (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) ||
+ protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
+ flood = null
+ floodProgress = 0f
+ com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
+ if (!busy && !LinuxRuntimeInstaller.isBusy() && !(SessionState.installing != null && !SessionState.running) &&
+ (protons.protonBusyId != null || ProtonExtras.installInProgress)) {
+ compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal
+ waitForCompat(f.intent)
+ }
+ return
+ }
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
super.startActivity(f.intent.putExtra(com.droiddeck.launcher.ui.EXTRA_FLOOD, signal.toArgb()))
overridePendingTransition(0, 0)
}
+ private fun waitForCompat(next: Intent, menuInstall: Boolean = protons.protonBusyId != null) {
+ if (compatLaunch != null) return
+ com.droiddeck.launcher.ui.LaunchOrigin.take()
+ com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
+ val waiting = CompatLaunch(Intent(next), com.droiddeck.launcher.session.LoadingState(this), menuInstall)
+ compatLaunch = waiting
+ val poll = object : Runnable {
+ override fun run() {
+ if (isDestroyed || isFinishing || compatLaunch !== waiting) return
+ if (protons.protonBusyId != null || ProtonExtras.installInProgress) {
+ waiting.menuInstall = waiting.menuInstall || protons.protonBusyId != null
+ val percent = if (protons.protonBusyId != null) protons.protonPercent else -1
+ val stage = protons.protonStage ?: getString(R.string.load_compat_wait)
+ waiting.loading.say(if (percent >= 0) getString(R.string.load_compat_progress, stage, percent) else stage,
+ com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
+ waiting.loading.percent = percent
+ waiting.loading.tick()
+ ui.postDelayed(this, 250)
+ return
+ }
+ if (!compatLaunchVisible) { ui.postDelayed(this, 250); return }
+ val problem = protons.protonProblem.takeIf { waiting.menuInstall }
+ if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) || pkgStage != null)) {
+ waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime),
+ com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
+ waiting.loading.percent = if (pkgStage != null) pkgPercent else percent
+ waiting.loading.tick()
+ ui.postDelayed(this, 250)
+ return
+ }
+ compatLaunchPoll = null
+ if (problem != null) waiting.loading.showEnded(problem)
+ else {
+ compatLaunch = null
+ startActivity(waiting.intent)
+ }
+ }
+ }
+ compatLaunchPoll = poll
+ poll.run()
+ }
+
+ private fun cancelCompatLaunch() {
+ compatLaunchPoll?.let(ui::removeCallbacks)
+ compatLaunchPoll = null
+ compatLaunch = null
+ compatFlood = null
+ }
+
+ private fun restoreCompatLaunch(state: Bundle) {
+ savedIntent(state, KEY_COMPAT_LAUNCH)?.let { next ->
+ val problem = state.getString(KEY_COMPAT_PROBLEM)
+ if (problem == null) waitForCompat(next, state.getBoolean(KEY_COMPAT_MENU_INSTALL))
+ else compatLaunch = CompatLaunch(next,
+ com.droiddeck.launcher.session.LoadingState(this).apply { showEnded(problem) }, false)
+ }
+ }
+
+ private fun saveCompatLaunch(state: Bundle) {
+ compatLaunch?.let {
+ state.putParcelable(KEY_COMPAT_LAUNCH, it.intent)
+ state.putBoolean(KEY_COMPAT_MENU_INSTALL, it.menuInstall)
+ if (it.loading.ended) state.putString(KEY_COMPAT_PROBLEM, it.loading.step)
+ }
+ }
+
private var shortcutPicker by mutableStateOf(false)
private var shortcutLibraryScanning by mutableStateOf(false)
@Volatile private var libraryScanGeneration = 0
+ @Volatile private var lastComponentRestore = 0L
+ @Volatile private var componentRestoreRetry = false
+ private val componentRestoreLock = Any()
+
+ private fun retryComponentRestore() {
+ val run = synchronized(componentRestoreLock) {
+ componentRestoreRetry = false
+ val now = android.os.SystemClock.elapsedRealtime()
+ (!isDestroyed && now - lastComponentRestore >= COMPONENT_RESTORE_MS).also { if (it) lastComponentRestore = now }
+ }
+ if (run) Thread({
+ runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
+ }, "components-restore").start()
+ }
private var pendingGameLink: String? = null
+ private var gameLinkReading = false
+ private var gameLinkTried = false
private var gameSyncFolder by mutableStateOf(null)
private fun pickGameExport(game: Library.SteamGame?) {
onSavePicked = { folder ->
@@ -493,7 +735,6 @@ class FrontEndActivity : ComponentActivity() {
LauncherIcon.set(this, style)
launcherIcon = LauncherIcon.current(this)
if (launcherIcon == before) return false
- // Android finishes activities started through the alias that was just disabled.
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(LauncherIcon.activity(this))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
@@ -510,16 +751,25 @@ class FrontEndActivity : ComponentActivity() {
shortcutLibraryScanning = true
} else shortcutLibraryScanning = false
pendingGameLink = null
+ gameLinkReading = false
+ gameLinkTried = false
if (GameLaunchIntent.accepts(request.action)) {
+ gameLinkReading = true
+ com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
val copy = Intent(request)
Thread({
val id = GameLaunchIntent.read(this, copy)
ui.post {
if (intent === request && !isDestroyed) {
+ gameLinkReading = false
pendingGameLink = id
if (id == null) {
+ syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
- } else refresh()
+ } else {
+ handleGameLink(steamGames, scanned = false)
+ refresh()
+ }
}
}
}, "game-launch-file").start()
@@ -527,7 +777,7 @@ class FrontEndActivity : ComponentActivity() {
}
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
- if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
+ if (pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
}
@@ -544,12 +794,12 @@ class FrontEndActivity : ComponentActivity() {
}
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.putExtra(SessionActivity.EXTRA_STEAMVR, steamVr)
- .putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
+ .returnTo(returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
return true
}
return startSession(Intent(this, SessionActivity::class.java)
- .putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
+ .returnTo(returnHome)
.apply {
if (game.gameIdString == com.droiddeck.launcher.gpu.SteamVr.APP_ID) {
putExtra(SessionActivity.EXTRA_STEAMVR, true)
@@ -560,6 +810,12 @@ class FrontEndActivity : ComponentActivity() {
}, steamSession = true)
}
+ private fun Intent.returnTo(returnHome: Boolean): Intent {
+ val task = taskId
+ return putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
+ .apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
+ }
+
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean): Boolean {
val app = applicationContext
Thread({
@@ -573,16 +829,18 @@ class FrontEndActivity : ComponentActivity() {
}
com.droiddeck.launcher.session.NoSteamLaunch.remember(command)
val next = Intent(this, SessionActivity::class.java)
- .putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
+ .returnTo(returnHome)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, command.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, command.args.toTypedArray())
+ .putExtra(SessionService.EXTRA_GAME_ID, com.droiddeck.launcher.session.NoSteamLaunch.scope(game))
when {
!SessionState.running -> startSessionOrWait(next)
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
+ command.program == com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET && handToBattleNet(command.args, returnHome) { pendingSwitch = next } -> {}
SessionState.mode == SessionService.MODE_RUN && SessionState.program == command.program && SessionState.programArgs == command.args ->
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
- .putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
+ .returnTo(returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
else -> pendingSwitch = next
}
@@ -631,7 +889,7 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, R.string.epic_client_uninstalling, android.widget.Toast.LENGTH_SHORT).show()
return false
}
- if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
+ if (pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
}
@@ -677,7 +935,8 @@ class FrontEndActivity : ComponentActivity() {
}
private fun startSessionOrWait(next: Intent): Boolean {
- val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL))
+ 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
}
@@ -713,15 +972,21 @@ class FrontEndActivity : ComponentActivity() {
ui.postDelayed(poll, SESSION_SWITCH_POLL_MS)
}
- private fun handleGameLink(games: List) {
+ private fun handleGameLink(games: List, scanned: Boolean = true) {
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
val id = pendingGameLink ?: return
+ if (!scanned && games.none { it.gameIdString == id }) return
+ gameLinkTried = true
+ ui.postDelayed({
+ if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
+ }, LINK_PANEL_MS)
val game = games.firstOrNull { it.gameIdString == id }
if (game == null) {
pendingGameLink = null
intent.data = null
intent.action = Intent.ACTION_MAIN
intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
+ syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show()
} else if (launchGame(game, returnHome = true)) {
pendingGameLink = null
@@ -738,10 +1003,12 @@ class FrontEndActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ if (savedInstanceState == null) readIntegrationIntent(intent)
readGameIntent(intent)
gameSyncFolder = GameFileSync.folder(this)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus()
+ if (!SessionState.running) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
theme = SessionPrefs.theme(this)
frameGenLabel = getString(R.string.frame_gen_off)
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
@@ -750,18 +1017,19 @@ class FrontEndActivity : ComponentActivity() {
steamGamesX64 = cachedX64
backActionsInverted = SessionPrefs.backActionsInverted(this)
orientation = SessionPrefs.orientation(this)
- requestedOrientation = orientation
+ launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
+ requestedOrientation = launcherOrientation
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
downloadSource = DownloadSource.mode(this)
downloadMirror = DownloadSource.mirror(this)
downloadPrefix = DownloadSource.custom(this)
+ downloadProxy = DownloadSource.proxyHostPort(this)
DownloadSource.probe()
animationsEnabled = SessionPrefs.animationsEnabled(this)
LauncherIcon.repair(this, intent?.component)
launcherIcon = LauncherIcon.current(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
- storesOpenTab = SessionPrefs.storesOpenTab(this)
storesShowMature = SessionPrefs.storesShowMature(this)
storesSort = SessionPrefs.storesSort(this)
storesView = SessionPrefs.storesView(this)
@@ -773,6 +1041,13 @@ class FrontEndActivity : ComponentActivity() {
if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog(
onConfirm = { decky.confirmPluginZip() }, onCancel = { decky.cancelPluginZip() },
)
+ slowUsb?.let { drive ->
+ com.droiddeck.launcher.ui.SlowUsbDialog(drive, slowUsbNever, { slowUsbNever = it }) {
+ com.droiddeck.launcher.session.UsbLink.markShown(this, drive)
+ showSlowUsb(null)
+ checkUsbLink()
+ }
+ }
val page: (@Composable () -> Unit)? = when {
showPerformance -> { { PerformanceHost() } }
showComponents -> { { ComponentsHost() } }
@@ -790,8 +1065,10 @@ class FrontEndActivity : ComponentActivity() {
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
+ gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
- bluetoothAllowed = bluetoothAllowed, allFilesAllowed = allFilesAllowed,
+ bluetoothAllowed = bluetoothAllowed, allFilesAllowed = allFilesAllowed, localNetworkAllowed = localNetworkAllowed,
+ clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this),
lossless = lossless,
@@ -802,14 +1079,22 @@ class FrontEndActivity : ComponentActivity() {
isHomeApp = homeAppSelected,
homeScreenEnabled = homeScreenEnabled,
defaultHomeLabel = defaultHomeLabel,
+ integration = integrationState,
+ integrationFocus = integrationFocus,
androidApps = androidApps,
secondScreenDisplays = secondScreenDisplays,
+ dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available,
+ dualScreenDevice = dualScreenDevice,
+ dualScreenMode = dualScreenMode,
+ dualScreenLauncher = dualScreenLauncher,
+ dualScreenControls = dualScreenControls,
packages = packageRows,
packageCatalogLoading = catalogLoading,
packageBusyId = pkgId,
packageStage = pkgStage,
packagePercent = pkgPercent,
sessionRunning = SessionState.running,
+ battleNetInstalled = battleNetInstalled,
backActionsInverted = backActionsInverted,
buildLabel = BuildConfig.BUILD_LABEL,
oscMode = oscMode,
@@ -818,15 +1103,16 @@ class FrontEndActivity : ComponentActivity() {
phantomProcessStatus = phantomProcessStatus,
showPhantomGate = showPhantomGate,
orientation = orientation,
+ launcherOrientation = launcherOrientation,
launcherFullscreen = launcherFullscreen,
downloadSource = downloadSource,
downloadMirror = downloadMirror,
downloadPrefix = downloadPrefix,
+ downloadProxy = downloadProxy,
animationsEnabled = animationsEnabled,
launcherIcon = launcherIcon,
gameStoresEnabled = gameStoresEnabled,
gameStoresSpeedTier = gameStoresSpeedTier,
- storesOpenTab = storesOpenTab,
navigate = navRequest,
addedGamesArt = addedGamesArt,
sgdbUserKey = sgdbUserKey,
@@ -898,6 +1184,7 @@ class FrontEndActivity : ComponentActivity() {
.putExtra(SessionService.EXTRA_PROGRAM, app.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, app.args.toTypedArray()))
},
+ onBattleNet = { openBattleNet() },
onFlatpakApp = { id, name ->
Library.flatpakNames[id] = name
startActivity(Intent(this, SessionActivity::class.java)
@@ -941,8 +1228,21 @@ class FrontEndActivity : ComponentActivity() {
.putExtra(com.droiddeck.launcher.files.FileManagerActivity.EXTRA_START_DIR, dir.absolutePath))
},
onLogs = {
- SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
+ val changed = SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
+ if (!changed) android.widget.Toast.makeText(
+ this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
+ ).show()
logsEnabled = SessionPrefs.logsEnabled(this)
+ gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
+ gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
+ },
+ onGameDebugLogs = {
+ val changed = SessionPrefs.setGameDebugLogsEnabled(this, !SessionPrefs.gameDebugLogsEnabled(this))
+ if (!changed) android.widget.Toast.makeText(
+ this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
+ ).show()
+ gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
+ gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onVacDiagnostics = {
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
@@ -953,7 +1253,14 @@ class FrontEndActivity : ComponentActivity() {
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
},
onBluetoothAllowed = { askBluetooth() },
- onAllFilesAllowed = { com.droiddeck.launcher.core.AllFilesAccess.openSettings(this) },
+ onLocalNetworkAllowed = { com.droiddeck.launcher.core.AppPermissions.requestLocalNetwork(this, 4) },
+ onAllFilesAllowed = { com.droiddeck.launcher.files.AllFilesAccess.openSettings(this) },
+ onClearCachedApps = { on -> SessionPrefs.setClearCachedApps(this, on); clearCachedApps = on },
+ onMemoryHud = { value -> SessionPrefs.setMemoryHud(this, value); memoryHud = value },
+ onBackgroundAppLimit = { limit ->
+ SessionPrefs.setBackgroundAppLimit(this, limit); backgroundAppLimit = limit
+ if (limit == com.droiddeck.launcher.core.BackgroundAppLimit.OFF) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
+ },
onShareLogs = {
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
@@ -995,6 +1302,10 @@ class FrontEndActivity : ComponentActivity() {
onOrientation = { value ->
SessionPrefs.setOrientation(this, value)
orientation = value
+ },
+ onLauncherOrientation = { value ->
+ com.droiddeck.launcher.core.AppUiPrefs.setOrientation(this, value)
+ launcherOrientation = value
requestedOrientation = value
},
onLauncherFullscreen = { on ->
@@ -1003,12 +1314,23 @@ class FrontEndActivity : ComponentActivity() {
applyLauncherFullscreen()
},
onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier },
- onStoresOpenTab = { tab -> SessionPrefs.setStoresOpenTab(this, tab); storesOpenTab = tab },
onNavigated = { navRequest = null },
onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show },
onStoresSort = { sort -> SessionPrefs.setStoresSort(this, sort); storesSort = sort },
onStoresView = { view -> SessionPrefs.setStoresView(this, view); storesView = view },
onLibraryChanged = { refreshAddedGames(); refresh() },
+ onDualScreenMode = { mode ->
+ SessionPrefs.setDualScreenMode(this, mode)
+ refreshSecondScreenDisplays()
+ },
+ onDualScreenLauncher = { on ->
+ SessionPrefs.setDualScreenLauncher(this, on)
+ refreshSecondScreenDisplays()
+ },
+ onDualScreenControls = { on ->
+ SessionPrefs.setDualScreenSessionControls(this, on)
+ dualScreenControls = on
+ },
onAnimationsEnabled = { on ->
SessionPrefs.setAnimationsEnabled(this, on)
animationsEnabled = on
@@ -1026,7 +1348,19 @@ class FrontEndActivity : ComponentActivity() {
DownloadSource.setCustom(this, prefix)
downloadPrefix = DownloadSource.custom(this)
},
+ onDownloadProxy = { value ->
+ DownloadSource.setProxy(this, value)
+ downloadProxy = DownloadSource.proxyHostPort(this)
+ },
onHomeApp = { manageHomeApp() },
+ onSteamIntegration = ::openIntegration,
+ onIntegration = { integrationFocus = null; configureIntegration(it) },
+ onIntegrationAppInfo = ::openAppInfo,
+ onIntegrationLocation = ::openWifiDiscoverySettings,
+ onDismissIntegration = {
+ SteamIntegration.dismissSuggestion(this)
+ integrationState = readIntegration()
+ },
onHomeScreen = { on ->
HomeApp.setHomeScreenEnabled(this, on)
refreshHomeAppState()
@@ -1080,7 +1414,15 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
},
onDismissPhantomGate = { showPhantomGate = false },
- onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
+ onShowPhantomGate = {
+ refreshPhantomStatus()
+ showPhantomGate = true
+ },
+ onStartWirelessAdbPairing = {
+ if (com.droiddeck.launcher.core.AppPermissions.localNetwork(this)) WirelessAdbPairingService.start(this)
+ else com.droiddeck.launcher.core.AppPermissions.requestLocalNetwork(this, 5)
+ },
+ onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) },
onOpenNotificationSettings = {
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
@@ -1176,20 +1518,32 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
}
}
+ androidx.activity.compose.BackHandler(compatLaunch != null) { cancelCompatLaunch() }
+ compatLaunch?.loading?.let { loading ->
+ if (!loading.ended) com.droiddeck.launcher.ui.VeilRing()
+ com.droiddeck.launcher.ui.LoadingOverlay(
+ loading.step, loading.percent, loading.elapsed, getString(R.string.load_compat_hint), loading.ended,
+ loading.topic, loading.readable, title = getString(R.string.load_compat_title),
+ onCancel = ::cancelCompatLaunch, onClose = ::cancelCompatLaunch,
+ flood = compatFlood, onFlooded = { compatFlood = null },
+ )
+ }
}
}
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
else {
+ restoreCompatLaunch(savedInstanceState)
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
}
val wanted = ArrayList()
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
- && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
- wanted.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ for (permission in arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
+ if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) wanted.add(permission)
+ }
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !SessionPrefs.bluetoothAsked(this)
&& checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
@@ -1201,14 +1555,9 @@ class FrontEndActivity : ComponentActivity() {
wanted.add(Manifest.permission.RECORD_AUDIO)
SessionPrefs.setMicAsked(this)
}
+ wanted.addAll(com.droiddeck.launcher.core.AppPermissions.startup(this))
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
- else if (!com.droiddeck.launcher.core.AllFilesAccess.granted() && !SessionPrefs.allFilesAsked(this)) {
- Thread({
- if (com.droiddeck.launcher.core.AllFilesAccess.usesSharedStorage(this)) runOnUiThread {
- if (com.droiddeck.launcher.core.AllFilesAccess.ask(this)) SessionPrefs.setAllFilesAsked(this)
- }
- }, "all-files-access").start()
- }
+ else askSharedStorage()
Thread({ com.droiddeck.launcher.stores.StoreAccounts.encryptAll(this) }, "store-credentials").start()
if (!SessionState.running) Thread({
com.droiddeck.launcher.session.LogMigration.run(this)
@@ -1220,9 +1569,33 @@ class FrontEndActivity : ComponentActivity() {
}, "finish-abandoned").start()
}
+ private fun askSharedStorage() {
+ if (!com.droiddeck.launcher.files.AllFilesAccess.granted() && !SessionPrefs.allFilesAsked(this)) {
+ Thread({
+ if (com.droiddeck.launcher.files.AllFilesAccess.usesSharedStorage(this)) runOnUiThread {
+ if (!SessionPrefs.allFilesAsked(this) && com.droiddeck.launcher.files.AllFilesAccess.ask(this)) SessionPrefs.setAllFilesAsked(this)
+ }
+ }, "all-files-access").start()
+ }
+ }
+
+ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
+ super.onRequestPermissionsResult(requestCode, permissions, grantResults)
+ refreshPermissionRows()
+ if (requestCode == 5 && com.droiddeck.launcher.core.AppPermissions.localNetwork(this)) WirelessAdbPairingService.start(this)
+ askSharedStorage()
+ }
+
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
+ if (intent.action == SteamIntegration.ACTION_SETUP) {
+ gameLinkReading = false
+ pendingGameLink = null
+ syncDualPanel()
+ readIntegrationIntent(intent)
+ return
+ }
readGameIntent(intent)
refresh()
startSteamAtStartupIfEnabled()
@@ -1252,9 +1625,28 @@ class FrontEndActivity : ComponentActivity() {
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true)
}
+ @Suppress("OVERRIDE_DEPRECATION")
+ override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
+ val outside = com.droiddeck.launcher.ui.DualScreenPanel.shownOn >= 0 &&
+ com.droiddeck.launcher.ui.DualScreenPanel.opensOutside(packageName, intent.component?.packageName ?: intent.`package` ?: intent.resolveActivity(packageManager)?.packageName)
+ if (outside) {
+ com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
+ window.decorView.postDelayed({ if (hasWindowFocus()) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) }, 1500)
+ }
+ try {
+ super.startActivityForResult(intent, requestCode, options)
+ } catch (e: RuntimeException) {
+ if (outside) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
+ throw e
+ }
+ }
+
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
- if (hasFocus) applyLauncherFullscreen()
+ if (hasFocus) {
+ com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
+ applyLauncherFullscreen()
+ }
}
private fun applyLauncherFullscreen() {
@@ -1280,7 +1672,16 @@ class FrontEndActivity : ComponentActivity() {
}
}
+ @android.annotation.SuppressLint("RestrictedApi")
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
+ if (compatLaunch != null) {
+ if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
+ if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch()
+ return true
+ }
+ if (!compatLaunch!!.loading.ended && event.keyCode !in listOf(
+ KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true
+ }
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
@@ -1298,9 +1699,10 @@ class FrontEndActivity : ComponentActivity() {
}
private fun refreshPermissionRows() {
+ localNetworkAllowed = if (Build.VERSION.SDK_INT >= 37) com.droiddeck.launcher.core.AppPermissions.localNetwork(this) else null
bluetoothAllowed = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED else null
- allFilesAllowed = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) com.droiddeck.launcher.core.AllFilesAccess.granted() else null
+ allFilesAllowed = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) com.droiddeck.launcher.files.AllFilesAccess.granted() else null
}
private fun askBluetooth() {
@@ -1317,14 +1719,32 @@ class FrontEndActivity : ComponentActivity() {
}
}
+ override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
+ if (compatLaunch != null && !compatLaunch!!.loading.ended &&
+ com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true
+ return super.dispatchGenericMotionEvent(event)
+ }
+
+ override fun onPause() {
+ compatLaunchVisible = false
+ if (android.os.Build.VERSION.SDK_INT >= 29) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, true)
+ super.onPause()
+ }
+
override fun onResume() {
super.onResume()
+ compatLaunchVisible = true
+ com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
+ com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false)
orientation = SessionPrefs.orientation(this)
- requestedOrientation = orientation
+ launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
+ requestedOrientation = launcherOrientation
+ SteamIntegration.syncShortcutsListing(this)
refreshWifiDiscovery()
refreshPermissionRows()
com.droiddeck.launcher.stores.StoresState.refresh(this)
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
+ com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) }
com.droiddeck.launcher.ui.Motion.refresh(this)
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
@@ -1335,14 +1755,21 @@ class FrontEndActivity : ComponentActivity() {
drivers.checkOnOpen()
resumeInterruptedPackages()
protons.checkUpdates()
- if (!SessionState.running) Thread({
- val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
- if (applied.isNotEmpty()) ui.post {
- android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
- }
- ui.post { if (showComponents) components.refreshComponents() }
- }, "components-queue").start()
- else if (showComponents) components.refreshComponents()
+ catalogFresh = false
+ if (!SessionState.running && !componentsQueueBusy && !LinuxRuntimeInstaller.isBusy()) {
+ componentsQueueBusy = true
+ Thread({
+ val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
+ if (applied.isNotEmpty()) ui.post {
+ android.widget.Toast.makeText(this, getString(R.string.main_applied, applied.joinToString(", ")), android.widget.Toast.LENGTH_LONG).show()
+ }
+ ui.post {
+ componentsQueueBusy = false
+ if (showComponents) components.refreshComponents()
+ autoUpdateRuntime()
+ }
+ }, "components-queue").start()
+ } else if (showComponents) components.refreshComponents()
oscMode = SessionPrefs.oscMode(this)
refreshController()
refreshHomeAppState()
@@ -1365,11 +1792,24 @@ class FrontEndActivity : ComponentActivity() {
addDataScheme("file")
})
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
+ getSystemService(android.hardware.input.InputManager::class.java)?.registerInputDeviceListener(secondScreenTouchListener, ui)
+ launcherStarted = true
refreshSecondScreenDisplays()
+ getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
+ HomeWidgets.startListening(this)
+ }
+
+ @Suppress("OVERRIDE_DEPRECATION")
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) return
+ @Suppress("DEPRECATION")
+ super.onActivityResult(requestCode, resultCode, data)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
+ if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
+ saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
switchingTo?.let {
outState.putParcelable(KEY_SWITCHING_TO, it)
@@ -1382,6 +1822,7 @@ class FrontEndActivity : ComponentActivity() {
else @Suppress("DEPRECATION") state.getParcelable(key)
override fun onDestroy() {
+ cancelCompatLaunch()
updates.unregister()
super.onDestroy()
}
@@ -1389,9 +1830,15 @@ class FrontEndActivity : ComponentActivity() {
override fun onStop() {
unregisterReceiver(wifiLocationReceiver)
unregisterReceiver(mediaReceiver)
+ getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
+ HomeWidgets.stopListening(this)
ui.removeCallbacks(mediaRefresh)
com.droiddeck.launcher.stores.StoresState.libraryListener = null
+ com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
+ getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener)
+ launcherStarted = false
+ com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
flood = null
returning = null
floodProgress = 0f
@@ -1403,20 +1850,52 @@ class FrontEndActivity : ComponentActivity() {
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
defaultHomeLabel = HomeApp.defaultLabel(this)
- androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList()
+ refreshAndroidApps()
+ integrationState = readIntegration()
+ }
+
+ private fun refreshAndroidApps() {
+ if (!homeAppSelected) {
+ ++androidAppsListing
+ androidApps = emptyList()
+ return
+ }
+ val seq = ++androidAppsListing
+ HomePins.refresh(this)
+ Thread({
+ val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList())
+ ui.post { if (seq == androidAppsListing) androidApps = apps }
+ }, "home-apps").start()
}
private fun refreshSecondScreenDisplays() {
if (!::displayManager.isInitialized) return
- // The launcher can itself be shown on a non-default display (DeX, an external monitor); that one is not a "second screen".
val ownDisplayId = if (android.os.Build.VERSION.SDK_INT >= 30) display?.displayId ?: android.view.Display.DEFAULT_DISPLAY else @Suppress("DEPRECATION") windowManager.defaultDisplay.displayId
+ dualScreenMode = SessionPrefs.dualScreenMode(this)
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId)
+ dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null
+ dualScreenLauncher = SessionPrefs.dualScreenLauncher(this)
+ dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
+ val target = com.droiddeck.launcher.input.DualScreen.display(this, displayManager, ownDisplayId)
+ dualDisplayId = if (dualScreenLauncher) target?.displayId ?: -1 else -1
+ syncDualPanel()
}
+ private fun syncDualPanel() {
+ if (launchPending()) return
+ if (launcherStarted && dualDisplayId >= 0) com.droiddeck.launcher.ui.DualScreenPanel.show(this, dualDisplayId, taskId)
+ else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
+ }
+
+ private fun launchPending(): Boolean = gameLinkReading || (pendingGameLink != null && !gameLinkTried)
+
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
+ val onOwnScreen = displayId == null || displayId == ((if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.displayId ?: Display.DEFAULT_DISPLAY)
+ if (onOwnScreen) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
try {
HomeApp.launch(this, app, displayId)
} catch (_: Exception) {
+ com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
val message = when {
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
@@ -1548,6 +2027,7 @@ class FrontEndActivity : ComponentActivity() {
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
onMode = { m -> drivers.chooseMode(m) },
onRestart = { drivers.restartApp() },
+ onTpUbwcMode = { drivers.chooseTpUbwcMode(it) },
),
protons = com.droiddeck.launcher.ui.ProtonsState(
rows = protons.protonRows, busyId = protons.protonBusyId, stage = protons.protonStage, percent = protons.protonPercent,
@@ -1583,6 +2063,50 @@ class FrontEndActivity : ComponentActivity() {
desktopPresent = DesktopCatalog.desktopPresent(this)
}
+ private fun openBattleNet(args: List = emptyList()) {
+ if (pkgStage != null) {
+ android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
+ return
+ }
+ val app = applicationContext
+ Thread({
+ val full = if (args.firstOrNull() == "--library") args else com.droiddeck.launcher.stores.battlenet.BattleNetClient.library(app) + args
+ ui.post {
+ if (isDestroyed) return@post
+ val next = Intent(this, SessionActivity::class.java)
+ .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
+ .putExtra(SessionService.EXTRA_PROGRAM, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET)
+ .putExtra(SessionService.EXTRA_PROGRAM_ARGS, full.toTypedArray())
+ when {
+ !SessionState.running -> startSessionOrWait(next)
+ SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
+ handToBattleNet(full) { pendingSwitch = next } -> {}
+ else -> pendingSwitch = next
+ }
+ }
+ }, "battlenet-open").start()
+ }
+
+ private fun handToBattleNet(args: List, returnHome: Boolean = false, otherwise: () -> Unit): Boolean {
+ if (SessionState.mode != SessionService.MODE_RUN || SessionState.program != com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET) return false
+ val library = args.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1)
+ val sessionLibrary = SessionState.programArgs.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1)
+ if (library != null && sessionLibrary != null && library != sessionLibrary) return false
+ val request = if (library != null) args.drop(2) else args
+ val app = applicationContext
+ Thread({
+ val handed = request.isEmpty() || com.droiddeck.launcher.stores.battlenet.BattleNetClient.request(LinuxRuntime.sessionRoot(app), request)
+ ui.post {
+ if (isDestroyed) return@post
+ if (!handed) otherwise()
+ else startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
+ .returnTo(returnHome)
+ .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
+ }
+ }, "battlenet-request").start()
+ return true
+ }
+
private fun launchProgram(path: String) {
startActivity(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
@@ -1648,7 +2172,7 @@ class FrontEndActivity : ComponentActivity() {
ModeSettings(
mode = mode, resolution = resolution,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
- hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit,
+ hdr = hdrOn, hdrReason = hdrReason,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
touchMode = touchMode,
@@ -1656,10 +2180,10 @@ class FrontEndActivity : ComponentActivity() {
steamDownloadsInBackground = steamDownloadsInBackground,
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
pipAutoEnter = pipAutoEnter,
- unfoldedControls = if (mode == SessionService.MODE_STEAM &&
- com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null,
+ unfoldedControls = if (mode == SessionService.MODE_STEAM) unfoldedControls else null,
unfoldedControlsWithController = unfoldedControlsWithController,
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
+ backHold = backHold,
backActionsInverted = backActionsInverted,
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null,
@@ -1667,12 +2191,14 @@ class FrontEndActivity : ComponentActivity() {
mic = if (mode == SessionService.MODE_STEAM) mic else null,
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
storageOptions = storageOptions,
+ steamLibraries = steamLibraries,
storageDiagnostics = mode == SessionService.MODE_STEAM && storageDiagnostics,
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
forceSsbs = forceSsbs,
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
steamClientArch = if (mode == SessionService.MODE_STEAM) steamClientArch else null,
returnAfterGame = if (mode == SessionService.MODE_STEAM) returnAfterGame else null,
+ shaderPrecache = if (mode == SessionService.MODE_STEAM) shaderPrecache else null,
steamRepairQueued = steamRepairQueued,
mangoapp = mangoapp,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
@@ -1682,11 +2208,7 @@ class FrontEndActivity : ComponentActivity() {
bootMovieCustomName = bootMovieCustomName,
bootMovieImporting = bootMovieImporting,
bootMovieProgress = bootMovieProgress,
- wifiDiscovery = if (mode == SessionService.MODE_STEAM) wifiDiscovery else null,
- wifiDiscoveryPermission = wifiDiscoveryPermission,
- wifiDiscoveryLocation = wifiDiscoveryLocation,
- wifiDiscoveryAsked = wifiDiscoveryAsked,
- wifiDiscoveryBlocked = wifiDiscoveryBlocked,
+ integration = if (mode == SessionService.MODE_STEAM) integrationState else null,
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyLatest else null,
deckyBranch = decky.deckyBranch,
@@ -1695,25 +2217,12 @@ class FrontEndActivity : ComponentActivity() {
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
),
ModeSettingsActions(
- onWifiDiscovery = { on ->
- if (!on) {
- SessionPrefs.setWifiDiscoveryEnabled(this, false)
- refreshWifiDiscovery()
- } else if (WifiDiscovery.permissionGranted(this)) {
- SessionPrefs.setWifiDiscoveryEnabled(this, true)
- refreshWifiDiscovery()
- } else if (wifiDiscoveryBlocked) {
- openWifiDiscoverySettings()
- } else {
- SessionPrefs.setWifiDiscoveryAsked(this)
- wifiLocationPermission.launch(WifiDiscovery.permissions)
- }
- },
- onWifiDiscoverySettings = { openWifiDiscoverySettings() },
+ onIntegration = ::configureIntegration,
+ onIntegrationAppInfo = ::openAppInfo,
+ onIntegrationLocation = ::openWifiDiscoverySettings,
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value },
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
- onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
@@ -1728,6 +2237,7 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.setUnfoldedControlsWithController(this, on); unfoldedControlsWithController = on
},
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
+ onBackHold = { on -> SessionPrefs.setBackHold(this, on); backHold = on },
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this, inverted)
backActionsInverted = inverted
@@ -1746,6 +2256,19 @@ class FrontEndActivity : ComponentActivity() {
onPickGameStorageFolder = {
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_game_storage), gameStorage.ifEmpty { null }))
},
+ onAddSteamLibrary = {
+ pickSteamLibrary.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.libraries_pick), null))
+ },
+ onRenameSteamLibrary = { id, label ->
+ SteamLibraries.rename(this, id, label)
+ steamLibraries = SteamLibraries.list(this)
+ refresh()
+ },
+ onRemoveSteamLibrary = { id ->
+ SteamLibraries.remove(this, id)
+ steamLibraries = SteamLibraries.list(this)
+ refresh()
+ },
onStorageDiagnostics = { on ->
SessionPrefs.setStorageDiagnosticsEnabled(this, on)
storageDiagnostics = on
@@ -1759,9 +2282,15 @@ class FrontEndActivity : ComponentActivity() {
syncFallback = SessionPrefs.syncFallback(this)
},
onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) },
- onSteamClientArch = { id -> SessionPrefs.setSteamClientArch(this, id); steamClientArch = id; refresh() },
+ onSteamClientArch = { id ->
+ SessionPrefs.setSteamClientArch(this, id)
+ steamClientArch = id
+ loadShaderPrecache(mode)
+ refresh()
+ },
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = on },
+ onShaderPrecache = { on -> SessionPrefs.setShaderPrecache(this, on); shaderPrecache = on },
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
onRunSteamAtStartup = { on ->
SessionPrefs.setRunSteamAtStartup(this, on)
@@ -1802,7 +2331,12 @@ class FrontEndActivity : ComponentActivity() {
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
- prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, guestHostname = guestHostname, phantomWarning = phantomWarning,
+ ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient,
+ deviceRamMb = (android.app.ActivityManager.MemoryInfo()
+ .also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
+ ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
+ prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, cursorComposite = cursorComposite,
+ guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
@@ -1814,8 +2348,12 @@ class FrontEndActivity : ComponentActivity() {
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
+ onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
+ onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
+ onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
+ onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
onClientCore = { core, on ->
clientCores = if (on) clientCores + core else clientCores - core
@@ -1888,6 +2426,7 @@ class FrontEndActivity : ComponentActivity() {
}
private fun refreshAddedGames() {
+ checkUsbLink()
sgdbKeyKnown()
fetchAddedGameArt()
}
@@ -1916,6 +2455,19 @@ class FrontEndActivity : ComponentActivity() {
private var pipAutoEnter by mutableStateOf(false)
private var unfoldedControls by mutableStateOf(false)
private var unfoldedControlsWithController by mutableStateOf(false)
+ private var shaderPrecacheGeneration = 0
+
+ private fun loadShaderPrecache(mode: String) {
+ val generation = ++shaderPrecacheGeneration
+ shaderPrecache = null
+ if (mode != SessionService.MODE_STEAM) return
+ Thread({
+ val precache = SessionPrefs.shaderPrecache(this)
+ ui.post {
+ if (!isDestroyed && generation == shaderPrecacheGeneration) shaderPrecache = precache
+ }
+ }, "shader-precache").start()
+ }
private fun loadModeSettings(mode: String) {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
@@ -1931,11 +2483,11 @@ class FrontEndActivity : ComponentActivity() {
steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this)
returnAfterGame = SessionPrefs.returnAfterGame(this)
+ loadShaderPrecache(mode)
steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
loadBootMovie()
hdrOn = SessionPrefs.hdr(this, mode)
- fpsLimit = SessionPrefs.fpsLimit(this, mode)
upscaler = SessionPrefs.upscaler(this)
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
@@ -1943,6 +2495,7 @@ class FrontEndActivity : ComponentActivity() {
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
oscMode = SessionPrefs.oscMode(this)
+ backHold = SessionPrefs.backHold(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
directAudio = SessionPrefs.directAudio(this)
picturePosition = SessionPrefs.picturePosition(this)
@@ -1950,6 +2503,7 @@ class FrontEndActivity : ComponentActivity() {
mic = SessionPrefs.micEnabled(this)
refreshWifiDiscovery()
gameStorage = SessionPrefs.gameStorage(this)
+ steamLibraries = SteamLibraries.list(this)
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
settingsMode = mode
Thread({
@@ -1979,6 +2533,20 @@ class FrontEndActivity : ComponentActivity() {
}
SessionPrefs.setGameStorage(this, path, label)
gameStorage = path
+ checkUsbLink()
+ }
+
+ private fun checkUsbLink() {
+ if (android.os.Looper.myLooper() != android.os.Looper.getMainLooper()) { ui.post { checkUsbLink() }; return }
+ val scan = ++usbScan
+ Thread({
+ val drive = runCatching { com.droiddeck.launcher.session.UsbLink.slowLibrary(this) }.getOrNull()
+ ui.post {
+ if (scan != usbScan || isFinishing) return@post
+ val due = drive?.takeIf { com.droiddeck.launcher.session.UsbLink.stillDue(this, it) }
+ if (due == null) { if (slowUsb != null) showSlowUsb(null) } else if (slowUsb?.key != due.key) showSlowUsb(due)
+ }
+ }, "usb-link").start()
}
private fun refreshCores() {
@@ -1994,15 +2562,22 @@ class FrontEndActivity : ComponentActivity() {
syncFallback = SessionPrefs.syncFallback(this)
fsyncFirst = SessionPrefs.fsyncFirst(this)
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
+ ramCapMb = SessionPrefs.ramCapMb(this)
+ zramClient = SessionPrefs.zramClient(this)
+ vramCapMb = SessionPrefs.vramCapMb(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
+ cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
refreshPhantomStatus()
}
+ private fun gameDebugLogsNeedsRestart(): Boolean =
+ SessionPrefs.logsEnabled(this) && SessionPrefs.gameDebugLogsEnabled(this) &&
+ !SessionPaths.currentSessionLogsRetained(this)
+
private fun refresh() {
- // Until the scan finishes, the other client's games would launch in this one.
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
if (listX64 != steamGamesX64) {
steamGamesX64 = listX64
@@ -2013,16 +2588,24 @@ class FrontEndActivity : ComponentActivity() {
addedGamesArt = SessionPrefs.addedGamesArt(this)
desktopInstalled = DesktopCatalog.desktopInstalled(this)
desktopPresent = DesktopCatalog.desktopPresent(this)
+ battleNetInstalled = com.droiddeck.launcher.runtime.BattleNet.installed(this)
offlineAccount = OfflineMode.account(this)
offline = OfflineMode.enabled(this)
installed = LinuxRuntimeInstaller.installedVersion(this)
ready = LinuxRuntime.isInstalled(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
+ ui.post { autoUpdateRuntime() }
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
+ gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
+ gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
+ clearCachedApps = SessionPrefs.clearCachedApps(this)
+ adbPaired = WirelessAdbFix.hasSavedPairing(this)
+ memoryHud = SessionPrefs.memoryHud(this)
+ backgroundAppLimit = SessionPrefs.backgroundAppLimit(this)
runningLabel = if (SessionState.running) when (SessionState.mode) {
SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop)
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
@@ -2032,7 +2615,7 @@ class FrontEndActivity : ComponentActivity() {
val scanGeneration = ++libraryScanGeneration
val artRefreshesAtStart = HashMap(steamArtRefreshes)
if (shortcutPicker) shortcutLibraryScanning = true
- if (SessionPrefs.steamClientArch(this) == "x86_64" && !OfflineMode.enabled(this)) {
+ if (!OfflineMode.enabled(this)) {
Thread({ com.droiddeck.launcher.session.FexCatalog.refresh(this) }, "fex-catalog").start()
}
Thread({
@@ -2054,15 +2637,32 @@ class FrontEndActivity : ComponentActivity() {
}
val scannedArch = SessionPrefs.activeSteamClientArch(this)
val scannedX64 = scannedArch == "x86_64"
- val games = if (ready) Library.launchableGames(this, arch = scannedArch) else emptyList()
+ val games = if (ready || com.droiddeck.launcher.runtime.LinuxRuntime.hasRootfs(this)) Library.launchableGames(this, arch = scannedArch) else emptyList()
val all = games.distinctBy { it.gameId }
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64)
val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession }
- if (ready && (!componentSweepDone || endedSession != null)) {
+ val sweepDue = ready && (!componentSweepDone || endedSession != null)
+ if (sweepDue) {
componentSweepDone = true
endedSession?.let { componentSweepSession = it }
- ui.postDelayed({ Thread({ com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all) }, "components-sweep").start() }, 10_000)
}
+ val restoreDue = synchronized(componentRestoreLock) {
+ val now = android.os.SystemClock.elapsedRealtime()
+ val due = ready && (lastComponentRestore == 0L || now - lastComponentRestore >= COMPONENT_RESTORE_MS)
+ if (due) {
+ lastComponentRestore = now
+ } else if (ready && !componentRestoreRetry) {
+ componentRestoreRetry = true
+ ui.postDelayed({ retryComponentRestore() }, (COMPONENT_RESTORE_MS - (now - lastComponentRestore)).coerceAtLeast(0L))
+ }
+ due
+ }
+ if (restoreDue || sweepDue) ui.postDelayed({
+ Thread({
+ if (restoreDue) runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
+ if (sweepDue) com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all)
+ }, "components-restore").start()
+ }, 10_000)
ui.post {
if (scanGeneration == libraryScanGeneration) {
val current = steamGames.filter { it.library != Library.ADDED }.associateBy { it.appId }
@@ -2103,6 +2703,10 @@ class FrontEndActivity : ComponentActivity() {
private fun startSession(intent: Intent, steamSession: 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()
+ return false
+ }
if (com.droiddeck.launcher.storage.StorageState.cleaning) {
android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show()
return false
@@ -2120,6 +2724,7 @@ class FrontEndActivity : ComponentActivity() {
private fun refreshPhantomStatus() {
phantomProcessStatus = PhantomProcessLimit.read(this)
+ adbPaired = WirelessAdbFix.hasSavedPairing(this)
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
getString(
R.string.phantom_warning, PhantomProcessLimit.title(this, phantomProcessStatus),
@@ -2151,7 +2756,7 @@ class FrontEndActivity : ComponentActivity() {
private fun runtimeChangesBlocked(): Boolean =
busy || LinuxRuntimeInstaller.isBusy() || SessionState.running ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
- protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null ||
+ protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null || componentsQueueBusy ||
components.compBusy != null || saveBusy != null || com.droiddeck.launcher.store.UserAppsState.working != null
private fun removeDesktop() {
@@ -2211,18 +2816,38 @@ class FrontEndActivity : ComponentActivity() {
}, "runtime-operation").start()
}
+ private fun autoUpdateRuntime() {
+ val release = available?.takeIf { catalogFresh } ?: return
+ if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED) || runtimeChangesBlocked() || removalPending) return
+ if (release.version == installed || installed == null) return
+ if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
+ Log.i(TAG, "runtime: updating $installed to ${release.version} by itself")
+ install(release)
+ }
+ }
+
private fun checkCatalog() {
val release = LinuxRuntimeInstaller.fetchRelease()
Log.i(TAG, "catalog: " + (release?.version ?: "unreachable"))
- ui.post { if (release != null) available = release }
+ ui.post {
+ if (release == null) return@post
+ available = release
+ catalogFresh = true
+ autoUpdateRuntime()
+ }
}
companion object {
private const val TAG = "MainActivity"
private const val MEDIA_SETTLE_MS = 1500L
+ private const val COMPONENT_RESTORE_MS = 60_000L
+ private const val LINK_PANEL_MS = 1500L
private const val SESSION_SWITCH_WAIT_MS = 30_000L
private const val SESSION_SWITCH_POLL_MS = 250L
private const val KEY_PENDING_SWITCH = "pending_switch"
+ private const val KEY_COMPAT_LAUNCH = "compat_launch"
+ private const val KEY_COMPAT_MENU_INSTALL = "compat_menu_install"
+ private const val KEY_COMPAT_PROBLEM = "compat_problem"
private const val KEY_SWITCHING_TO = "switching_to"
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
diff --git a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt
index 71304e883..59e10c48e 100644
--- a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt
@@ -13,7 +13,7 @@ class HomeActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
+ requestedOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
routeHome()
}
diff --git a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt
index 74b49821c..4d5b87aa7 100644
--- a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt
+++ b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt
@@ -6,20 +6,41 @@ import android.graphics.Bitmap
import android.content.ComponentName
import android.content.Context
import android.content.Intent
+import android.content.pm.ApplicationInfo
+import android.content.pm.LauncherApps
+import android.content.pm.ShortcutInfo
+import android.graphics.Rect
+import android.os.Process
+import android.os.UserHandle
+import android.os.UserManager
import android.content.pm.PackageManager
+import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.graphics.drawable.toBitmap
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
+import kotlin.math.roundToInt
object HomeApp {
+ private const val ICON_DP = 72
+
data class LaunchableApp(
val label: String,
val packageName: String,
val className: String,
val icon: Bitmap?,
- )
+ val system: Boolean = false,
+ val game: Boolean = false,
+ val installedAt: Long = 0L,
+ val updatedAt: Long = 0L,
+ val user: UserHandle? = null,
+ val userSerial: Long = 0L,
+ ) {
+ val component get() = ComponentName(packageName, className)
+ val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
+ val work get() = userSerial != 0L
+ }
fun isHomeScreenEnabled(context: Context): Boolean =
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
@@ -69,33 +90,134 @@ object HomeApp {
fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS)
fun launchableApps(context: Context): List {
+ val launcher = context.getSystemService(LauncherApps::class.java)
+ val users = context.getSystemService(UserManager::class.java)
val pm = context.packageManager
- val launch = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
- val apps = pm.queryIntentActivities(launch, 0)
- .asSequence()
- .mapNotNull { result ->
- val activity = result.activityInfo ?: return@mapNotNull null
- if (!activity.exported || activity.packageName == context.packageName) return@mapNotNull null
- val label = result.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { activity.packageName }
- val icon = runCatching { result.loadIcon(pm).toBitmap(48, 48) }.getOrNull()
- LaunchableApp(label, activity.packageName, activity.name, icon)
+ val own = Process.myUserHandle()
+ val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt()
+ val apps = users.userProfiles.flatMap { user ->
+ val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
+ runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info ->
+ val component = info.componentName
+ if (component.packageName == context.packageName && user == own) return@mapNotNull null
+ val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName }
+ val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
+ val app = info.applicationInfo
+ val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null
+ @Suppress("DEPRECATION")
+ val game = app.category == ApplicationInfo.CATEGORY_GAME || app.flags and ApplicationInfo.FLAG_IS_GAME != 0
+ LaunchableApp(
+ label, component.packageName, component.className, icon,
+ system = app.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0,
+ game = game,
+ installedAt = info.firstInstallTime,
+ updatedAt = updated ?: info.firstInstallTime,
+ user = user,
+ userSerial = serial,
+ )
}
- .distinctBy { it.packageName }
- .toList()
- return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
+ }
+ return apps.distinctBy { it.key }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
}
- fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) {
- val intent = Intent(Intent.ACTION_MAIN)
- .addCategory(Intent.CATEGORY_LAUNCHER)
- .setComponent(ComponentName(app.packageName, app.className))
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- if (displayId == null) {
- context.startActivity(intent)
- return
+ fun launch(context: Context, app: LaunchableApp, displayId: Int? = null, bounds: Rect? = null) {
+ val options = displayId?.let { ActivityOptions.makeBasic().setLaunchDisplayId(it).toBundle() }
+ val launcher = context.getSystemService(LauncherApps::class.java)
+ launcher.startMainActivity(app.component, app.user ?: Process.myUserHandle(), bounds, options)
+ }
+
+ fun canUseShortcuts(context: Context): Boolean =
+ runCatching { context.getSystemService(LauncherApps::class.java).hasShortcutHostPermission() }.getOrDefault(false)
+
+ fun shortcuts(context: Context, app: LaunchableApp): List {
+ if (!canUseShortcuts(context)) return emptyList()
+ val query = LauncherApps.ShortcutQuery()
+ .setPackage(app.packageName)
+ .setActivity(app.component)
+ .setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC or LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST)
+ return runCatching { context.getSystemService(LauncherApps::class.java).getShortcuts(query, app.user ?: Process.myUserHandle()) }
+ .getOrNull().orEmpty()
+ .filter { it.isEnabled }
+ .sortedWith(compareBy { if (it.isDeclaredInManifest) 0 else 1 }.thenBy { it.rank })
+ .take(5)
+ }
+
+ fun shortcutIcon(context: Context, info: ShortcutInfo, px: Int = (ICON_DP * context.resources.displayMetrics.density).roundToInt()): Bitmap? = runCatching {
+ context.getSystemService(LauncherApps::class.java)
+ .getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
+ }.getOrNull()
+
+ fun trackRecents(app: android.app.Application) {
+ app.registerActivityLifecycleCallbacks(object : android.app.Application.ActivityLifecycleCallbacks {
+ override fun onActivityCreated(activity: android.app.Activity, savedInstanceState: android.os.Bundle?) = Unit
+ override fun onActivityStarted(activity: android.app.Activity) = Unit
+ override fun onActivityResumed(activity: android.app.Activity) = syncRecents(activity)
+ override fun onActivityPaused(activity: android.app.Activity) { if (activity is FrontEndActivity) syncRecents(activity) }
+ override fun onActivityStopped(activity: android.app.Activity) = Unit
+ override fun onActivitySaveInstanceState(activity: android.app.Activity, outState: android.os.Bundle) = Unit
+ override fun onActivityDestroyed(activity: android.app.Activity) = Unit
+ })
+ }
+
+ private fun syncRecents(activity: android.app.Activity) =
+ keepOutOfRecents(activity, activity is FrontEndActivity && !SessionState.running && isDefault(activity))
+
+ internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
+
+ internal fun recentsStep(hidden: Boolean, owned: Boolean, excluded: Boolean): RecentsStep = when {
+ hidden && !excluded -> RecentsStep.HIDE
+ !hidden && owned && excluded -> RecentsStep.SHOW
+ !hidden && owned -> RecentsStep.FORGET
+ else -> RecentsStep.NONE
+ }
+
+ fun keepOutOfRecents(activity: android.app.Activity, hidden: Boolean) {
+ val prefs = activity.getSharedPreferences("home-recents", Context.MODE_PRIVATE)
+ val owned = prefs.getStringSet("tasks", null).orEmpty()
+ val id = activity.taskId.toString()
+ if (!hidden && id !in owned) return
+ runCatching {
+ @Suppress("DEPRECATION")
+ fun idOf(task: android.app.ActivityManager.AppTask) =
+ task.taskInfo?.let { if (Build.VERSION.SDK_INT >= 29) it.taskId else it.persistentId } ?: -1
+ val tasks = activity.getSystemService(android.app.ActivityManager::class.java).appTasks
+ val task = tasks.firstOrNull { idOf(it) == activity.taskId } ?: return
+ val baseIntent = task.taskInfo?.baseIntent ?: return@runCatching
+ val excluded = baseIntent.flags and Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS != 0
+ val step = recentsStep(hidden, id in owned, excluded)
+ if (step == RecentsStep.NONE) return
+ if (step != RecentsStep.FORGET) task.setExcludeFromRecents(step == RecentsStep.HIDE)
+ val live = tasks.map { idOf(it).toString() }.toSet()
+ val next = owned.filter { it in live && it != id }.toMutableSet()
+ if (step == RecentsStep.HIDE) next += id
+ prefs.edit().putStringSet("tasks", next).apply()
}
- val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
- context.startActivity(intent, options.toBundle())
+ }
+
+ fun startShortcut(context: Context, info: ShortcutInfo) {
+ val task = generateSequence(context) { (it as? android.content.ContextWrapper)?.baseContext }
+ .filterIsInstance().firstOrNull()?.taskId
+ task?.let { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(it, true) }
+ try {
+ context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
+ } catch (e: Exception) {
+ task?.let { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(it, false) }
+ throw e
+ }
+ }
+
+ fun openAppInfo(context: Context, app: LaunchableApp) {
+ context.getSystemService(LauncherApps::class.java)
+ .startAppDetailsActivity(app.component, app.user ?: Process.myUserHandle(), null, null)
+ }
+
+ fun canUninstall(app: LaunchableApp): Boolean = !app.system && !app.work
+
+ fun uninstall(context: Context, app: LaunchableApp) {
+ context.startActivity(
+ Intent(Intent.ACTION_DELETE, Uri.fromParts("package", app.packageName, null))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ )
}
fun isActiveSteamSession(): Boolean =
diff --git a/app/src/main/java/com/droiddeck/launcher/HomeFolders.kt b/app/src/main/java/com/droiddeck/launcher/HomeFolders.kt
new file mode 100644
index 000000000..dc1f0bca4
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/HomeFolders.kt
@@ -0,0 +1,65 @@
+package com.droiddeck.launcher
+
+import android.content.Context
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import org.json.JSONArray
+import org.json.JSONObject
+import java.util.UUID
+
+object HomeFolders {
+ data class Folder(val id: String, val name: String, val apps: List)
+
+ private const val PREFS = "home_launcher"
+ private const val KEY = "folders"
+
+ var folders by mutableStateOf>(emptyList())
+ private set
+ private var loaded = false
+
+ fun load(context: Context) {
+ if (loaded) return
+ loaded = true
+ val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
+ folders = runCatching {
+ val array = JSONArray(raw)
+ (0 until array.length()).map { i ->
+ val o = array.getJSONObject(i)
+ val apps = o.getJSONArray("apps")
+ Folder(o.getString("id"), o.getString("name"), (0 until apps.length()).map { apps.getString(it) })
+ }
+ }.getOrDefault(emptyList())
+ }
+
+ fun create(context: Context, name: String, appKey: String): Folder {
+ val folder = Folder(UUID.randomUUID().toString(), name, listOf(appKey))
+ update(context, without(appKey) + folder)
+ return folder
+ }
+
+ fun add(context: Context, folderId: String, appKey: String) =
+ update(context, without(appKey).map { if (it.id == folderId) it.copy(apps = it.apps + appKey) else it })
+
+ fun remove(context: Context, appKey: String) = update(context, without(appKey))
+
+ fun rename(context: Context, folderId: String, name: String) =
+ update(context, folders.map { if (it.id == folderId) it.copy(name = name) else it })
+
+ fun delete(context: Context, folderId: String) = update(context, folders.filterNot { it.id == folderId })
+
+ fun migrateMembers(context: Context, keyFor: (String) -> String?) {
+ if (folders.none { f -> f.apps.any { '/' !in it } }) return
+ update(context, folders.map { f -> f.copy(apps = f.apps.map { if ('/' in it) it else keyFor(it) ?: it }.distinct()) })
+ }
+
+ private fun without(appKey: String): List =
+ folders.map { it.copy(apps = it.apps - appKey) }.filter { it.apps.isNotEmpty() }
+
+ private fun update(context: Context, next: List) {
+ folders = next
+ val array = JSONArray()
+ for (f in next) array.put(JSONObject().put("id", f.id).put("name", f.name).put("apps", JSONArray(f.apps)))
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/HomeHidden.kt b/app/src/main/java/com/droiddeck/launcher/HomeHidden.kt
new file mode 100644
index 000000000..70f98f484
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/HomeHidden.kt
@@ -0,0 +1,26 @@
+package com.droiddeck.launcher
+
+import android.content.Context
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+
+object HomeHidden {
+ private const val PREFS = "home_launcher"
+ private const val KEY = "hidden"
+
+ var keys by mutableStateOf>(emptySet())
+ private set
+ private var loaded = false
+
+ fun load(context: Context) {
+ if (loaded) return
+ loaded = true
+ keys = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY, emptySet()).orEmpty().toSet()
+ }
+
+ fun set(context: Context, key: String, hidden: Boolean) {
+ keys = if (hidden) keys + key else keys - key
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY, keys).apply()
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/HomePins.kt b/app/src/main/java/com/droiddeck/launcher/HomePins.kt
new file mode 100644
index 000000000..38acb1813
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/HomePins.kt
@@ -0,0 +1,74 @@
+package com.droiddeck.launcher
+
+import android.content.Context
+import android.content.pm.LauncherApps
+import android.content.pm.ShortcutInfo
+import android.graphics.Bitmap
+import android.os.Handler
+import android.os.Looper
+import android.os.Process
+import android.os.UserManager
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+
+object HomePins {
+ class Pinned(val info: ShortcutInfo, val icon: Bitmap?, val appLabel: String, val userSerial: Long) {
+ val key get() = "pin:${info.`package`}/${info.id}" + if (userSerial != 0L) "#$userSerial" else ""
+ val label get() = info.shortLabel?.toString()?.trim().orEmpty().ifEmpty { appLabel }
+ val work get() = userSerial != 0L
+ }
+
+ var pinned by mutableStateOf>(emptyList())
+ private set
+ private val main = Handler(Looper.getMainLooper())
+ private var listing = 0
+
+ fun refresh(context: Context) {
+ val app = context.applicationContext
+ val seq = ++listing
+ Thread({
+ val list = runCatching { load(app) }.getOrDefault(emptyList())
+ main.post { if (seq == listing) pinned = list }
+ }, "home-pins").start()
+ }
+
+ private fun load(context: Context): List {
+ if (!HomeApp.canUseShortcuts(context)) return emptyList()
+ val launcher = context.getSystemService(LauncherApps::class.java)
+ val users = context.getSystemService(UserManager::class.java)
+ val pm = context.packageManager
+ val own = Process.myUserHandle()
+ val query = LauncherApps.ShortcutQuery().setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
+ return users.userProfiles.flatMap { user ->
+ val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
+ runCatching { launcher.getShortcuts(query, user) }.getOrNull().orEmpty()
+ .filter { it.isEnabled && it.isPinned }
+ .map { info ->
+ val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.`package`, 0)).toString() }
+ .getOrDefault(info.`package`)
+ Pinned(info, HomeApp.shortcutIcon(context, info), appLabel, serial)
+ }
+ }
+ }
+
+ fun accept(context: Context, request: LauncherApps.PinItemRequest): Boolean {
+ val ok = runCatching { request.isValid && request.accept() }.getOrDefault(false)
+ if (ok) refresh(context)
+ return ok
+ }
+
+ fun unpin(context: Context, pinned: Pinned) {
+ val info = pinned.info
+ val launcher = context.getSystemService(LauncherApps::class.java)
+ val query = LauncherApps.ShortcutQuery().setPackage(info.`package`).setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
+ val unpinned = runCatching {
+ val current = checkNotNull(launcher.getShortcuts(query, info.userHandle))
+ val keep = current.map { it.id } - info.id
+ launcher.pinShortcuts(info.`package`, keep, info.userHandle)
+ }.isSuccess
+ if (!unpinned) return
+ listing++
+ this.pinned = this.pinned.filterNot { it.key == pinned.key }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt b/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt
new file mode 100644
index 000000000..886f5f0e8
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt
@@ -0,0 +1,316 @@
+package com.droiddeck.launcher
+
+import android.app.Activity
+import android.appwidget.AppWidgetHost
+import android.appwidget.AppWidgetHostView
+import android.appwidget.AppWidgetManager
+import android.appwidget.AppWidgetProviderInfo
+import android.content.Context
+import android.content.Intent
+import android.content.pm.LauncherApps
+import android.graphics.Bitmap
+import android.os.Build
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.util.SizeF
+import android.view.HapticFeedbackConstants
+import android.view.MotionEvent
+import android.view.ViewConfiguration
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.core.graphics.drawable.toBitmap
+import org.json.JSONArray
+import org.json.JSONObject
+import kotlin.math.hypot
+import kotlin.math.roundToInt
+
+object HomeWidgets {
+ data class Placed(val id: Int, val widthDp: Int, val heightDp: Int)
+
+ data class Provider(
+ val info: AppWidgetProviderInfo,
+ val label: String,
+ val appLabel: String,
+ val preview: Bitmap?,
+ val widthDp: Int,
+ val heightDp: Int,
+ )
+
+ private const val HOST_ID = 0x0DDE
+ private const val PREFS = "home_launcher"
+ private const val KEY = "widgets"
+ private const val REQUEST_BIND = 0x0DD1
+ private const val REQUEST_CONFIGURE = 0x0DD2
+ private const val REQUEST_RECONFIGURE = 0x0DD3
+ const val MIN_WIDTH_DP = 96
+ const val MIN_HEIGHT_DP = 56
+
+ var widgets by mutableStateOf>(emptyList())
+ private set
+ var providers by mutableStateOf?>(null)
+ private set
+ private var loaded = false
+ private var host: Host? = null
+ private var pending: AppWidgetProviderInfo? = null
+ private var pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
+ private var pinRequest: LauncherApps.PinItemRequest? = null
+ private val main = Handler(Looper.getMainLooper())
+
+ private class Host(context: Context) : AppWidgetHost(context, HOST_ID) {
+ override fun onCreateView(context: Context, appWidgetId: Int, appWidget: AppWidgetProviderInfo?): AppWidgetHostView =
+ HomeWidgetView(context)
+ }
+
+ class HomeWidgetView(context: Context) : AppWidgetHostView(context) {
+ var onLongPress: (() -> Unit)? = null
+ private var fired = false
+ private var downX = 0f
+ private var downY = 0f
+ private val slop = ViewConfiguration.get(context).scaledTouchSlop
+ private val longPress = Runnable {
+ fired = true
+ performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
+ onLongPress?.invoke()
+ }
+
+ override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
+ when (ev.actionMasked) {
+ MotionEvent.ACTION_DOWN -> {
+ fired = false
+ downX = ev.x
+ downY = ev.y
+ postDelayed(longPress, ViewConfiguration.getLongPressTimeout().toLong())
+ }
+ MotionEvent.ACTION_MOVE -> if (hypot(ev.x - downX, ev.y - downY) > slop) removeCallbacks(longPress)
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> removeCallbacks(longPress)
+ }
+ return fired
+ }
+
+ override fun onTouchEvent(event: MotionEvent): Boolean {
+ if (fired) {
+ if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) fired = false
+ return true
+ }
+ return super.onTouchEvent(event)
+ }
+ }
+
+ private fun host(context: Context): Host = host ?: Host(context.applicationContext).also { host = it }
+
+ fun load(context: Context) {
+ if (loaded) return
+ loaded = true
+ val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
+ val manager = AppWidgetManager.getInstance(context)
+ val parsed = runCatching {
+ val array = JSONArray(raw)
+ (0 until array.length()).map { i ->
+ val o = array.getJSONObject(i)
+ Placed(o.getInt("id"), o.getInt("w"), o.getInt("h"))
+ }
+ }.getOrDefault(emptyList())
+ val live = parsed.filter { manager.getAppWidgetInfo(it.id) != null }
+ parsed.filterNot { it in live }.forEach { host(context).deleteAppWidgetId(it.id) }
+ widgets = live
+ if (live.size != parsed.size) save(context)
+ }
+
+ fun startListening(context: Context) {
+ load(context)
+ runCatching { host(context).startListening() }
+ }
+
+ fun stopListening(context: Context) {
+ runCatching { host(context).stopListening() }
+ }
+
+ fun info(context: Context, id: Int): AppWidgetProviderInfo? = AppWidgetManager.getInstance(context).getAppWidgetInfo(id)
+
+ fun createView(context: Context, id: Int): HomeWidgetView? {
+ val info = info(context, id) ?: return null
+ return host(context).createView(context, id, info) as? HomeWidgetView
+ }
+
+ fun applySize(view: AppWidgetHostView, widthDp: Int, heightDp: Int) {
+ if (Build.VERSION.SDK_INT >= 31) {
+ view.updateAppWidgetSize(Bundle(), listOf(SizeF(widthDp.toFloat(), heightDp.toFloat())))
+ } else {
+ @Suppress("DEPRECATION")
+ view.updateAppWidgetSize(null, widthDp, heightDp, widthDp, heightDp)
+ }
+ }
+
+ fun loadProviders(context: Context) {
+ if (providers != null) return
+ val app = context.applicationContext
+ Thread({
+ val pm = app.packageManager
+ val manager = AppWidgetManager.getInstance(app)
+ val dpi = app.resources.displayMetrics.densityDpi
+ val list = manager.installedProviders.mapNotNull { info ->
+ runCatching {
+ val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.provider.packageName, 0)).toString() }
+ .getOrDefault(info.provider.packageName)
+ val drawable = info.loadPreviewImage(app, dpi) ?: info.loadIcon(app, dpi)
+ val preview = drawable?.let { d ->
+ val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
+ val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
+ val scale = minOf(1f, 360f / maxOf(w, h))
+ d.toBitmap((w * scale).roundToInt().coerceAtLeast(1), (h * scale).roundToInt().coerceAtLeast(1))
+ }
+ val (w, h) = defaultSize(app, info)
+ Provider(info, info.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { appLabel }, appLabel, preview, w, h)
+ }.getOrNull()
+ }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, Provider::appLabel).thenBy(String.CASE_INSENSITIVE_ORDER, Provider::label))
+ main.post { providers = list }
+ }, "widget-providers").start()
+ }
+
+ fun refreshProviders(context: Context) {
+ providers = null
+ loadProviders(context)
+ }
+
+ private fun defaultSize(context: Context, info: AppWidgetProviderInfo): Pair {
+ val density = context.resources.displayMetrics.density
+ var w = (info.minWidth / density).roundToInt()
+ var h = (info.minHeight / density).roundToInt()
+ if (Build.VERSION.SDK_INT >= 31) {
+ if (info.targetCellWidth > 0) w = maxOf(w, info.targetCellWidth * 80)
+ if (info.targetCellHeight > 0) h = maxOf(h, info.targetCellHeight * 80)
+ }
+ return w.coerceIn(160, 560) to h.coerceIn(MIN_HEIGHT_DP, 360)
+ }
+
+ fun minSize(context: Context, id: Int): Pair {
+ val info = info(context, id) ?: return MIN_WIDTH_DP to MIN_HEIGHT_DP
+ val density = context.resources.displayMetrics.density
+ val w = (if (info.minResizeWidth > 0) info.minResizeWidth else info.minWidth) / density
+ val h = (if (info.minResizeHeight > 0) info.minResizeHeight else info.minHeight) / density
+ return w.roundToInt().coerceAtLeast(MIN_WIDTH_DP) to h.roundToInt().coerceAtLeast(MIN_HEIGHT_DP)
+ }
+
+ fun add(activity: Activity, provider: Provider) {
+ if (pendingId == AppWidgetManager.INVALID_APPWIDGET_ID) add(activity, provider.info, null)
+ }
+
+ fun addPinned(activity: Activity, request: LauncherApps.PinItemRequest): Boolean {
+ if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) return false
+ val info = request.getAppWidgetProviderInfo(activity) ?: return false
+ load(activity)
+ add(activity, info, request)
+ return pending != null
+ }
+
+ private fun add(activity: Activity, info: AppWidgetProviderInfo, request: LauncherApps.PinItemRequest?) {
+ val h = host(activity)
+ val id = h.allocateAppWidgetId()
+ pending = info
+ pendingId = id
+ pinRequest = request
+ val manager = AppWidgetManager.getInstance(activity)
+ val bound = runCatching { manager.bindAppWidgetIdIfAllowed(id, info.profile, info.provider, null) }.getOrDefault(false)
+ if (bound) {
+ bound(activity, id, info)
+ return
+ }
+ val bind = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile)
+ @Suppress("DEPRECATION")
+ runCatching { activity.startActivityForResult(bind, REQUEST_BIND) }.onFailure { abandon(activity) }
+ }
+
+ private fun bound(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
+ val request = pinRequest
+ if (request == null) {
+ configure(activity, id, info)
+ return
+ }
+ val accepted = runCatching { request.isValid && request.accept(Bundle().apply { putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, id) }) }
+ .getOrDefault(false)
+ if (accepted) place(activity, id, info) else abandon(activity)
+ }
+
+ private fun configure(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
+ val optional = Build.VERSION.SDK_INT >= 31 &&
+ info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0
+ if (info.configure == null || optional) {
+ place(activity, id, info)
+ return
+ }
+ runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_CONFIGURE, null) }
+ .onFailure { place(activity, id, info) }
+ }
+
+ fun canReconfigure(context: Context, id: Int): Boolean {
+ val info = info(context, id) ?: return false
+ if (info.configure == null) return false
+ return Build.VERSION.SDK_INT < 28 || info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE != 0
+ }
+
+ fun reconfigure(activity: Activity, id: Int) {
+ runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_RECONFIGURE, null) }
+ }
+
+ fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int): Boolean {
+ when (requestCode) {
+ REQUEST_BIND -> {
+ val info = pending
+ if (resultCode == Activity.RESULT_OK && info != null) bound(activity, pendingId, info) else abandon(activity)
+ }
+ REQUEST_CONFIGURE -> {
+ val info = pending
+ if (resultCode == Activity.RESULT_OK && info != null) place(activity, pendingId, info) else abandon(activity)
+ }
+ REQUEST_RECONFIGURE -> Unit
+ else -> return false
+ }
+ return true
+ }
+
+ private fun abandon(context: Context) {
+ if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) host(context).deleteAppWidgetId(pendingId)
+ pending = null
+ pinRequest = null
+ pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
+ }
+
+ private fun place(context: Context, id: Int, info: AppWidgetProviderInfo) {
+ val (w, h) = defaultSize(context, info)
+ pending = null
+ pinRequest = null
+ pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
+ widgets = widgets + Placed(id, w, h)
+ save(context)
+ }
+
+ fun resize(context: Context, id: Int, widthDp: Int, heightDp: Int) {
+ widgets = widgets.map { if (it.id == id) it.copy(widthDp = widthDp, heightDp = heightDp) else it }
+ save(context)
+ }
+
+ fun move(context: Context, id: Int, by: Int) {
+ val i = widgets.indexOfFirst { it.id == id }
+ val j = i + by
+ if (i < 0 || j !in widgets.indices) return
+ widgets = widgets.toMutableList().apply { add(j, removeAt(i)) }
+ save(context)
+ }
+
+ fun remove(context: Context, id: Int) {
+ host(context).deleteAppWidgetId(id)
+ widgets = widgets.filterNot { it.id == id }
+ save(context)
+ }
+
+ private fun save(context: Context) {
+ val array = JSONArray()
+ for (w in widgets) array.put(JSONObject().put("id", w.id).put("w", w.widthDp).put("h", w.heightDp))
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt b/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt
new file mode 100644
index 000000000..5632c0854
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt
@@ -0,0 +1,346 @@
+package com.droiddeck.launcher
+
+import android.app.ActivityOptions
+import android.app.AppOpsManager
+import android.app.PictureInPictureParams
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.content.res.Configuration
+import android.os.Build
+import android.os.Bundle
+import android.os.Process
+import android.provider.Settings
+import android.util.Rational
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.BackHandler
+import androidx.activity.compose.setContent
+import androidx.compose.animation.core.LinearEasing
+import androidx.compose.animation.core.RepeatMode
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.infiniteRepeatable
+import androidx.compose.animation.core.rememberInfiniteTransition
+import androidx.compose.animation.core.tween
+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.Row
+import androidx.compose.foundation.layout.Spacer
+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.layout.widthIn
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.produceState
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.scale
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+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
+import com.droiddeck.launcher.ui.LocalPalette
+import com.droiddeck.launcher.ui.PrimaryButton
+import com.droiddeck.launcher.ui.SecondaryButton
+import kotlinx.coroutines.delay
+
+class PairingGuideActivity : ComponentActivity() {
+ 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
+
+ override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
+
+ 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
+ }
+
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ setIntent(intent)
+ settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
+ toggleOnly = intent.getBooleanExtra(EXTRA_TOGGLE_ONLY, false)
+ launchPending = true
+ }
+
+ override fun onResume() {
+ super.onResume()
+ if (!launchPending) return
+ if (inPip || settingsDisplay != null) {
+ launchSettings()
+ return
+ }
+ enterPip()
+ if (!inPip) launchSettings()
+ }
+
+ override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
+ super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
+ inPip = isInPictureInPictureMode
+ if (isInPictureInPictureMode && launchPending) launchSettings()
+ }
+
+ private fun launchSettings() {
+ launchPending = false
+ openSettings(stepFor(SettingsState.read(this), WirelessAdbPairingService.stage.value, toggleOnly))
+ }
+
+ private fun enterPip() {
+ inPip = runCatching {
+ enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(4, 3)).build())
+ }.getOrDefault(false)
+ }
+
+ private fun openSettings(step: Step) {
+ val intent = if (step == Step.BUILD_NUMBER) {
+ Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number")
+ } else {
+ Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).apply {
+ if (step != Step.CHILD_PROCESS) putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
+ }
+ }.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ val display = settingsDisplay
+ runCatching {
+ if (display == null) startActivity(intent)
+ else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
+ }.onFailure {
+ runCatching { startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
+ }
+ }
+
+ private fun returnToApp() {
+ startActivity(Intent(this, FrontEndActivity::class.java)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
+ finish()
+ }
+
+ @Composable
+ private fun Guide() {
+ val stage by WirelessAdbPairingService.stage.collectAsState()
+ val settingsState by produceState(SettingsState.read(this)) {
+ while (true) {
+ value = SettingsState.read(this@PairingGuideActivity)
+ delay(500)
+ }
+ }
+ val step = stepFor(settingsState, stage, toggleOnly)
+ var previous by remember { mutableStateOf(step) }
+ LaunchedEffect(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() }
+ Step.FAILED -> { delay(3_000); returnToApp() }
+ else -> Unit
+ }
+ }
+ LaunchedEffect(stage) { if (stage == Stage.Idle && !toggleOnly) finish() }
+ BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() }
+
+ Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {
+ if (inPip) CompactStep(step, stage)
+ else FullGuide(step, stage)
+ }
+ }
+
+ @Composable
+ private fun CompactStep(step: Step, stage: Stage) {
+ Column(Modifier.fillMaxSize().padding(10.dp), verticalArrangement = Arrangement.SpaceBetween) {
+ Text(
+ instruction(step, stage), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold,
+ color = MaterialTheme.colorScheme.onBackground, maxLines = 3, overflow = TextOverflow.Ellipsis,
+ )
+ StepVisual(step, compact = true)
+ StepDots(step)
+ }
+ }
+
+ @Composable
+ private fun FullGuide(step: Step, stage: Stage) {
+ Column(
+ Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(24.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ ) {
+ 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)
+ StepDots(step)
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ if (step == Step.DONE || step == Step.FAILED) {
+ PrimaryButton(stringResource(R.string.common_back), onClick = ::returnToApp)
+ } else {
+ PrimaryButton(stringResource(R.string.gate_open_dev), onClick = {
+ if (settingsDisplay == null) enterPip()
+ openSettings(step)
+ })
+ SecondaryButton(stringResource(R.string.common_cancel), onClick = {
+ if (!toggleOnly) WirelessAdbPairingService.cancel(this@PairingGuideActivity)
+ returnToApp()
+ })
+ }
+ }
+ }
+ }
+
+ @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_working)
+ Step.DONE -> stringResource(R.string.adbpair_title_done)
+ Step.FAILED -> (stage as? Stage.Failed)?.error ?: stringResource(R.string.adbpair_title_failed)
+ }
+
+ @Composable
+ private fun StepVisual(step: Step, compact: Boolean) {
+ val colors = MaterialTheme.colorScheme
+ val accent = LocalPalette.current.signal
+ val pulse = rememberInfiniteTransition(label = "guidePulse")
+ 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)
+ Step.WORKING, Step.DONE, Step.FAILED -> return
+ }
+ val rowHeight = if (compact) 34.dp else 56.dp
+ Row(
+ Modifier.fillMaxWidth().height(rowHeight).background(colors.surfaceVariant, RoundedCornerShape(10.dp))
+ .border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(10.dp)).padding(horizontal = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ 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, 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) {
+ Box(Modifier.size(if (compact) 18.dp else 26.dp).scale(0.6f + beat * 0.8f).alpha(1f - beat)
+ .background(accent, CircleShape))
+ Box(Modifier.size(if (compact) 8.dp else 12.dp).background(accent, CircleShape))
+ }
+ }
+ }
+ }
+ }
+
+ @Composable
+ private fun Toggle(on: Boolean, accent: Color, compact: Boolean) {
+ val width = if (compact) 26.dp else 40.dp
+ val knob = if (compact) 12.dp else 18.dp
+ Box(
+ Modifier.width(width).height(knob + 4.dp)
+ .background(if (on) accent.copy(alpha = 0.6f) else MaterialTheme.colorScheme.outline, CircleShape).padding(2.dp),
+ contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart,
+ ) { Box(Modifier.size(knob).background(Color.White, CircleShape)) }
+ }
+
+ @Composable
+ private fun StepDots(step: Step) {
+ val accent = LocalPalette.current.signal
+ 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, _ ->
+ Box(Modifier.size(if (index == at) 8.dp else 6.dp)
+ .background(if (index <= at) accent else MaterialTheme.colorScheme.outline, CircleShape))
+ }
+ Spacer(Modifier.width(2.dp))
+ }
+ }
+
+ 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, 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
+ is Stage.CodeNeeded -> Step.CODE
+ else -> when {
+ !settings.developerOptions -> Step.BUILD_NUMBER
+ !settings.wirelessDebugging -> Step.WIRELESS_DEBUGGING
+ else -> Step.PAIR
+ }
+ }
+
+ fun canFloat(context: Context): Boolean {
+ if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false
+ val ops = context.getSystemService(AppOpsManager::class.java) ?: return true
+ val mode = if (Build.VERSION.SDK_INT >= 29) {
+ ops.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
+ } else {
+ @Suppress("DEPRECATION")
+ ops.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
+ }
+ return mode == AppOpsManager.MODE_ALLOWED
+ }
+
+ 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
+ }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/PinRequestActivity.kt b/app/src/main/java/com/droiddeck/launcher/PinRequestActivity.kt
new file mode 100644
index 000000000..ca8d382fe
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/PinRequestActivity.kt
@@ -0,0 +1,82 @@
+package com.droiddeck.launcher
+
+import android.content.Intent
+import android.content.pm.LauncherApps
+import android.graphics.Bitmap
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.core.graphics.drawable.toBitmap
+import com.droiddeck.launcher.core.AppUiPrefs
+import com.droiddeck.launcher.ui.DroidDeckTheme
+import com.droiddeck.launcher.ui.PinRequestPrompt
+
+class PinRequestActivity : ComponentActivity() {
+ override fun attachBaseContext(newBase: android.content.Context) {
+ super.attachBaseContext(newBase)
+ com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ val request = runCatching { getSystemService(LauncherApps::class.java).getPinItemRequest(intent) }.getOrNull()
+ if (request == null || !request.isValid) {
+ finish()
+ return
+ }
+ val prompt = when (request.requestType) {
+ LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT -> request.shortcutInfo?.let { info ->
+ val appLabel = appLabel(info.`package`)
+ Triple(info.shortLabel?.toString().orEmpty().ifEmpty { appLabel }, appLabel, HomeApp.shortcutIcon(this, info))
+ }
+ LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET -> request.getAppWidgetProviderInfo(this)?.let { info ->
+ val appLabel = appLabel(info.provider.packageName)
+ val dpi = resources.displayMetrics.densityDpi
+ val icon = runCatching { (info.loadPreviewImage(this, dpi) ?: info.loadIcon(this, dpi))?.let(::scaled) }.getOrNull()
+ Triple(info.loadLabel(packageManager)?.toString().orEmpty().ifEmpty { appLabel }, appLabel, icon)
+ }
+ else -> null
+ }
+ if (prompt == null) {
+ finish()
+ return
+ }
+ val (label, appLabel, icon) = prompt
+ val widget = request.requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET
+ setContent {
+ DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
+ PinRequestPrompt(
+ label = label, appLabel = appLabel, icon = icon, wide = widget,
+ onAdd = {
+ if (!widget) {
+ HomePins.accept(this, request)
+ finish()
+ } else if (!HomeWidgets.addPinned(this, request)) finish()
+ },
+ onCancel = { finish() },
+ )
+ }
+ }
+ }
+
+ @Suppress("OVERRIDE_DEPRECATION")
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) {
+ finish()
+ return
+ }
+ @Suppress("DEPRECATION")
+ super.onActivityResult(requestCode, resultCode, data)
+ }
+
+ private fun appLabel(packageName: String): String =
+ runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString() }
+ .getOrDefault(packageName)
+
+ private fun scaled(d: android.graphics.drawable.Drawable): Bitmap {
+ val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
+ val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
+ val k = minOf(1f, 480f / maxOf(w, h))
+ return d.toBitmap((w * k).toInt().coerceAtLeast(1), (h * k).toInt().coerceAtLeast(1))
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt
index 5bd651cf5..5251b50da 100644
--- a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt
@@ -1,6 +1,8 @@
package com.droiddeck.launcher
import android.os.Handler
+import android.util.Log
+import androidx.annotation.VisibleForTesting
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
@@ -8,31 +10,58 @@ import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState
+import com.droiddeck.launcher.session.SessionPhase
+import com.droiddeck.launcher.frontend.AutoComponents
+import com.droiddeck.launcher.runtime.LinuxRuntime
+import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
-internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
- var protonRows by mutableStateOf>(emptyList())
- var protonBusyId by mutableStateOf(null)
- var protonStage by mutableStateOf(null)
- var protonPercent by mutableIntStateOf(-1)
+internal class ProtonMenu(
+ private val activity: android.app.Activity,
+ private val ui: Handler,
+ private val idle: () -> Boolean = { true },
+) {
+ private object Operation {
+ val rows = mutableStateOf>(emptyList())
+ val busyId = mutableStateOf(null)
+ val stage = mutableStateOf(null)
+ val percent = mutableIntStateOf(-1)
+ val problem = mutableStateOf(null)
+ }
+ var protonRows by Operation.rows
+ var protonBusyId by Operation.busyId
+ var protonStage by Operation.stage
+ var protonPercent by Operation.percent
+ var protonProblem by Operation.problem
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
+ @VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
+ { tool, progress -> ProtonExtras.install(activity, tool, progress) }
- fun installProton(id: String) {
+ fun installProton(id: String, automatic: Boolean = false) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
- if (protonBusyId != null || SessionState.running) return
+ if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
ProtonExtras.unqueue(activity, tool)
protonBusyId = id
+ protonProblem = null
protonStage = activity.getString(R.string.store_starting)
protonPercent = -1
Thread({
- val problem = ProtonExtras.install(activity, tool) { label, value ->
- ui.post { protonStage = label; protonPercent = value }
- }
+ val problem = runCatching {
+ installer(tool) { label, value ->
+ ui.post { protonStage = label; protonPercent = value }
+ }
+ }.getOrElse { it.message ?: it.javaClass.simpleName }
+ if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
ui.post {
+ protonProblem = problem
protonBusyId = null
protonStage = null
protonPercent = -1
refreshProtons()
- if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
+ if (problem != null) {
+ if (automatic) Log.w("ProtonMenu", "auto-update ${tool.id}: $problem")
+ else android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
+ }
+ if (automatic) ensureAutoUpdates()
}
}, "install-proton-$id").start()
}
@@ -41,10 +70,12 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || SessionState.running) return
protonBusyId = id
+ protonProblem = null
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
protonPercent = -1
Thread({
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
+ if (tool.id == ProtonExtras.OWN && ProtonExtras.installedAll(activity, tool).isEmpty()) ProtonExtras.setDeclined(activity, true)
ui.post {
protonBusyId = null
protonStage = null
@@ -64,7 +95,39 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
if (!checking.compareAndSet(false, true)) return
Thread({
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
- if (asked) ui.post { refreshProtons() }
+ ui.post {
+ if (asked) refreshProtons()
+ ensureAutoUpdates()
+ }
}, "proton-updates").start()
}
+
+ internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
+ if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
+ ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
+ SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
+ !LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
+ if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
+ protonBusyId = ProtonExtras.OWN
+ protonProblem = null
+ Thread({
+ ProtonExtras.tidy(activity)
+ val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
+ ui.post {
+ protonBusyId = null
+ refreshProtons()
+ if (tidied) ensureAutoUpdates()
+ }
+ }, "proton-tidy").start()
+ return
+ }
+ val attempts = activity.getSharedPreferences("proton-auto-updates", android.content.Context.MODE_PRIVATE)
+ val (tool, update) = ProtonExtras.tools.firstNotNullOfOrNull { tool ->
+ val update = ProtonExtras.update(activity, tool) ?: ProtonExtras.missing(activity, tool) ?: return@firstNotNullOfOrNull null
+ val previous = attempts.getLong("${tool.id}.at", 0L)
+ if (attempts.getString("${tool.id}.tag", null) != update || now - previous !in 0 until 15L * 60 * 1000) tool to update else null
+ } ?: return
+ attempts.edit().putString("${tool.id}.tag", update).putLong("${tool.id}.at", now).apply()
+ installProton(tool.id, automatic = true)
+ }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt b/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt
index 28270e195..98e5a0b22 100644
--- a/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt
@@ -71,7 +71,6 @@ class QuestXrActivity : NativeActivity() {
}
} finally {
synchronized(steamVrLock) {
- // A retiring activity must not stop a replacement's SteamVR session.
if (steamVrOwner === this) {
if (sessionAlive()) SteamVr.run(this, "stop")
steamVrOwner = null
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index 6de07a00d..d282681e2 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -9,6 +9,7 @@ import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
+import android.database.ContentObserver
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
@@ -66,17 +67,21 @@ import com.droiddeck.launcher.gpu.ScreenEffectLooks
import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.gpu.Lossless
import com.droiddeck.launcher.gpu.TurnipDriver
-import com.droiddeck.launcher.input.EvdevKeys
+import com.droiddeck.launcher.input.HomeGuideInput
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.OnScreenControls
import com.droiddeck.launcher.input.PadBridge
+import com.droiddeck.launcher.input.PhysicalShortcuts
+import com.droiddeck.launcher.input.PhysicalShortcutRouter
import com.droiddeck.launcher.input.PadMouse
import com.droiddeck.launcher.input.PadState
+import com.droiddeck.launcher.input.ScreenKeys
import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.DirectTouchHold
+import com.droiddeck.launcher.input.GestureTouchStreamGate
import com.droiddeck.launcher.input.PointerGestures
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
@@ -86,7 +91,8 @@ import com.droiddeck.launcher.input.TouchscreenGestures
import com.droiddeck.launcher.input.ScrollTouchGestures
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.LoadingState
-import com.droiddeck.launcher.session.PerfHud
+import com.droiddeck.launcher.hud.DroidDeckHudConfig
+import com.droiddeck.launcher.hud.DroidDeckHudHost
import com.droiddeck.launcher.session.PerfMode
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.session.GameEnvironmentStore
@@ -113,6 +119,10 @@ import com.droiddeck.launcher.ui.LoadingOverlay
import com.droiddeck.launcher.ui.SessionDrawer
import com.droiddeck.launcher.ui.SessionPausedOverlay
import com.droiddeck.launcher.ui.SecondScreenPresentation
+import com.droiddeck.launcher.ui.BottomDashboard
+import com.droiddeck.launcher.ui.BottomPage
+import com.droiddeck.launcher.ui.sessionBottomPages
+import com.droiddeck.launcher.ui.BottomPageActions
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -154,8 +164,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var surfaceView: SurfaceView
private lateinit var sessionOverlay: ComposeView
private lateinit var loading: LoadingState
- private lateinit var hud: PerfHud
+ private lateinit var hud: DroidDeckHudHost
+ private lateinit var memoryHud: com.droiddeck.launcher.session.MemoryHud
private var padBridge: PadBridge? = null
+ private val physicalShortcuts = PhysicalShortcutRouter()
private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null
private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null
private var padMotion: com.droiddeck.launcher.input.PadMotion? = null
@@ -183,7 +195,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val steamTouchRetry = Runnable { updateOnScreenControls() }
private var steamTouchOptions: com.droiddeck.launcher.input.SteamTouchConfig.Options? = null
private var routedTouchMode = SessionPrefs.TOUCH_AUTO
+ private var touchRoute: com.droiddeck.launcher.input.TouchRouter.Route? = null
private var keyboard: KeyboardHost? = null
+ private var desktopKeyboardButton: com.droiddeck.launcher.input.DesktopKeyboardButton? = null
+ private var lastUserPressMs = 0L
+ private var pressDownX = 0f
+ private var pressDownY = 0f
+ private var pressTravel = 0f
+ private var pressMoved = false
private var controllerSettings by mutableStateOf(null)
private val sessionClipboard by lazy {
SessionClipboard(this) {
@@ -193,15 +212,30 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var watching = true
private lateinit var touchpad: TouchpadGestures
private lateinit var directTouchHold: DirectTouchHold
+ private lateinit var twoFingerGestures: com.droiddeck.launcher.input.TwoFingerGestures
private lateinit var threeFingerTap: com.droiddeck.launcher.input.ThreeFingerTap
private lateinit var touchscreenGestures: TouchscreenGestures
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
private var gestureGame: String? = null
+ private var gameStarts by mutableIntStateOf(0)
private var gestureSettingsOpen by mutableStateOf(false)
+ private var steamImportAsk by mutableStateOf(null)
+ private var steamImportAnswered: String? = null
+ private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)
+ private var screenKeyPickerOpen by mutableStateOf(false)
+ private var screenKeyBind: List? = null
+ private var screenKeyDir: Int? = null
+ private var screenKeyTextFocus = false
+ private var screenKeyEdit by mutableStateOf(null)
+ private var screenLayoutsOpen by mutableStateOf(false)
+ private var screenKeysShown by mutableStateOf(true)
+ private var screenLayoutNames by mutableStateOf(listOf())
+ private var screenKeys: ScreenKeys? = null
private var recognizedGesture by mutableStateOf(null)
private var gesturePointerX = 0f
private var gesturePointerY = 0f
private var gesturePointerReady = false
+ private val gestureTouchStreamGate = GestureTouchStreamGate()
private val clearRecognizedGesture = Runnable { recognizedGesture = null }
private val gestureKeysDown = mutableSetOf()
private lateinit var scrollTouch: ScrollTouchGestures
@@ -218,6 +252,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val cursorHide = Runnable { cursorVisible = false }
private var lastPadInputMs = 0L
private val cursorBuf = IntArray(WaylandCompositor.CURSOR_BUF_INTS)
+ private val cursorPosBuf = IntArray(2)
private var cursorSerial = 0
private var clientHidesCursor = false
private var pointerLocked = false
@@ -227,9 +262,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
gesturePointerReady = false
pointerLocked = locked
Log.i(TAG, "pointer lock " + if (locked) "taken by a program" else "released")
+ if (locked) openEvdevMouse() else closeEvdevMouse()
padMouseCheckedAt = 0L
if (::padMouse.isInitialized) padMouseMode()
- // Touchpad deltas are measured from the middle while locked (moveLockedPointer).
if (locked && ::touchpad.isInitialized) {
drawnRect()?.let { touchpad.place(it.centerX(), it.centerY()) }
cursorVisible = false
@@ -241,9 +276,40 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var cursorHotX by mutableStateOf(0)
private var cursorHotY by mutableStateOf(0)
private var cursorImageScale by mutableStateOf(1f)
- private val cursorResync = Runnable { if (syncClientCursor() && clientHidesCursor) cursorVisible = false }
+ private var cursorResyncIdle = 0
+ private val cursorResync = object : Runnable {
+ override fun run() {
+ if (syncClientCursor() && clientHidesCursor) {
+ cursorVisible = false
+ return
+ }
+ if (touchDrivesPointer()) return
+ cursorResyncIdle = if (alignCursorToGuest()) 0 else cursorResyncIdle + 1
+ if (!cursorVisible || pointerLocked) return
+ if (cursorResyncIdle > CURSOR_RESYNC_IDLE_TICKS) return
+ uiHandler.postDelayed(this, 60)
+ }
+ }
+
+ private fun alignCursorToGuest(): Boolean {
+ if (pointerLocked || !CompositorHost.isStarted) return false
+ if (!WaylandCompositor.nativeCursorInputPos(cursorPosBuf)) return false
+ if (surfaceView.width <= 0 || surfaceView.height <= 0) return false
+ val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * surfaceView.width
+ val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * surfaceView.height
+ if (kotlin.math.abs(x - cursorPos.x) < 0.75f && kotlin.math.abs(y - cursorPos.y) < 0.75f) return false
+ cursorPos = androidx.compose.ui.geometry.Offset(x, y)
+ return true
+ }
private val uiHandler = Handler(Looper.getMainLooper())
private var pendingBackAction: Runnable? = null
+ private val backQamInput = com.droiddeck.launcher.input.BackQamInput(
+ setPressed = { padBridge?.setBackQamPressed(it) },
+ onTap = { performBackAction(double = it) },
+ doubleTapMs = { backDoubleTapMs.toLong() },
+ onCancel = { padBridge?.cancelBackQam() },
+ holds = { backHold },
+ )
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
private var drawerDirectionDownTime = 0L
private var drawerDirectionDeviceId = -1
@@ -270,8 +336,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private val resumeKeysDown = mutableSetOf>()
+ private val drawerShortcutKeysDown = mutableSetOf>()
- private var drawerOpen by mutableStateOf(false)
+ private var drawerOpenState by mutableStateOf(false)
+ private var typingReturnMode: SecondScreenMode? = null
+ private var drawerDocked by mutableStateOf(false)
+ private var drawerLayerOpen = false
+ private var drawerBackRequests by mutableIntStateOf(0)
+ private var drawerOpen: Boolean
+ get() = drawerOpenState
+ set(value) {
+ if (value == drawerOpenState) return
+ drawerLayerOpen = false
+ if (value) drawerDocked = dockDrawer() && openDockedMenu()
+ drawerOpenState = value
+ if (!value && drawerDocked) closeDockedMenu()
+ }
private var quitFrom by mutableStateOf(null)
private var quitFlooded = false
private var leaving by mutableStateOf(false)
@@ -280,6 +360,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var drawerDefaultProton by mutableStateOf(null)
private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) }
private var drawerGameProfileId by mutableStateOf(null)
+ private var fpsLimit by mutableStateOf(SessionState.fpsLimit)
+
+ private fun noSteamSession(): Boolean = (SessionState.mode == SessionService.MODE_RUN &&
+ SessionState.program in setOf(
+ com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.EPIC,
+ com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET,
+ )) || SessionState.mode == SessionService.MODE_DESKTOP
private val drawerGameInventory = GameProfileInventoryCache()
private var drawerGameInventoryRevision = 0L
private var drawerGameFexPresetSaving by mutableStateOf(false)
@@ -300,17 +387,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val drawerGameProfileRefreshes = LatestRequestCoordinator()
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
private var drawerControllerActive by mutableStateOf(false)
+ private var backHold by mutableStateOf(true)
private var backActionsInverted by mutableStateOf(false)
- private var lowLatencyController by mutableStateOf(false)
- private var lowLatencyTouch by mutableStateOf(false)
+ private var backDoubleTapMs by mutableStateOf(500)
+ private var lowLatency by mutableStateOf(true)
+ private var evdevMouseOn by mutableStateOf(false)
+ private var directCursorOn by mutableStateOf(false)
+ private var mouseWriter: com.droiddeck.launcher.input.FakeInputWriter? = null
+ private var evdevMouseActive = false
+ private var lastMouseX = Float.NaN
+ private var lastMouseY = Float.NaN
private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
private var pcKeyboardOpen by mutableStateOf(false)
private var achievementsInFront by mutableStateOf(null)
private var achievementsOpen by mutableStateOf(false)
private var hudOn by mutableStateOf(true)
- private var hudFps by mutableStateOf(true)
- private var hudBattery by mutableStateOf(true)
- private var hudGraph by mutableStateOf(true)
+ private var hudConfig by mutableStateOf