diff --git a/.github/workflows/build-desktop-kde.yml b/.github/workflows/build-desktop-kde.yml new file mode 100644 index 0000000000..9390e1af85 --- /dev/null +++ b/.github/workflows/build-desktop-kde.yml @@ -0,0 +1,101 @@ +name: Build desktop package (KDE Plasma) + +# The desktop the app installs into its Linux runtime on first use: KDE Plasma as SteamOS's desktop +# mode has it, the closure of tools/desktop-kde/seeds.txt over Arch Linux ARM minus what the runtime +# already carries, plus tools/desktop-kde/overlay (tools/desktop-kde/build.sh), every package +# signature-checked. Published as a release in Droid-Deck/DroidDeck-Components with DroidDeck's +# other components; the apk pins it in tools/desktop-kde/release.env (tag, sha256, size). A +# published tag is never rebuilt: the packages are Arch Linux ARM's current ones, so a rebuild +# would not match the pinned sha256. A changed package gets a new tag (desktop-kde-r2, ...) and a +# release.env update. +on: + push: + paths: + - 'tools/desktop-kde/**' + - '.github/workflows/build-desktop-kde.yml' + workflow_dispatch: + inputs: + tag: + description: 'Release tag to publish as (e.g. desktop-kde-r1); empty = artifact only' + required: false + default: '' + +permissions: + contents: write + +jobs: + kwin: + runs-on: ubuntu-24.04-arm + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + - name: Build KWin with nested desktop scaling + run: | + sudo apt-get update -qq && sudo apt-get install -y -qq zstd xz-utils gpgv patch binutils >/dev/null + bash tools/desktop-kde/build-kwin.sh out/kwin + - uses: actions/upload-artifact@v4 + with: + name: desktop-kde-kwin + retention-days: 7 + path: out/kwin/ + build: + needs: kwin + runs-on: ubuntu-24.04 + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: desktop-kde-kwin + path: out/kwin + - 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 xz-utils gpgv >/dev/null + KDE_KWIN_OVERRIDE="$PWD/out/kwin" 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)" + # The package itself too, briefly: enough to try a build on a device before publishing it. + - uses: actions/upload-artifact@v4 + with: + name: desktop-kde + retention-days: 7 + compression-level: 0 + path: | + out/desktop-kde.tar.zst + out/desktop-kde.packages.txt + out/desktop-kde.kwin.txt + out/desktop-kde.sha256 + - 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 }}' + if gh release view "$TAG" >/dev/null 2>&1; then + 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" \ + --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 + gh release edit "$TAG" --latest=false --prerelease=false diff --git a/.github/workflows/build-wlroots.yml b/.github/workflows/build-wlroots.yml deleted file mode 100644 index 92780a2a49..0000000000 --- a/.github/workflows/build-wlroots.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: Build wlroots (patched) - -# The desktop's wlroots (Arch Linux ARM's wlroots0.20, what the desktop package's labwc links) -# rebuilt with tools/wlroots/patches: a Vulkan DMA-BUF allocator for the Adreno node, which is not -# a DRM device, so labwc's vulkan and gles2 renderers can start. Built in an Arch Linux ARM -# container on an arm64 runner and published as a release asset the apk build fetches -# (tools/wlroots/release.env names the tag and sha). The hosted desktop package is never changed. -on: - push: - paths: - - 'tools/wlroots/**' - - '.github/workflows/build-wlroots.yml' - workflow_dispatch: - inputs: - tag: - description: 'Release tag to publish as (e.g. wlroots-0.20.2-p1); empty = artifact only' - required: false - default: '' - -permissions: - contents: write - -jobs: - build: - runs-on: ubuntu-24.04-arm - timeout-minutes: 90 - steps: - - uses: actions/checkout@v4 - - name: Build in Arch Linux ARM - run: | - set -euo pipefail - docker run --rm -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/wlroots/build-in-arch.sh - sudo chown -R "$(id -u):$(id -g)" . - - uses: actions/upload-artifact@v4 - with: - name: wlroots-patched - path: | - wlroots.tzst - wlroots.tzst.sha256 - - name: Publish - if: github.event_name == 'workflow_dispatch' && inputs.tag != '' - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - gh release create "${{ inputs.tag }}" --latest=false --prerelease=false --title "${{ inputs.tag }}" --notes "wlroots 0.20.2 with tools/wlroots/patches (Vulkan DMA-BUF allocator for non-DRM GPU nodes); staged by the apk at /usr/local/lib/droiddeck-wlroots for the desktop's GPU renderers. sha256 $(cut -d' ' -f1 wlroots.tzst.sha256)" wlroots.tzst wlroots.tzst.sha256 || gh release upload "${{ inputs.tag }}" wlroots.tzst wlroots.tzst.sha256 --clobber - # A component the apk fetches by tag, never something users install: it must not - # become the repo's Latest release or appear as a pre-release, also when re-uploaded. - gh release edit "${{ inputs.tag }}" --latest=false --prerelease=false diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d409218765..62fda2a5e0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -44,6 +44,19 @@ jobs: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} fetch-depth: 0 + - name: Check co-authors + if: github.event_name == 'pull_request' + run: | + set -euo pipefail + git fetch --no-tags origin main + base=$(git merge-base origin/main HEAD) + messages=$(git log --format=%B "$base..HEAD") + messages+=$'\n'"$(jq -r '.pull_request.title, (.pull_request.body // "")' "$GITHUB_EVENT_PATH")" + if grep -Eiq '^[[:space:]]*Co-authored-by:.*(Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\])' <<<"$messages"; then + echo "::error::AI and bot identities cannot be co-authors; remove the Co-authored-by trailer." + exit 1 + fi + - name: The packages a signed build ships as id: variants run: echo "list=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .)" >> "$GITHUB_OUTPUT" @@ -173,7 +186,7 @@ jobs: 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', '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/**') }} + key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', '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/linuxfs/debian-image.env') }} - name: Build libfakeinput.so and libblsession.so (glibc aarch64) if: steps.preloads.outputs.cache-hit != 'true' @@ -195,6 +208,9 @@ jobs: 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" # Force-SSBS adapter, preloaded into a game's Wine only when the game asks for it. aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ -o "$D/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl @@ -216,14 +232,6 @@ jobs: test -f "$D/usr/local/bin/gamescope" rm gamescope.tzst fi - if [ -f tools/wlroots/release.env ]; then - . tools/wlroots/release.env - gh release download "${WLROOTS_TAG}" -R "${GITHUB_REPOSITORY}" -p wlroots.tzst -O wlroots.tzst - echo "${WLROOTS_SHA256} wlroots.tzst" | sha256sum -c - - tar --use-compress-program=unzstd -xf wlroots.tzst -C "$D" - test -f "$D/usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so" - rm wlroots.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 - @@ -262,10 +270,13 @@ jobs: done install -m644 msi-pkgs/usr/bin/msiinfo "$T/msiinfo" install -m644 msi-pkgs/usr/bin/cabextract "$T/cabextract" + # 7-Zip (the full build with its format plugin) opens installer .exe wrappers. + 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; do + 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 @@ -273,17 +284,42 @@ jobs: 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/autostart "$D/etc/xdg/labwc/autostart" - install -Dm644 tools/linuxfs/desktop/rc.xml "$D/etc/xdg/labwc/rc.xml" - install -Dm644 tools/linuxfs/desktop/panel.conf "$D/etc/xdg/lxqt/panel.conf" + 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" + # The Debian 11 image the preloads are compiled in comes from a release on this repo + # (published once by ci-debian-image.yml, pinned in tools/linuxfs/debian-image.env): the + # public registry mirrors rate-limit the shared runner addresses and failed builds on a + # busy evening. Only if that download fails is the image pulled, with retries. + - 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 debian:bullseye bash -c ' + docker run --rm -v "$PWD:/src" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c ' set -euo pipefail printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list apt-get -o Acquire::Check-Valid-Until=false update -qq @@ -347,8 +383,9 @@ jobs: 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 .) - mv pulseaudio.tzst app/src/main/assets/pulseaudio.tzst - tar --use-compress-program=unzstd -tf app/src/main/assets/pulseaudio.tzst | grep -c '\.so$' + 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 @@ -368,42 +405,40 @@ jobs: - name: Check the preloads run: | set -euo pipefail - D=app/src/main/assets/linuxfs - NEED=$(readelf -d "$D/libfakeinput.so" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p') - for bad in libstdc++.so.6 libgcc_s.so.1; do - if printf '%s\n' "$NEED" | grep -qx "$bad"; then - echo "::error::libfakeinput.so links $bad - the C++ runtime must stay static"; exit 1 - fi - done - syms() { readelf -Ws "$1" | awk '$4 == "FUNC" && $5 == "GLOBAL" {sub(/@.*/, "", $8); print $8}'; } - FAKE=$(syms "$D/libfakeinput.so") - for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do - grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; } - done - # The static C++ runtime stays private: every session process preloads this library, - # and an exported personality routine takes over other programs' unwinding (shadPS4 - # aborted in pthread_exit). - if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then - echo "::error::libfakeinput.so exports the C++ runtime"; exit 1 - fi - SESSION=$(syms "$D/libblsession.so") - for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap drmPrimeFDToHandle drmCloseBufferHandle; do - grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; } - done - # Zink's GEM_CLOSE is caught at ioctl(); an exported drmIoctl made NMS replay old frames. - if grep -qx drmIoctl <<<"$SESSION"; then - echo "::error::libblsession.so exports drmIoctl"; exit 1 - fi - SSBS=$(syms "$D/libssbs.so") - for sym in sigaction signal bsd_signal sysv_signal; do - grep -qx "$sym" <<<"$SSBS" || { echo "::error::libssbs.so does not export $sym"; exit 1; } - done - test -f "$D/usr/local/bin/droiddeck-session" - test -f "$D/usr/local/bin/droiddeck-proton-extra" - test -f "$D/usr/local/bin/droiddeck-msi-install" - for f in msiinfo cabextract libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do - test -f "$D/usr/local/lib/droiddeck-msitools/$f" || { echo "::error::droiddeck-msitools/$f missing"; exit 1; } - done + bash tools/linuxfs/check-preloads.sh app/src/main/assets/linuxfs + + # The store download engines (app/src/main/rust/stores) are Rust, built by Gradle's + # buildRustStores task through cargo-ndk. rustup and cargo are on the runner image; the Android + # target and cargo-ndk are added here. Cache = cargo registry + cargo-ndk + the crate's target + # tree, keyed on the rustc version and Cargo.lock, so a source-only change rebuilds this crate + # on top of the cached dependency objects, and a lockfile change still starts from the + # previous objects (restore-keys). + - name: Rust toolchain for the store engines (aarch64-linux-android) + id: rust + run: | + set -euo pipefail + rustup target add aarch64-linux-android + echo "rustc=$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT" + rustc -V; cargo -V + + - name: Cache cargo registry and the store engines' target + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.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') }} + restore-keys: | + stores-${{ steps.rust.outputs.rustc }}- + + - name: cargo-ndk + run: | + set -euo pipefail + command -v cargo-ndk >/dev/null || cargo install cargo-ndk --locked + cargo ndk --version - name: Cache the CMake build tree uses: actions/cache@v4 @@ -419,10 +454,46 @@ jobs: id: build env: DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }} + SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }} run: | set -o pipefail + 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 + python3 tools/release/runtime_inputs.py apk app/build/outputs/apk/release/app-release.apk + + - name: Check the store engines' library + # The exports Kotlin binds must be in the apk's libdroiddeckstores.so, or the stores fail on + # the device with an UnsatisfiedLinkError instead of here. The lockfile check is the + # reproducibility guard: cargo must not have had to re-resolve anything. + run: | + set -euo pipefail + NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}" + python3 tools/release/check_android_libraries.py app/build/outputs/apk/release/app-release.apk \ + --readelf "$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf" + git diff --stat -- app/src/main/rust/stores/Cargo.lock + 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 + # The crate's #[test] functions are pure host-side logic (manifest parsing, chunk plans, + # assembly from a cache, hashes), so a plain `cargo test` on the runner's own architecture + # runs them; the Android build above compiles none of them. Informational on this first + # run - the point is to learn whether they pass - and bounded so a hang can never hold + # the apk. Make it blocking once it is known green. + 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 + with: + name: stores-cargo-lock + path: app/src/main/rust/stores/Cargo.lock + if-no-files-found: ignore - name: Steam import and game environment tests run: python3 -m unittest discover -s tools/tests -p 'test_*.py' @@ -430,27 +501,6 @@ jobs: - name: Unit tests run: ./gradlew testReleaseUnitTest --console=plain -PndkVersion="$NDK_VERSION" - - name: Check the native dependency closure - run: | - set -euo pipefail - APK=$(find app/build/outputs/apk -name '*.apk' | head -1) - WORK=$(mktemp -d) - unzip -q "$APK" 'lib/arm64-v8a/*' -d "$WORK" - cd "$WORK/lib/arm64-v8a" - SYSTEM="libc.so libm.so libdl.so liblog.so libandroid.so libz.so libvulkan.so libstdc++.so - libGLESv2.so libEGL.so libnativewindow.so libjnigraphics.so libaaudio.so - libOpenSLES.so libmediandk.so libcamera2ndk.so libsync.so libneuralnetworks.so" - fail=0 - for so in *.so; do - for need in $(readelf -d "$so" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p'); do - [ -f "$need" ] && continue - case " $(echo $SYSTEM) " in *" $need "*) continue ;; esac - echo "::error::$so needs $need, which is neither in the apk nor a platform library" - fail=1 - done - done - exit $fail - - name: Sign with the testkey (v1 + v2 + v3) run: | set -euo pipefail diff --git a/.github/workflows/ci-debian-image.yml b/.github/workflows/ci-debian-image.yml new file mode 100644 index 0000000000..1635ed4074 --- /dev/null +++ b/.github/workflows/ci-debian-image.yml @@ -0,0 +1,55 @@ +name: Publish the CI Debian image + +# Pulls the Debian 11 image the x86 preloads build in, once, and publishes it as a release asset +# on this repo so build.yml never depends on a registry mirror's rate limit. Run it again (with a +# new tag) only to refresh the image; tools/linuxfs/debian-image.env names the one builds use. + +on: + workflow_dispatch: + inputs: + tag: + description: 'Release tag to publish to (a new -rN tag for a refresh; builds pin the one in tools/linuxfs/debian-image.env)' + required: true + default: 'ci-debian-bullseye-r2' + replace: + description: 'Overwrite the asset if the release already has one (changes its checksum: re-pin it in debian-image.env)' + type: boolean + default: false + +permissions: + contents: write + +jobs: + publish: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - name: Pull, save and publish + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ inputs.tag }} + REPLACE: ${{ inputs.replace }} + run: | + set -euo pipefail + image=public.ecr.aws/docker/library/debian:bullseye + # A published image is pinned by checksum in the build; never replace one by accident. + if [ "$REPLACE" != true ] && gh release view "$TAG" -R "$GITHUB_REPOSITORY" --json assets -q '.assets[].name' 2>/dev/null | grep -qx debian-bullseye.tar.zst; then + echo "::error::$TAG already carries debian-bullseye.tar.zst; publish to a new tag, or set replace and re-pin tools/linuxfs/debian-image.env" + exit 1 + fi + for attempt in 1 2 3 4 5 6; do + docker pull "$image" && break + [ "$attempt" -lt 6 ] || { echo "::error::could not pull $image"; exit 1; } + echo "pull attempt $attempt failed (registry busy?); retrying in $((attempt * 30)) s" + sleep $((attempt * 30)) + done + docker image inspect "$image" --format 'image id {{.Id}} created {{.Created}}' + docker save "$image" | zstd -19 -T0 -o debian-bullseye.tar.zst + sha256sum debian-bullseye.tar.zst | tee SHA256SUMS + ls -l debian-bullseye.tar.zst + if ! gh release view "$TAG" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + gh release create "$TAG" -R "$GITHUB_REPOSITORY" --title "CI Debian 11 image ($TAG)" --latest=false \ + --notes "The debian:bullseye image build.yml compiles the x86 preloads in (glibc 2.31), saved with docker save and compressed with zstd. Pulled from public.ecr.aws/docker/library/debian:bullseye on $(date -u +%Y-%m-%d); image id $(docker image inspect "$image" --format '{{.Id}}'). Pinned in tools/linuxfs/debian-image.env." + fi + gh release upload "$TAG" -R "$GITHUB_REPOSITORY" debian-bullseye.tar.zst SHA256SUMS --clobber + { echo "Published \`$TAG\`:"; echo; echo '```'; cat SHA256SUMS; echo '```'; } >> "$GITHUB_STEP_SUMMARY" diff --git a/.gitignore b/.gitignore index 71f997c628..a9e068c0d1 100644 --- a/.gitignore +++ b/.gitignore @@ -13,8 +13,12 @@ captures/ app/src/main/assets/linuxfs/ 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/libdirectaudiorelay.so +# The store download engines (app/src/main/rust/stores) are cross-compiled by Gradle into +# app/build/rustJniLibs; cargo's own build tree stays next to the crate. Neither is source. +app/src/main/rust/stores/target/ app/src/main/assets/droiddeck-esync/ # Kotlin compiler session files (build-tool state, never source). diff --git a/README.md b/README.md index e9b495d1a0..ceaef7ff73 100644 --- a/README.md +++ b/README.md @@ -15,21 +15,25 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big ## 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. +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, browses their catalogs and libraries, downloads games into the Games storage and adds each one to the Steam client as a non-Steam game, so it launches through Proton like everything else; the cog on its chip row sets which tab a store opens on and the download speed tier. Before Steam launches, you must turn off **Restrict child processes** 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. ## Community -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 session folder from `Download/DroidDeck/` so the logs come with 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. ## Build -Run `tools/build_local.sh` with Docker, Java 17, the Android SDK/NDK, and `zstd` installed. It builds the ARM64 audio sinks from PulseAudio 13.0 and packages them into the APK 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. To install the APK on an attached device, run `tools/deploy_local.sh`. +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`. + +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. + +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. ## Limits -Compatibility and performance vary by device; hardware validation is limited. Desktop compositing uses software rendering. Firefox sandboxing is reduced under proot. See the session logs in `Download/DroidDeck/` when diagnosing problems. +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. ## Credits and licence diff --git a/app/build.gradle b/app/build.gradle index 98a37d7e1e..6752f032bb 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -59,6 +59,19 @@ def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'tr def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim() // When the source was committed, for "built 3 hours ago": fixed per commit, so it costs no rebuilds. def commitTime = (gitValue(['show', '-s', '--format=%ct', 'HEAD']) ?: '0').with { it.isLong() ? it : '0' } +// The desktop package this apk installs (tools/desktop-kde/release.env): published once per tag in +// DroidDeck-Components, pinned here with its checksum like gamescope and the esync packs, so the +// desktop scripts in the apk always get the package they were made for. +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 desktopRemovalSources = new groovy.json.JsonSlurper().parse(file('src/main/assets/desktop-removal/sources.json')) +if (desktopRemovalSources.archives[desktopKde.DESKTOP_KDE_TAG] != desktopKde.DESKTOP_KDE_SHA256) { + throw new GradleException('Desktop removal inventories do not match the pinned archive') +} +if (!file('src/main/assets/desktop-removal/versions.txt').readLines().contains(desktopKde.DESKTOP_KDE_TAG)) { + throw new GradleException('Regenerate desktop removal inventories for ' + desktopKde.DESKTOP_KDE_TAG) +} // tools/release/variants.txt as "package=suffix;...", so the updater picks the apk of the package it runs as. def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines() .findAll { it.trim() && !it.startsWith('#') } @@ -88,6 +101,11 @@ android { buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\"" buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L" buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\"" + buildConfigField "String", "SGDB_API_KEY", "\"${System.getenv("SGDB_API_KEY") ?: project.findProperty("sgdbApiKey") ?: ""}\"" + buildConfigField "String", "DESKTOP_KDE_TAG", "\"${desktopKde.DESKTOP_KDE_TAG}\"" + buildConfigField "String", "DESKTOP_KDE_URL", "\"https://github.com/${desktopKde.DESKTOP_KDE_REPO}/releases/download/${desktopKde.DESKTOP_KDE_TAG}/desktop-kde.tar.zst\"" + buildConfigField "String", "DESKTOP_KDE_SHA256", "\"${desktopKde.DESKTOP_KDE_SHA256}\"" + buildConfigField "long", "DESKTOP_KDE_SIZE", "${desktopKde.DESKTOP_KDE_SIZE}L" ndk { abiFilters 'arm64-v8a' @@ -188,6 +206,76 @@ def stageSessionScripts = tasks.register('stageSessionScripts', Copy) { } tasks.named('preBuild').configure { dependsOn(stageSessionScripts) } +// Prepared audio lives under build/, so native builds never rewrite the tracked base bundle. +// Copying into one asset root also prevents an old base bundle winning a duplicate asset merge. +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(layout.buildDirectory.dir('prepared-assets')) + into(runtimeAssetsDir) +} +android.sourceSets.main.assets.setSrcDirs([runtimeAssetsDir]) +tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) } + +// Unit tests and previews remain usable without Docker. Packaging an APK requires the complete +// runtime payload prepared by the local helper or CI, with matching sources and output hashes. +def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) { + // The session scripts are re-copied into the asset tree by stageSessionScripts; with parallel + // task execution this check once hashed a file mid-copy and failed a main build. Hash only + // once the staging has finished. + mustRunAfter(stageSessionScripts, stageRuntimeAssets) + workingDir rootProject.projectDir + commandLine 'python3', 'tools/release/runtime_inputs.py', 'verify' +} +tasks.configureEach { task -> + if (task.name in ['packageDebug', 'packageRelease']) task.dependsOn(verifyRuntimeInputs) +} + +// The GOG / Epic / Amazon download engines are Rust (app/src/main/rust/stores, ported from +// Bannerlator's bl-steam-client crate). cargo-ndk cross-compiles them for arm64-v8a into the build +// directory, which is one more jniLibs source below: nothing compiled is committed, the same rule +// the preloads, proot and the DirectAudio relay follow. cargo-ndk exports the NDK clang/llvm-ar as +// the C compiler for the one C-compiling crate (ring, under rustls) - the step Bannerlator's CI +// does by hand - and reads the NDK from ANDROID_NDK_HOME, which is set to the NDK this build pins. +// -PskipRust=true builds without the library, for a checkout with no Rust toolchain: the stores +// then report themselves unavailable instead of the build failing. +def rustCrateDir = layout.projectDirectory.dir('src/main/rust/stores') +def rustJniLibsDir = layout.buildDirectory.dir('rustJniLibs') +def skipRust = (project.findProperty('skipRust') ?: 'false').toString().toBoolean() +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.files(rustCrateDir.file('Cargo.toml'), rustCrateDir.file('Cargo.lock')) + inputs.property('ndkVersion', android.ndkVersion) + if (!skipRust) inputs.property('rustToolchain', providers.exec { + environment 'PATH', "${System.getProperty('user.home')}/.cargo/bin${File.pathSeparator}${System.getenv('PATH')}" + commandLine 'rustup', 'run', 'stable', 'rustc', '-Vv' + }.standardOutput.asText) + outputs.dir(rustJniLibsDir) + workingDir rustCrateDir + // The configuration cache serialises the task, so everything it needs is resolved here, not + // in doFirst. ~/.cargo/bin is where rustup puts cargo and cargo-ndk; an IDE-launched Gradle + // does not always have it on PATH. + def cargoBin = "${System.getProperty('user.home')}/.cargo/bin" + environment 'PATH', "${cargoBin}${File.pathSeparator}${System.getenv('PATH')}" + environment 'ANDROID_NDK_HOME', android.ndkDirectory.absolutePath + environment 'CARGO_TERM_COLOR', 'never' + if (!skipRust) environment 'RUSTC', providers.exec { + commandLine 'rustup', 'which', '--toolchain', 'stable', 'rustc' + }.standardOutput.asText.get().trim() + // --platform 26 = minSdkVersion: the engines link against the API 26 libc, like the C++ code. + // Homebrew's cargo/rustc can precede rustup on macOS and use a different sysroot, despite + // rustup reporting the Android target installed. Run both through the selected toolchain. + commandLine 'rustup', 'run', 'stable', 'cargo', 'ndk', '--target', 'arm64-v8a', '--platform', '26', + '--output-dir', rustJniLibsDir.get().asFile.absolutePath, + 'build', '--release', '--locked' +} +// Skipping Rust must omit its library even if another build left a cached .so behind. +if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir) +tasks.named('preBuild').configure { dependsOn(buildRustStores) } + dependencies { // The runtime tarball is a zstd-compressed tar. implementation 'com.github.luben:zstd-jni:1.5.2-3@aar' diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7fa9d195aa..d833ca2ae8 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -8,6 +8,8 @@ + + @@ -28,6 +30,9 @@ + + @@ -127,6 +132,13 @@ android:screenOrientation="sensorLandscape" android:theme="@style/AppTheme" /> + + + + + #include #include +#include #include #include #include @@ -265,6 +266,31 @@ static std::unordered_map &ff_effects() { return *map; } +// Every fd the maps hold, readable without controller_mutex(): the hooks see each read, write, +// ioctl and poll a process makes, and almost none are on these. Set before an fd is handed out, +// cleared once no map holds it; an fd past the bitmap takes the lock once any such fd exists. +static constexpr int kWatchedFds = 1 << 16; +static constexpr int kWatchedBits = sizeof(unsigned long) * 8; +static std::atomic watched_fds[kWatchedFds / kWatchedBits]; +static std::atomic watched_beyond{false}; + +static void watch_fd(int fd) { + if (fd < 0) return; + if (fd >= kWatchedFds) watched_beyond.store(true, std::memory_order_release); + else watched_fds[fd / kWatchedBits].fetch_or(1UL << (fd % kWatchedBits), std::memory_order_release); +} + +static void unwatch_fd(int fd) { + if (fd >= 0 && fd < kWatchedFds) + watched_fds[fd / kWatchedBits].fetch_and(~(1UL << (fd % kWatchedBits)), std::memory_order_release); +} + +static bool watched(int fd) { + if (fd < 0) return false; + if (fd >= kWatchedFds) return watched_beyond.load(std::memory_order_acquire); + return (watched_fds[fd / kWatchedBits].load(std::memory_order_acquire) >> (fd % kWatchedBits)) & 1; +} + static const char *fake_hook_dir() { return config().hook_dir; } static const char *fake_udev_data_dir() { return config().udev_data_dir; } static bool fake_vibration_enabled() { return config().vibration_enabled; } @@ -301,23 +327,43 @@ namespace Logger { int log_enabled; // FAKE_EVDEV_LOG_FILE: the session's pad.log, shared by every process the library is loaded in // (the client, each game), so a pad report has the guest side in one file of the session folder. -// Opened with the raw syscall: open() is this library's own hook. -static int log_fd = -1; +// Opened with the raw syscalls (open() and close() are this library's own hooks), and only once +// there is a line to write: most processes never log one, and each open is a stop in proot on +// shared storage. +static std::atomic log_fd{-1}; +static std::atomic log_unusable{false}; +static char log_path[PATH_MAX]; static char log_name[17]; void init() { log_enabled = getenv("FAKE_EVDEV_LOG") && atoi(getenv("FAKE_EVDEV_LOG")); const char *path = getenv("FAKE_EVDEV_LOG_FILE"); - if (log_enabled && path && *path) - log_fd = static_cast(syscall(SYS_openat, AT_FDCWD, path, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0644)); + if (log_enabled && path && *path && strlen(path) < sizeof(log_path)) strcpy(log_path, path); if (prctl(PR_GET_NAME, log_name) != 0) strcpy(log_name, "?"); } +static int log_file() { + int fd = log_fd.load(std::memory_order_acquire); + if (fd >= 0 || !log_path[0] || log_unusable.load(std::memory_order_relaxed)) return fd; + fd = static_cast(syscall(SYS_openat, AT_FDCWD, log_path, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0644)); + if (fd < 0) { + log_unusable.store(true, std::memory_order_relaxed); + return -1; + } + int expected = -1; + if (!log_fd.compare_exchange_strong(expected, fd, std::memory_order_acq_rel)) { + syscall(SYS_close, fd); + fd = expected; + } + return fd; +} + void log(const char *message, ...) { if (!log_enabled) return; - if (log_fd < 0) { + int fd = log_file(); + if (fd < 0) { va_list args; va_start(args, message); vfprintf(stderr, message, args); @@ -343,7 +389,7 @@ void log(const char *message, ...) { n = sizeof(line) - 1; line[n - 1] = '\n'; } - ssize_t ignored = write(log_fd, line, n); + ssize_t ignored = write(fd, line, n); (void)ignored; } } // namespace Logger @@ -671,6 +717,7 @@ open_fake_input_ring(const char *event, int flags) { { std::lock_guard guard(controller_mutex()); controller_map()[fd] = controller; + watch_fd(fd); } Logger::log("Adding ring-backed controller, fd %d event %s slot %d\n", fd, @@ -753,20 +800,29 @@ copy_slot_ioctl_string(int op, void *argp, const char *format, int event_number) } __attribute__((visibility("hidden"))) static bool is_fake_input_fd(int fd) { + if (!watched(fd)) return false; std::lock_guard guard(controller_mutex()); return controller_map().find(fd) != controller_map().end(); } +static bool fake_pad_withdrawn(const FakeController &fake); + +// A node whose pad is gone: the app republished its ring, or the pad was switched to a type that +// is not this node (it became the Deck or the Steam Controller again, fake_pad_withdrawn). +static bool controller_gone(const FakeController &fake) { + return ring_generation(fake.ring) != fake.generation || fake_pad_withdrawn(fake); +} + __attribute__((visibility("hidden"))) static bool fake_fd_is_stale(int fd) { + if (!watched(fd)) return false; std::lock_guard guard(controller_mutex()); auto controller = controller_map().find(fd); - return controller != controller_map().end() && - ring_generation(controller->second->ring) != controller->second->generation; + return controller != controller_map().end() && controller_gone(*controller->second); } // Caller holds controller_mutex(). static bool fake_has_unread_data(const FakeController &fake) { - if (ring_generation(fake.ring) != fake.generation) + if (controller_gone(fake)) return false; // Readiness never consumes resync requests or changes the read cursor. // Do not spin a nonblocking guest on a producer's unfinished publication. @@ -789,7 +845,7 @@ static bool fake_fd_has_unread_data(int fd) { static short fake_poll_revents(const std::shared_ptr &fake, short events) { std::lock_guard guard(controller_mutex()); if (fake->closed) return POLLNVAL; - if (ring_generation(fake->ring) != fake->generation) return POLLHUP; + if (controller_gone(*fake)) return POLLHUP; short ready = events & (POLLOUT | POLLWRNORM); if ((events & (POLLIN | POLLRDNORM)) && fake_has_unread_data(*fake)) ready |= events & (POLLIN | POLLRDNORM); @@ -871,6 +927,7 @@ __attribute__((visibility("hidden"))) static int open_uinput(int flags) { writer->owner = getpid(); std::lock_guard guard(controller_mutex()); uinput_map()[fd] = writer; + watch_fd(fd); Logger::log("uinput: opened as fd %d\n", fd); return fd; } @@ -1216,6 +1273,10 @@ struct DeckHidraw { FakeInputRingHeader *ring = nullptr; size_t mapping_size = 0; uint8_t pending_feature = 0; + bool touch = false; // Steam's touch controller (below), not the Deck + bool triton = false; // The paired 2025 Steam Controller, with native BLE report IDs + bool emulated = false; // That Steam Controller made from the app's own pad (FAKE_EVDEV_TRITON_PAD) + uint8_t sony = 0; // The app's own pad as a DualShock 4 (4) or DualSense (5), else 0 }; // What the Deck has and an Xbox pad does not, after the ring's events: motion (PadMotion) and the @@ -1224,14 +1285,16 @@ struct DeckHidraw { // Absent from a ring file written without one. struct DeckImu { uint32_t magic; // IMU1 once written - uint32_t reserved; + uint32_t imu_mode; // written by this library: the client's SETTING_IMU_MODE | 0x80000000 uint64_t seq; // odd while being written int16_t accel[3]; int16_t gyro[3]; int16_t pads[4]; // left X, Y, right X, Y: -32768..32767, Y up uint16_t pressure[2]; // left, right: 0..32767 uint32_t controls; // DECK_EXTRA_* bits + uint32_t pad_type; // PAD_TYPE_* | 0x80000000, written by the app; 0 until it does }; +static_assert(offsetof(DeckImu, pad_type) == 44, "DeckImu::pad_type matches FakeInputWriter"); // DeckImu::controls (DeckControls.kt). static constexpr uint32_t DECK_EXTRA_L4 = 1, DECK_EXTRA_R4 = 2, DECK_EXTRA_L5 = 4, DECK_EXTRA_R5 = 8, DECK_EXTRA_LPAD_TOUCH = 16, @@ -1249,6 +1312,65 @@ 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"); +// Shared native Steam Controller reports. Field offsets match FakeInputWriter.java. Android writes +// the original BLE input packet; this process writes Steam's HID output report for Android to send. +// A feature read is a round trip: this process bumps get_request, Android reads the controller's +// report characteristic and answers with get_reply set to the same number. +struct TritonSharedData { + uint32_t magic; + uint32_t connected; // written by the app: the paired controller is connected and streaming + uint64_t input_seq; + uint32_t report_id; + uint32_t input_length; + uint8_t input[64]; + uint64_t output_seq; + uint32_t output_feature; + uint32_t output_length; + uint8_t output[64]; + uint64_t get_request; + uint64_t get_reply; + uint32_t get_report_id; + int32_t get_length; + uint8_t get[64]; +}; +static constexpr uint32_t TRITON_SHARED_MAGIC = 0x4e525454; +static constexpr size_t TRITON_SHARED_BLOCK_SIZE = 256; +static constexpr size_t TRITON_SHARED_OFFSET = FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE; +static_assert(offsetof(TritonSharedData, connected) == 4, "Triton connected offset"); +static_assert(offsetof(TritonSharedData, input_seq) == 8, "Triton input sequence offset"); +static_assert(offsetof(TritonSharedData, report_id) == 16, "Triton report ID offset"); +static_assert(offsetof(TritonSharedData, input) == 24, "Triton input offset"); +static_assert(offsetof(TritonSharedData, output_seq) == 88, "Triton output sequence offset"); +static_assert(offsetof(TritonSharedData, output_feature) == 96, "Triton output feature offset"); +static_assert(offsetof(TritonSharedData, output) == 104, "Triton output offset"); +static_assert(offsetof(TritonSharedData, get_request) == 168, "Triton feature request offset"); +static_assert(offsetof(TritonSharedData, get_reply) == 176, "Triton feature reply offset"); +static_assert(offsetof(TritonSharedData, get_report_id) == 184, "Triton feature report ID offset"); +static_assert(offsetof(TritonSharedData, get_length) == 188, "Triton feature length offset"); +static_assert(offsetof(TritonSharedData, get) == 192, "Triton feature data offset"); +static_assert(sizeof(TritonSharedData) <= TRITON_SHARED_BLOCK_SIZE, "Triton ring block size"); + +static constexpr const char *TRITON_HIDRAW_PATH = "/dev/hidraw18"; +static constexpr unsigned int TRITON_HIDRAW_MAJOR = 240; +static constexpr unsigned int TRITON_HIDRAW_MINOR = 18; +// The app's own pad as the wired Steam Controller: a node of its own, so a paired one keeps 18. +static constexpr const char *TRITON_PAD_HIDRAW_PATH = "/dev/hidraw19"; +static constexpr unsigned int TRITON_PAD_HIDRAW_MINOR = 19; +static constexpr int TRITON_REPORT_ID_BYTES = 1; +static constexpr int TRITON_STATE_BYTES = 45; +static constexpr int TRITON_REPORT_INTERVAL_US = 4000; +// A BLE read takes a few connection intervals; past this the controller is taken to be gone. +static constexpr int TRITON_FEATURE_TIMEOUT_MS = 500; +static constexpr const char *TRITON_NAME = "Steam Controller"; +static constexpr const char *TRITON_SERIAL = "DROIDDECKSC01"; +static const uint8_t kTritonReportDescriptor[] = { + 0x06, 0x00, 0xff, 0x09, 0x01, 0xa1, 0x01, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, + 0x85, 0x45, 0x09, 0x02, 0x95, 0x2d, 0x81, 0x02, 0x85, 0x47, 0x09, 0x03, 0x95, 0x2d, 0x81, 0x02, + 0x85, 0x80, 0x09, 0x04, 0x95, 0x09, 0x91, 0x02, 0x85, 0x81, 0x09, 0x05, 0x95, 0x07, 0x91, 0x02, + 0x85, 0x82, 0x09, 0x06, 0x95, 0x03, 0x91, 0x02, 0x85, 0x83, 0x09, 0x07, 0x95, 0x09, 0x91, 0x02, + 0x85, 0x84, 0x09, 0x08, 0x95, 0x08, 0x91, 0x02, 0x85, 0x85, 0x09, 0x09, 0x95, 0x03, 0x91, 0x02, + 0x85, 0x01, 0x09, 0x0a, 0x95, 0x3f, 0xb1, 0x02, 0xc0}; + __attribute__((visibility("hidden"))) static bool read_deck_extras(const DeckHidraw &deck, DeckExtras &out) { if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return false; const auto *imu = reinterpret_cast(reinterpret_cast(deck.ring) + @@ -1285,6 +1407,78 @@ static bool fake_deck_enabled() { return enabled == 1; } +// What the app's own pad is to the client, switchable while the session runs (the drawer's +// Controller page): the Deck (/dev/hidraw16), the wired Steam Controller (/dev/hidraw19, built from +// ring slot 0 as the Deck's reports are), or an Xbox 360 pad (its own evdev node, no HID device). +// The app writes the choice into the slot's Deck block (DeckImu::pad_type); until it has, +// FAKE_EVDEV_PAD_TYPE says what the session started with. Only the chosen device can be opened; +// the others end their streams, and the client is told through udev (pad_type_thread). +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) { + const char *env = getenv("FAKE_EVDEV_PAD_TYPE"); + type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM + : env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX + : env && !strcmp(env, "dualshock4") ? PAD_TYPE_DS4 + : env && !strcmp(env, "dualsense") ? PAD_TYPE_DUALSENSE : PAD_TYPE_DECK; + } + return static_cast(type); +} + +// Slot 0's Deck and Triton blocks, mapped once, read-only; null until the ring file has them. +__attribute__((visibility("hidden"))) static const uint8_t *ring_blocks() { + static std::atomic block{nullptr}; + static std::atomic tries{0}; + const uint8_t *mapped = block.load(std::memory_order_acquire); + if (mapped || tries.load(std::memory_order_relaxed) > 200) return mapped; + static std::mutex lock; + std::lock_guard guard(lock); + if ((mapped = block.load(std::memory_order_acquire))) return mapped; + tries.fetch_add(1, std::memory_order_relaxed); + static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); + std::string path = get_ring_path_for_slot(0); + int fd = path.empty() ? -1 : my_open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) return nullptr; + struct stat st; + void *mapping = MAP_FAILED; + const size_t size = TRITON_SHARED_OFFSET + TRITON_SHARED_BLOCK_SIZE; + if (fstat(fd, &st) == 0 && static_cast(st.st_size) >= size) + mapping = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0); + syscall(SYS_close, fd); + if (mapping == MAP_FAILED) return nullptr; + mapped = static_cast(mapping); + block.store(mapped, std::memory_order_release); + return mapped; +} + +// The paired Bluetooth controller is offered only while the app has it connected: Steam asks a +// device it is offered for its info, and one that never answers holds up every other controller. +__attribute__((visibility("hidden"))) static bool triton_connected() { + const uint8_t *blocks = ring_blocks(); + if (!blocks) return false; + const auto *shared = reinterpret_cast(blocks + TRITON_SHARED_OFFSET); + return __atomic_load_n(&shared->magic, __ATOMIC_ACQUIRE) == TRITON_SHARED_MAGIC && + __atomic_load_n(&shared->connected, __ATOMIC_ACQUIRE) != 0; +} + +__attribute__((visibility("hidden"))) static uint32_t live_pad_type() { + const uint8_t *blocks = ring_blocks(); + const DeckImu *imu = blocks ? reinterpret_cast(blocks + FAKE_INPUT_RING_SIZE) : nullptr; + uint32_t value = imu ? __atomic_load_n(&imu->pad_type, __ATOMIC_ACQUIRE) : 0; + return value & PAD_TYPE_SET ? value & 0xff : session_pad_type(); +} + +static bool fake_triton_enabled() { + static int enabled = -1; + if (enabled < 0) + enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0; + return enabled == 1; +} + // The Deck is the client's alone: a game that found it would have the pad twice, once through it // and once through Steam Input's virtual pad. __attribute__((visibility("hidden"))) static bool process_is_steam_client() { @@ -1312,16 +1506,49 @@ __attribute__((constructor)) static void log_client_start() { } __attribute__((visibility("hidden"))) static bool is_deck_hidraw_path(const char *pathname) { - return pathname && fake_deck_enabled() && !strcmp(pathname, DECK_HIDRAW_PATH); + return pathname && fake_deck_enabled() && !strcmp(pathname, DECK_HIDRAW_PATH) && live_pad_type() == PAD_TYPE_DECK; } -// The app's own pads are the Deck now; their evdev nodes are withdrawn from everyone. +// The app's own pad as a PlayStation controller: /dev/hidraw20 (DualShock 4) or /dev/hidraw21 +// (DualSense), USB devices of their own in SteamDeckPad's sysfs. Returns 4 or 5, or 0. +static constexpr const char *DS4_HIDRAW_PATH = "/dev/hidraw20"; +static constexpr const char *DUALSENSE_HIDRAW_PATH = "/dev/hidraw21"; +static constexpr unsigned int DS4_HIDRAW_MINOR = 20, DUALSENSE_HIDRAW_MINOR = 21; + +__attribute__((visibility("hidden"))) static int sony_pad_path(const char *pathname) { + if (!pathname || !fake_deck_enabled() || strncmp(pathname, "/dev/hidraw2", 12)) return 0; + if (!strcmp(pathname, DS4_HIDRAW_PATH)) return live_pad_type() == PAD_TYPE_DS4 ? 4 : 0; + if (!strcmp(pathname, DUALSENSE_HIDRAW_PATH)) return live_pad_type() == PAD_TYPE_DUALSENSE ? 5 : 0; + return 0; +} + +__attribute__((visibility("hidden"))) static bool is_triton_pad_path(const char *pathname) { + return pathname && fake_deck_enabled() && !strcmp(pathname, TRITON_PAD_HIDRAW_PATH) && + live_pad_type() == PAD_TYPE_STEAM; +} + +__attribute__((visibility("hidden"))) static bool is_triton_hidraw_path(const char *pathname) { + return pathname && fake_triton_enabled() && !strcmp(pathname, TRITON_HIDRAW_PATH) && triton_connected(); +} + +// The app's first pad is the Deck now: its evdev node is withdrawn from everyone. Further players' +// pads are left to the client alone, which hands them to games through Steam Input. __attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const char *pathname) { if (!fake_deck_enabled() || !pathname || strncmp(pathname, "/dev/input/", 11)) return false; + // As an Xbox 360 pad it is its own evdev node again, for the client and games alike. + if (live_pad_type() == PAD_TYPE_XBOX) return false; const char *event = strrchr(pathname, '/') + 1; if (strncmp(event, "event", 5) && strncmp(event, "js", 2)) return false; int number = get_event_number(event); - return number >= 0 && number < UINPUT_EVENT_BASE; + if (number < 0 || number >= UINPUT_EVENT_BASE) return false; + return number == 0 || !process_is_steam_client(); +} + +static bool fake_pad_withdrawn(const FakeController &fake) { + if (fake.uinput || !fake.event) return false; + char path[64]; + snprintf(path, sizeof(path), "/dev/input/%s", fake.event); + return is_withdrawn_pad_path(path); } static inline void put16(uint8_t *at, int value) { @@ -1395,7 +1622,8 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg) uint32_t buttons = 0; int32_t axes[8] = {}; DeckExtras extras; - for (;;) { + // Switched to another type, the stream ends: the client's read fails and it lets the Deck go. + while (live_pad_type() == PAD_TYPE_DECK) { if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) { buttons = snap.buttons; memcpy(axes, snap.axes, sizeof(axes)); @@ -1416,18 +1644,151 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg) return nullptr; } -__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { +// ---- The pad as a PlayStation controller ---- +// +// The DualShock 4 (054c:09cc) and DualSense (054c:0ce6) as they are on USB, read by the client's +// own PlayStation drivers (SDL's hidapi ps4/ps5 are the reference): input report 1 every 4 ms, +// the feature reports a driver reads at start answered here (calibration, serial, firmware), and +// output reports' rumble on the handheld's motor. Built from the same ring as the Deck's report: +// sticks, triggers, buttons, motion (in the units the calibration below declares), and the +// touchpad from the Deck controls' two trackpads, the left one on its left half and the right one +// on its right half, either's click as the touchpad's. +static constexpr int SONY_REPORT_BYTES = 64; +static constexpr int SONY_TOUCH_WIDTH = 1920; +static constexpr int SONY_TOUCH_HEIGHT_DS4 = 942, SONY_TOUCH_HEIGHT_DUALSENSE = 1080; +static constexpr const uint8_t SONY_MAC[6] = {0x5e, 0x43, 0x4b, 0x44, 0x44, 0x02}; + +struct SonyTouch { + bool down[2] = {}; + uint8_t id[2] = {}; + uint8_t next_id = 0; +}; + +// One finger per trackpad: Deck pads are -32768..32767 with Y up; the touchpad counts from its top +// left, 12 bits per axis. +__attribute__((visibility("hidden"))) static void put_sony_touch(uint8_t *at, SonyTouch &touch, int side, + bool down, int16_t x, int16_t y, int height) { + if (down && !touch.down[side]) touch.id[side] = touch.next_id++ & 0x7f; + touch.down[side] = down; + int half = SONY_TOUCH_WIDTH / 2; + int px = side * half + (static_cast(x) + 32768) * (half - 1) / 65535; + int py = (32767 - static_cast(y)) * (height - 1) / 65535; + at[0] = static_cast(touch.id[side] | (down ? 0 : 0x80)); + at[1] = static_cast(px & 0xff); + at[2] = static_cast(((px >> 8) & 0x0f) | ((py & 0x0f) << 4)); + at[3] = static_cast(py >> 4); +} + +__attribute__((visibility("hidden"))) static void +build_sony_report(uint8_t *report, uint8_t model, uint32_t packet, uint32_t buttons, const int32_t *axes, + const DeckExtras &extras, SonyTouch &touch) { + memset(report, 0, SONY_REPORT_BYTES); + report[0] = 0x01; + uint8_t *p = report + 1; + auto stick = [](int32_t value) { return static_cast(std::max(0, std::min(255, (value + 32768) >> 8))); }; + p[0] = stick(axes[0]); + p[1] = stick(axes[1]); // evdev and the PlayStation pads both count Y downwards + p[2] = stick(axes[2]); + p[3] = stick(axes[3]); + int32_t hat_x = axes[6], hat_y = axes[7]; + static const uint8_t kHat[3][3] = {{7, 0, 1}, {6, 8, 2}, {5, 4, 3}}; // [y+1][x+1] + uint8_t hat = kHat[(hat_y > 0) - (hat_y < 0) + 1][(hat_x > 0) - (hat_x < 0) + 1]; + // Snapshot order (kButtonBits): A B X Y L1 R1 View Menu L3 R3 Steam. + uint8_t face = (buttons & 4 ? 0x10 : 0) | (buttons & 1 ? 0x20 : 0) | (buttons & 2 ? 0x40 : 0) | (buttons & 8 ? 0x80 : 0); + uint8_t shoulders = (buttons & 16 ? 0x01 : 0) | (buttons & 32 ? 0x02 : 0) | (axes[5] > 0 ? 0x04 : 0) | + (axes[4] > 0 ? 0x08 : 0) | (buttons & 64 ? 0x10 : 0) | (buttons & 128 ? 0x20 : 0) | + (buttons & 256 ? 0x40 : 0) | (buttons & 512 ? 0x80 : 0); + bool click = extras.controls & (DECK_EXTRA_LPAD_CLICK | DECK_EXTRA_RPAD_CLICK); + uint8_t system = (buttons & 1024 ? 0x01 : 0) | (click ? 0x02 : 0); + uint8_t left_trigger = static_cast(std::max(0, std::min(255, axes[5]))); + uint8_t right_trigger = static_cast(std::max(0, std::min(255, axes[4]))); + // Motion: the Deck block's gyro is 2000 dps and its accel 2 g over 16 bits; the calibration + // reports declare 16 units per degree/s and 8192 per g, and the axes are the Deck's reordered as + // SDL reads both (Deck X, Z, -Y). + int16_t gyro[3] = {extras.gyro[0], extras.gyro[2], static_cast(-extras.gyro[1])}; + int16_t accel[3] = {static_cast(extras.accel[0] / 2), static_cast(extras.accel[2] / 2), + static_cast(-extras.accel[1] / 2)}; + bool left = extras.controls & DECK_EXTRA_LPAD_TOUCH, right = extras.controls & DECK_EXTRA_RPAD_TOUCH; + if (model == 4) { + p[4] = static_cast(hat | face); + p[5] = shoulders; + p[6] = static_cast(system | ((packet & 0x3f) << 2)); + p[7] = left_trigger; + p[8] = right_trigger; + put16(p + 9, static_cast(packet * 750)); // 5.33 us ticks: 4 ms + for (int i = 0; i < 3; i++) { + put16(p + 12 + i * 2, gyro[i]); + put16(p + 18 + i * 2, accel[i]); + } + p[29] = 0x1b; // on the cable, full + p[32] = 1; // one touch packet + p[33] = static_cast(packet); + put_sony_touch(p + 34, touch, 0, left, extras.pads[0], extras.pads[1], SONY_TOUCH_HEIGHT_DS4); + put_sony_touch(p + 38, touch, 1, right, extras.pads[2], extras.pads[3], SONY_TOUCH_HEIGHT_DS4); + } else { + p[4] = left_trigger; + p[5] = right_trigger; + p[6] = static_cast(packet); + p[7] = static_cast(hat | face); + p[8] = shoulders; + p[9] = system; + put32(p + 11, packet); + for (int i = 0; i < 3; i++) { + put16(p + 15 + i * 2, gyro[i]); + put16(p + 21 + i * 2, accel[i]); + } + put32(p + 27, packet * 12000); // 0.33 us ticks: 4 ms + put_sony_touch(p + 32, touch, 0, left, extras.pads[0], extras.pads[1], SONY_TOUCH_HEIGHT_DUALSENSE); + put_sony_touch(p + 36, touch, 1, right, extras.pads[2], extras.pads[3], SONY_TOUCH_HEIGHT_DUALSENSE); + p[52] = 0x2a; // charging, full + p[53] = 0x08; // USB + } +} + +__attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg) { + auto *holder = static_cast *>(arg); + std::shared_ptr self = *holder; + delete holder; + uint32_t type = self->sony == 4 ? PAD_TYPE_DS4 : PAD_TYPE_DUALSENSE; + uint32_t packet = 0; + SnapshotState snap; + uint32_t buttons = 0; + int32_t axes[8] = {}; + DeckExtras extras; + SonyTouch touch; + // Switched to another type, the stream ends, as unplugging the controller would. + while (live_pad_type() == type) { + if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) { + buttons = snap.buttons; + memcpy(axes, snap.axes, sizeof(axes)); + } + read_deck_extras(*self, extras); + uint8_t report[SONY_REPORT_BYTES]; + build_sony_report(report, self->sony, ++packet, buttons, axes, extras, touch); + if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 && + errno != EAGAIN && errno != EWOULDBLOCK) + break; + struct timespec interval = {0, DECK_REPORT_INTERVAL_US * 1000L}; + nanosleep(&interval, nullptr); + } + syscall(SYS_close, self->peer); + munmap(self->ring, self->mapping_size); + return nullptr; +} + +__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) { + const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH; static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); if (!process_is_steam_client()) { // Only the client reads the Deck; a game sees Steam Input's virtual pad instead. - Logger::log("deck: %s refused: not the Steam client\n", DECK_HIDRAW_PATH); + Logger::log("deck: %s refused: not the Steam client\n", path); errno = ENOENT; return -1; } std::string ring_path = get_ring_path_for_slot(0); int ring_fd = ring_path.empty() ? -1 : my_open(ring_path.c_str(), O_RDONLY | O_CLOEXEC); if (ring_fd < 0) { - Logger::log("deck: %s refused: ring %s not openable (%s)\n", DECK_HIDRAW_PATH, + Logger::log("deck: %s refused: ring %s not openable (%s)\n", path, ring_path.empty() ? "(none configured)" : ring_path.c_str(), strerror(errno)); errno = ENODEV; return -1; @@ -1441,7 +1802,7 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { void *mapping = mmap(nullptr, mapping_size, PROT_READ, MAP_SHARED, ring_fd, 0); syscall(SYS_close, ring_fd); if (mapping == MAP_FAILED || !ring_header_is_valid(static_cast(mapping))) { - Logger::log("deck: %s refused: ring %s %s\n", DECK_HIDRAW_PATH, ring_path.c_str(), + Logger::log("deck: %s refused: ring %s %s\n", path, ring_path.c_str(), mapping == MAP_FAILED ? "could not be mapped" : "has no valid header"); if (mapping != MAP_FAILED) munmap(mapping, mapping_size); errno = ENODEV; @@ -1449,7 +1810,7 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { } int pair[2]; if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, pair) < 0) { - Logger::log("deck: %s refused: socketpair failed (%s)\n", DECK_HIDRAW_PATH, strerror(errno)); + Logger::log("deck: %s refused: socketpair failed (%s)\n", path, strerror(errno)); munmap(mapping, mapping_size); return -1; } @@ -1462,16 +1823,19 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { deck->peer = pair[1]; deck->ring = static_cast(mapping); deck->mapping_size = mapping_size; + deck->sony = sony; { std::lock_guard guard(controller_mutex()); deck_map()[pair[0]] = deck; + watch_fd(pair[0]); } pthread_t thread; auto *arg = new std::shared_ptr(deck); - if (pthread_create(&thread, nullptr, deck_report_thread, arg) != 0) { + if (pthread_create(&thread, nullptr, sony ? sony_report_thread : deck_report_thread, arg) != 0) { delete arg; std::lock_guard guard(controller_mutex()); deck_map().erase(pair[0]); + unwatch_fd(pair[0]); syscall(SYS_close, pair[0]); syscall(SYS_close, pair[1]); munmap(mapping, mapping_size); @@ -1479,10 +1843,652 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { return -1; } pthread_detach(thread); - Logger::log("deck: %s opened as fd %d\n", DECK_HIDRAW_PATH, pair[0]); + Logger::log("deck: %s opened as fd %d%s\n", path, pair[0], + sony == 4 ? " (a DualShock 4)" : sony == 5 ? " (a DualSense)" : ""); return pair[0]; } +__attribute__((visibility("hidden"))) static bool read_triton_state(const DeckHidraw &triton, uint8_t &report_id, + uint8_t *report, size_t &length) { + if (triton.mapping_size < TRITON_SHARED_OFFSET + TRITON_SHARED_BLOCK_SIZE) return false; + const auto *shared = reinterpret_cast(reinterpret_cast(triton.ring) + + TRITON_SHARED_OFFSET); + for (int attempt = 0; attempt < 8; attempt++) { + uint64_t seq = __atomic_load_n(&shared->input_seq, __ATOMIC_ACQUIRE); + if (seq & 1) continue; + if (__atomic_load_n(&shared->magic, __ATOMIC_RELAXED) != TRITON_SHARED_MAGIC) return false; + uint32_t id = __atomic_load_n(&shared->report_id, __ATOMIC_RELAXED); + uint32_t size = __atomic_load_n(&shared->input_length, __ATOMIC_RELAXED); + if (id > 0xff || size > sizeof(shared->input)) return false; + if (size) memcpy(report, shared->input, size); + __atomic_thread_fence(__ATOMIC_ACQUIRE); + if (seq == __atomic_load_n(&shared->input_seq, __ATOMIC_RELAXED)) { + report_id = size ? static_cast(id) : 0x45; + length = size ? size : TRITON_STATE_BYTES; + if (!size) memset(report, 0, length); + return true; + } + } + return false; +} + +__attribute__((visibility("hidden"))) static void *triton_report_thread(void *arg) { + auto *holder = static_cast *>(arg); + std::shared_ptr self = *holder; + delete holder; + uint8_t report[TRITON_REPORT_ID_BYTES + 64] = {}; + uint8_t report_id = 0x45; + size_t length = TRITON_STATE_BYTES; + // A disconnect ends the stream, as unplugging the controller would. + while (triton_connected()) { + if (read_triton_state(*self, report_id, report + 1, length)) { + report[0] = report_id; + if (send(self->peer, report, length + 1, MSG_DONTWAIT | MSG_NOSIGNAL) < 0 && + errno != EAGAIN && errno != EWOULDBLOCK) + break; + } + struct timespec interval = {0, TRITON_REPORT_INTERVAL_US * 1000L}; + nanosleep(&interval, nullptr); + } + syscall(SYS_close, self->peer); + munmap(self->ring, self->mapping_size); + return nullptr; +} + +// Button bits of the Triton state report (SDL, SDL_hidapi_steam_triton.c). SDL reads MENU as Back +// and VIEW as Start, the reverse of the Deck's names. +static constexpr uint32_t TRITON_A = 0x00000001, TRITON_B = 0x00000002, TRITON_X = 0x00000004, + TRITON_Y = 0x00000008, TRITON_QAM = 0x00000010, TRITON_R3 = 0x00000020, + TRITON_VIEW = 0x00000040, TRITON_R4 = 0x00000080, TRITON_R5 = 0x00000100, + TRITON_R = 0x00000200, TRITON_DOWN = 0x00000400, TRITON_RIGHT = 0x00000800, + TRITON_LEFT = 0x00001000, TRITON_UP = 0x00002000, TRITON_MENU = 0x00004000, + TRITON_L3 = 0x00008000, TRITON_STEAM = 0x00010000, TRITON_L4 = 0x00020000, + TRITON_L5 = 0x00040000, TRITON_L = 0x00080000, + TRITON_RSTICK_TOUCH = 0x00100000, TRITON_RPAD_TOUCH = 0x00200000, + TRITON_RPAD_CLICK = 0x00400000, TRITON_RTRIGGER_CLICK = 0x00800000, + TRITON_LSTICK_TOUCH = 0x01000000, TRITON_LPAD_TOUCH = 0x02000000, + TRITON_LPAD_CLICK = 0x04000000, TRITON_LTRIGGER_CLICK = 0x08000000, + TRITON_RGRIP_TOUCH = 0x10000000, TRITON_LGRIP_TOUCH = 0x20000000; +// The pad is built in, so it is the wired controller: 28de:1302 on USB, state report 0x42 (the +// same layout as the Bluetooth 0x45), where the paired one is 28de:1303 on Bluetooth. +static constexpr uint8_t TRITON_STATE_WIRED = 0x42; +static constexpr int16_t TRITON_WIRED_PRODUCT = 0x1302; +// A stick counts as touched once it leaves its centre: the pad has no capacitive caps to ask. +static constexpr int32_t TRITON_STICK_TOUCH = 2000; + +// The Triton BLE state report (SDL, controller_structs.h: TritonMTUNoQuat_t) from the ring's +// snapshot and the Deck block, which already hold the trackpads, back buttons and motion in the +// units both controllers share. A handheld is held whenever it is played, so both grips read as +// touched: Steam's grip-sense activators (gyro while held, say) then simply stay on. +__attribute__((visibility("hidden"))) static void +build_triton_report(uint8_t *report, uint32_t packet, uint32_t buttons, const int32_t *axes, + const DeckExtras &extras) { + memset(report, 0, TRITON_STATE_BYTES); + report[0] = static_cast(packet); + static const uint32_t kButtonBits[11] = {TRITON_A, TRITON_B, TRITON_X, TRITON_Y, + TRITON_L, TRITON_R, TRITON_MENU, TRITON_VIEW, + TRITON_L3, TRITON_R3, TRITON_STEAM}; + uint32_t bits = TRITON_LGRIP_TOUCH | TRITON_RGRIP_TOUCH; + for (int i = 0; i < 11; i++) + if (buttons & (1u << i)) bits |= kButtonBits[i]; + if (buttons & SNAPSHOT_QAM_BIT) bits |= TRITON_QAM; + if (axes[7] < 0) bits |= TRITON_UP; + if (axes[7] > 0) bits |= TRITON_DOWN; + if (axes[6] < 0) bits |= TRITON_LEFT; + if (axes[6] > 0) bits |= TRITON_RIGHT; + int32_t left_trigger = axes[5], right_trigger = axes[4]; // ABS_BRAKE, ABS_GAS: 0..255 + if (left_trigger >= 250) bits |= TRITON_LTRIGGER_CLICK; + if (right_trigger >= 250) bits |= TRITON_RTRIGGER_CLICK; + if (abs(axes[0]) > TRITON_STICK_TOUCH || abs(axes[1]) > TRITON_STICK_TOUCH) bits |= TRITON_LSTICK_TOUCH; + if (abs(axes[2]) > TRITON_STICK_TOUCH || abs(axes[3]) > TRITON_STICK_TOUCH) bits |= TRITON_RSTICK_TOUCH; + uint32_t controls = extras.controls; + if (controls & DECK_EXTRA_L4) bits |= TRITON_L4; + if (controls & DECK_EXTRA_R4) bits |= TRITON_R4; + if (controls & DECK_EXTRA_L5) bits |= TRITON_L5; + if (controls & DECK_EXTRA_R5) bits |= TRITON_R5; + if (controls & DECK_EXTRA_LPAD_TOUCH) bits |= TRITON_LPAD_TOUCH; + if (controls & DECK_EXTRA_RPAD_TOUCH) bits |= TRITON_RPAD_TOUCH; + if (controls & DECK_EXTRA_LPAD_CLICK) bits |= TRITON_LPAD_CLICK; + if (controls & DECK_EXTRA_RPAD_CLICK) bits |= TRITON_RPAD_CLICK; + put32(report + 1, bits); + put16(report + 5, std::min(32767, left_trigger * 32767 / 255)); + put16(report + 7, std::min(32767, right_trigger * 32767 / 255)); + auto stick = [](int32_t value) { return std::max(-32767, std::min(32767, value)); }; + put16(report + 9, stick(axes[0])); + put16(report + 11, stick(-axes[1])); + put16(report + 13, stick(axes[2])); + put16(report + 15, stick(-axes[3])); + put16(report + 17, extras.pads[0]); + put16(report + 19, extras.pads[1]); + put16(report + 21, extras.pressure[0]); + put16(report + 23, extras.pads[2]); + put16(report + 25, extras.pads[3]); + put16(report + 27, extras.pressure[1]); + put32(report + 29, packet * TRITON_REPORT_INTERVAL_US); // IMU timestamp, microseconds + for (int i = 0; i < 3; i++) { + put16(report + 33 + i * 2, extras.accel[i]); + put16(report + 39 + i * 2, extras.gyro[i]); + } +} + +__attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg) { + auto *holder = static_cast *>(arg); + std::shared_ptr self = *holder; + delete holder; + uint32_t packet = 0; + SnapshotState snap; + uint32_t buttons = 0; + int32_t axes[8] = {}; + DeckExtras extras; + while (live_pad_type() == PAD_TYPE_STEAM) { + if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) { + buttons = snap.buttons; + memcpy(axes, snap.axes, sizeof(axes)); + } + read_deck_extras(*self, extras); + uint8_t report[TRITON_REPORT_ID_BYTES + TRITON_STATE_BYTES]; + report[0] = TRITON_STATE_WIRED; + build_triton_report(report + 1, ++packet, buttons, axes, extras); + if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 && + errno != EAGAIN && errno != EWOULDBLOCK) + break; + struct timespec interval = {0, TRITON_REPORT_INTERVAL_US * 1000L}; + nanosleep(&interval, nullptr); + } + syscall(SYS_close, self->peer); + munmap(self->ring, self->mapping_size); + return nullptr; +} + +__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) { + static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); + if (!process_is_steam_client()) { + errno = ENOENT; + return -1; + } + std::string ring_path = get_ring_path_for_slot(0); + int ring_fd = ring_path.empty() ? -1 : my_open(ring_path.c_str(), O_RDWR | O_CLOEXEC); + if (ring_fd < 0) { + Logger::log("triton: %s refused: ring %s not openable (%s)\n", TRITON_HIDRAW_PATH, + ring_path.empty() ? "(none configured)" : ring_path.c_str(), strerror(errno)); + errno = ENODEV; + return -1; + } + struct stat ring_stat; + const size_t mapping_size = TRITON_SHARED_OFFSET + TRITON_SHARED_BLOCK_SIZE; + if (fstat(ring_fd, &ring_stat) < 0 || static_cast(ring_stat.st_size) < mapping_size) { + syscall(SYS_close, ring_fd); + errno = ENODEV; + return -1; + } + void *mapping = mmap(nullptr, mapping_size, PROT_READ | PROT_WRITE, MAP_SHARED, ring_fd, 0); + syscall(SYS_close, ring_fd); + if (mapping == MAP_FAILED || !ring_header_is_valid(static_cast(mapping)) || + reinterpret_cast(static_cast(mapping) + TRITON_SHARED_OFFSET)->magic != TRITON_SHARED_MAGIC) { + if (mapping != MAP_FAILED) munmap(mapping, mapping_size); + errno = ENODEV; + return -1; + } + int pair[2]; + if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, pair) < 0) { + munmap(mapping, mapping_size); + return -1; + } + int buffer = (TRITON_STATE_BYTES + TRITON_REPORT_ID_BYTES) * 4; + setsockopt(pair[1], SOL_SOCKET, SO_SNDBUF, &buffer, sizeof(buffer)); + if (!(flags & O_CLOEXEC)) fcntl(pair[0], F_SETFD, 0); + if (flags & O_NONBLOCK) fcntl(pair[0], F_SETFL, fcntl(pair[0], F_GETFL) | O_NONBLOCK); + auto triton = std::make_shared(); + triton->peer = pair[1]; + triton->ring = static_cast(mapping); + triton->mapping_size = mapping_size; + triton->triton = true; + triton->emulated = emulated; + { + std::lock_guard guard(controller_mutex()); + deck_map()[pair[0]] = triton; + watch_fd(pair[0]); + } + pthread_t thread; + auto *thread_arg = new std::shared_ptr(triton); + if (pthread_create(&thread, nullptr, triton->emulated ? triton_pad_thread : triton_report_thread, thread_arg) != 0) { + delete thread_arg; + std::lock_guard guard(controller_mutex()); + deck_map().erase(pair[0]); + unwatch_fd(pair[0]); + syscall(SYS_close, pair[0]); + syscall(SYS_close, pair[1]); + munmap(mapping, mapping_size); + errno = ENOMEM; + return -1; + } + pthread_detach(thread); + Logger::log("triton: %s opened as fd %d (%s)\n", emulated ? TRITON_PAD_HIDRAW_PATH : TRITON_HIDRAW_PATH, pair[0], + emulated ? "28de:1302, the app's pad" : "28de:1303"); + return pair[0]; +} + + +// ---- Steam's touch controller ---- +// +// docs/development/steam-touch-controller.md. Steam builds its touch controller (Steam Input's +// Mobile Touch type, the one Steam Link's on-screen controls are) for any HID device with the ids +// 0000:11fb. With FAKE_TOUCHCTL_RING set, the client is offered one as /dev/hidraw17 beside the +// Deck, its sysfs written by the app (SteamDeckPad.kt). The app draws the controls; this side only +// carries the device's traffic through the file FAKE_TOUCHCTL_RING names, which both map: +// +// - the app writes the 40-byte input report (under a seqlock), whether the device is plugged in, +// and the battery level; +// - this side writes what the client tells the device: the app and action set it is on (output +// report 4), the action set layers added and removed (5, 6), rumble (1, also passed to the app's +// vibration like any pad's) and the setting report (3), and how many readers have it open. +// +// Plugged in and out by the app (while its controls are up and no physical pad is in use), as +// Steam Link withdraws its touch controls: an unplugged device ends its open stream, refuses new +// opens, and a udev event (libblsession's stand-in monitor, udevmon.c) tells the client's HID +// discovery either way. Only the client is offered it; a game reads Steam Input's virtual pad. +static constexpr const char *TOUCH_HIDRAW_PATH = "/dev/hidraw17"; +static constexpr unsigned int TOUCH_HIDRAW_MINOR = 17; +static constexpr int TOUCH_REPORT_BYTES = 40; +static constexpr int TOUCH_REPORT_INTERVAL_US = 8000; +static constexpr const char *TOUCH_NAME = "Mobile Touch Control"; +static constexpr const char *TOUCH_SERIAL = "DROIDDECK0001"; +static constexpr const char *TOUCH_DEVPATH = "/devices/droiddeck/usb2/2-1:1.0/0003:0000:11FB.0002/hidraw/hidraw17"; +// Generic Desktop / Game Pad: for a vendor id that is not Valve's the client opens only a device +// with a gamepad usage. One 40-byte input report, one 64-byte output and one 64-byte feature +// report, no report ids. Must match SteamDeckPad.kt. +static const uint8_t kTouchReportDescriptor[] = { + 0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, + 0x09, 0x02, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x28, 0x81, 0x02, + 0x09, 0x03, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, + 0x09, 0x04, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0xb1, 0x02, 0xc0}; + +// The shared file. Must match SteamTouchDevice.kt. +struct TouchRingFile { + uint32_t magic; // TCH1 + uint32_t version; + uint64_t report_seq; // odd while the app writes report + uint8_t report[TOUCH_REPORT_BYTES]; + uint32_t plugged; + uint32_t battery; // percent + // Written here. + uint64_t state_seq; // odd while being written + uint32_t opened; + uint32_t appid; + uint32_t action_set; + uint32_t layer_count; + uint32_t layers[8]; + uint32_t rumble_seq; + uint16_t rumble_low; + uint16_t rumble_high; + uint32_t rumble_ms; + uint32_t setting30; + uint32_t action_seq; +}; +static constexpr uint32_t TOUCH_RING_MAGIC = 0x31484354; +static constexpr size_t TOUCH_RING_SIZE = 256; +static_assert(offsetof(TouchRingFile, report) == 16, "TouchRingFile layout"); +static_assert(offsetof(TouchRingFile, plugged) == 56, "TouchRingFile layout"); +static_assert(offsetof(TouchRingFile, state_seq) == 64, "TouchRingFile layout"); +static_assert(offsetof(TouchRingFile, layers) == 88, "TouchRingFile layout"); +static_assert(offsetof(TouchRingFile, rumble_seq) == 120, "TouchRingFile layout"); +static_assert(offsetof(TouchRingFile, action_seq) == 136, "TouchRingFile layout"); +static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout"); + +__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() { + static TouchRingFile *ring = nullptr; + static std::once_flag once; + std::call_once(once, [] { + const char *path = getenv("FAKE_TOUCHCTL_RING"); + if (!path || !*path || !fake_deck_enabled()) return; + static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); + int fd = my_open(path, O_RDWR | O_CLOEXEC); + if (fd < 0) { + Logger::log("touch: %s not openable (%s)\n", path, strerror(errno)); + return; + } + void *mapping = mmap(nullptr, TOUCH_RING_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + syscall(SYS_close, fd); + if (mapping == MAP_FAILED || static_cast(mapping)->magic != TOUCH_RING_MAGIC) { + Logger::log("touch: %s %s\n", path, mapping == MAP_FAILED ? "could not be mapped" : "has no valid header"); + if (mapping != MAP_FAILED) munmap(mapping, TOUCH_RING_SIZE); + return; + } + ring = static_cast(mapping); + }); + return ring; +} + +__attribute__((visibility("hidden"))) static bool touch_plugged() { + TouchRingFile *ring = touch_ring(); + return ring && __atomic_load_n(&ring->plugged, __ATOMIC_ACQUIRE) != 0; +} + +__attribute__((visibility("hidden"))) static bool is_touch_hidraw_path(const char *pathname) { + return pathname && !strcmp(pathname, TOUCH_HIDRAW_PATH) && process_is_steam_client() && touch_ring(); +} + +// The state the client gave the device, written under the ring's seqlock. +template +__attribute__((visibility("hidden"))) static void touch_state(F &&write) { + TouchRingFile *ring = touch_ring(); + if (!ring) return; + static std::mutex mutex; + std::lock_guard guard(mutex); + __atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL); + write(*ring); + __atomic_fetch_add(&ring->state_seq, 1, __ATOMIC_ACQ_REL); +} + +static inline uint32_t get32(const uint8_t *at) { + return static_cast(at[0]) | static_cast(at[1]) << 8 | static_cast(at[2]) << 16 | + static_cast(at[3]) << 24; +} + +// An output report from the client (Steam Link's CVirtualController::HandleFeatureReports): the +// type, then its fields. +__attribute__((visibility("hidden"))) static void touch_output(const uint8_t *data, size_t size) { + if (size < 9) return; + static std::atomic seen[8]; + uint8_t type = data[0]; + unsigned n = type < 8 ? ++seen[type] : 0; + if (n && (n & (n - 1)) == 0) + Logger::log("touch: output report %u (x%u): app %u, %u\n", type, n, get32(data + 1), get32(data + 5)); + switch (type) { + case 1: { // rumble: low, high, duration + uint16_t low = data[1] | data[2] << 8, high = data[3] | data[4] << 8; + uint32_t ms = get32(data + 5); + touch_state([&](TouchRingFile &r) { + r.rumble_low = low; + r.rumble_high = high; + r.rumble_ms = ms; + r.rumble_seq++; + }); + send_vibration(low, high, static_cast(std::min(ms, 0xffff)), 0); + break; + } + case 3: // a setting: 0x30 and a value + if (data[1] == 0x30) touch_state([&](TouchRingFile &r) { r.setting30 = data[2] | data[3] << 8; }); + break; + case 4: // the app and its action set + touch_state([&](TouchRingFile &r) { + r.appid = get32(data + 1); + r.action_set = get32(data + 5); + r.layer_count = 0; + r.action_seq++; + }); + break; + case 5: // a layer added to the app's action set + case 6: // and removed + touch_state([&](TouchRingFile &r) { + uint32_t layer = get32(data + 5); + uint32_t count = std::min(r.layer_count, 8); + uint32_t kept = 0; + for (uint32_t i = 0; i < count; i++) + if (r.layers[i] != layer) r.layers[kept++] = r.layers[i]; + if (type == 5 && kept < 8) r.layers[kept++] = layer; + r.layer_count = kept; + r.action_seq++; + }); + break; + } +} + +__attribute__((visibility("hidden"))) static bool read_touch_report(TouchRingFile *ring, uint8_t *out) { + for (int attempt = 0; attempt < 8; attempt++) { + uint64_t seq = __atomic_load_n(&ring->report_seq, __ATOMIC_ACQUIRE); + if (seq & 1) continue; + memcpy(out, ring->report, TOUCH_REPORT_BYTES); + __atomic_thread_fence(__ATOMIC_ACQUIRE); + if (seq == __atomic_load_n(&ring->report_seq, __ATOMIC_RELAXED)) return true; + } + return false; +} + +__attribute__((visibility("hidden"))) static void *touch_report_thread(void *arg) { + auto *holder = static_cast *>(arg); + std::shared_ptr self = *holder; + delete holder; + TouchRingFile *ring = touch_ring(); + uint8_t report[TOUCH_REPORT_BYTES] = {}; + while (touch_plugged()) { + read_touch_report(ring, report); + if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 && + errno != EAGAIN && errno != EWOULDBLOCK) + break; + struct timespec interval = {0, TOUCH_REPORT_INTERVAL_US * 1000L}; + nanosleep(&interval, nullptr); + } + // Ending the stream is the unplug: the client's read fails and it lets the controller go. + syscall(SYS_close, self->peer); + touch_state([](TouchRingFile &r) { if (r.opened) r.opened--; }); + return nullptr; +} + +__attribute__((visibility("hidden"))) static int open_touch_hidraw(int flags) { + if (!touch_plugged()) { + errno = ENOENT; + return -1; + } + int pair[2]; + if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, pair) < 0) return -1; + int buffer = TOUCH_REPORT_BYTES * 4; + setsockopt(pair[1], SOL_SOCKET, SO_SNDBUF, &buffer, sizeof(buffer)); + if (!(flags & O_CLOEXEC)) fcntl(pair[0], F_SETFD, 0); + if (flags & O_NONBLOCK) fcntl(pair[0], F_SETFL, fcntl(pair[0], F_GETFL) | O_NONBLOCK); + auto touch = std::make_shared(); + touch->peer = pair[1]; + touch->touch = true; + { + std::lock_guard guard(controller_mutex()); + deck_map()[pair[0]] = touch; + watch_fd(pair[0]); + } + touch_state([](TouchRingFile &r) { r.opened++; }); + pthread_t thread; + auto *arg = new std::shared_ptr(touch); + if (pthread_create(&thread, nullptr, touch_report_thread, arg) != 0) { + delete arg; + std::lock_guard guard(controller_mutex()); + deck_map().erase(pair[0]); + unwatch_fd(pair[0]); + syscall(SYS_close, pair[0]); + syscall(SYS_close, pair[1]); + touch_state([](TouchRingFile &r) { if (r.opened) r.opened--; }); + errno = ENOMEM; + return -1; + } + pthread_detach(thread); + Logger::log("touch: %s opened as fd %d\n", TOUCH_HIDRAW_PATH, pair[0]); + return pair[0]; +} + +static int copy_ioctl_string(ioctl_request_t op, void *argp, const char *value); + +__attribute__((visibility("hidden"))) static int ioctl_touch(DeckHidraw &touch, ioctl_request_t op, void *argp) { + if (_IOC_TYPE(op) != 'H') { + errno = ENOTTY; + return -1; + } + size_t size = _IOC_SIZE(op); + switch (_IOC_NR(op)) { + case 0x01: // HIDIOCGRDESCSIZE + *static_cast(argp) = sizeof(kTouchReportDescriptor); + return 0; + case 0x02: { // HIDIOCGRDESC + auto *descriptor = static_cast(argp); + uint32_t want; + memcpy(&want, descriptor, sizeof(want)); + memcpy(descriptor + 4, kTouchReportDescriptor, std::min(want, sizeof(kTouchReportDescriptor))); + return 0; + } + case 0x03: { // HIDIOCGRAWINFO + struct { + uint32_t bustype; + int16_t vendor; + int16_t product; + } info = {BUS_USB, 0x0000, static_cast(0x11fb)}; + memcpy(argp, &info, sizeof(info)); + return 0; + } + case 0x04: return copy_ioctl_string(op, argp, TOUCH_NAME); // HIDIOCGRAWNAME + case 0x05: return copy_ioctl_string(op, argp, "usb-droiddeck-2/input0"); // HIDIOCGRAWPHYS + case 0x08: return copy_ioctl_string(op, argp, TOUCH_SERIAL); // HIDIOCGRAWUNIQ + case 0x06: // HIDIOCSFEATURE: Steam Link's controller ignores these + touch.pending_feature = size > 0 ? static_cast(argp)[0] : 0; + return static_cast(size); + case 0x07: { // HIDIOCGFEATURE: report 2 is the battery + auto *buf = static_cast(argp); + uint8_t id = size ? buf[0] : 0; + memset(buf, 0, size); + if (size) buf[0] = id; + if (size > 2) { + TouchRingFile *ring = touch_ring(); + buf[1] = 2; + buf[2] = static_cast(ring && ring->battery ? std::min(ring->battery, 100) : 100); + } + return static_cast(std::min(size, 18)); + } + default: + errno = EINVAL; + return -1; + } +} + +// Plugging in and out: the app flips `plugged`; this tells the client's HID discovery, which +// otherwise never looks again (the sandbox gives it no kernel uevents). +__attribute__((visibility("hidden"))) static int inject_uevent(const char *action, const char *devpath, + const char *subsystem, const char *devname, + unsigned major, unsigned minor) { + using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned); + static auto inject = reinterpret_cast(dlsym(RTLD_DEFAULT, "bl_udevmon_inject")); + return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1; +} + +__attribute__((visibility("hidden"))) static void touch_uevent(const char *action) { + int sent = inject_uevent(action, TOUCH_DEVPATH, "hidraw", TOUCH_HIDRAW_PATH, DECK_HIDRAW_MAJOR, TOUCH_HIDRAW_MINOR); + Logger::log("touch: %s (udev event to %d monitor%s)\n", action, sent, sent == 1 ? "" : "s"); +} + +// The devices each pad type is, as SteamDeckPad.kt describes them and inputudev.c the evdev node. +static constexpr const char *DECK_DEVPATH = "/devices/droiddeck/usb1/1-1:1.2/0003:28DE:1205.0001/hidraw/hidraw16"; +static constexpr const char *TRITON_PAD_DEVPATH = "/devices/droiddeck/usb3/3-1:1.0/0003:28DE:1302.0004/hidraw/hidraw19"; +static constexpr const char *PAD_EVDEV_DEVPATH = "/devices/virtual/input/droiddeck0/event0"; +static constexpr const char *DS4_DEVPATH = "/devices/droiddeck/usb4/4-1:1.3/0003:054C:09CC.0005/hidraw/hidraw20"; +static constexpr const char *DUALSENSE_DEVPATH = "/devices/droiddeck/usb5/5-1:1.3/0003:054C:0CE6.0006/hidraw/hidraw21"; +static constexpr const char *TRITON_DEVPATH = "/devices/droiddeck/bluetooth/0005:28DE:1303.0003/hidraw/hidraw18"; + +__attribute__((visibility("hidden"))) static int pad_type_uevent(uint32_t type, const char *action) { + if (type == PAD_TYPE_DECK) + return inject_uevent(action, DECK_DEVPATH, "hidraw", DECK_HIDRAW_PATH, DECK_HIDRAW_MAJOR, DECK_HIDRAW_MINOR); + if (type == PAD_TYPE_DS4) + return inject_uevent(action, DS4_DEVPATH, "hidraw", DS4_HIDRAW_PATH, DECK_HIDRAW_MAJOR, DS4_HIDRAW_MINOR); + if (type == PAD_TYPE_DUALSENSE) + return inject_uevent(action, DUALSENSE_DEVPATH, "hidraw", DUALSENSE_HIDRAW_PATH, DECK_HIDRAW_MAJOR, + DUALSENSE_HIDRAW_MINOR); + if (type == PAD_TYPE_STEAM) + return inject_uevent(action, TRITON_PAD_DEVPATH, "hidraw", TRITON_PAD_HIDRAW_PATH, TRITON_HIDRAW_MAJOR, + TRITON_PAD_HIDRAW_MINOR); + dev_t rdev = get_fake_input_rdev("event0"); + return inject_uevent(action, PAD_EVDEV_DEVPATH, "input", "/dev/input/event0", major(rdev), minor(rdev)); +} + +// SDL's HIDAPI in the client (the PlayStation pads' driver) finds hidraw devices by watching /dev +// with inotify, with udev off, and looks again on any entry named hidraw. The guest cannot +// create one in /dev, so the client's watch of /dev also covers this directory (inotify_add_watch +// below), where a switch makes and removes one. +__attribute__((visibility("hidden"))) static std::string hidraw_event_dir() { + return std::string(fake_hook_dir()) + "/.hidraw-events"; +} + +__attribute__((visibility("hidden"))) static void poke_hidraw_watchers(unsigned minor) { + std::string path = hidraw_event_dir() + "/hidraw" + std::to_string(minor); + int fd = static_cast(syscall(SYS_openat, AT_FDCWD, path.c_str(), O_CREAT | O_WRONLY | O_CLOEXEC, 0600)); + if (fd >= 0) syscall(SYS_close, fd); + unlink(path.c_str()); +} + +__attribute__((visibility("hidden"))) static unsigned pad_type_minor(uint32_t type) { + return type == PAD_TYPE_DS4 ? DS4_HIDRAW_MINOR + : type == PAD_TYPE_DUALSENSE ? DUALSENSE_HIDRAW_MINOR + : type == PAD_TYPE_STEAM ? TRITON_PAD_HIDRAW_MINOR : DECK_HIDRAW_MINOR; +} + +// A switch, as the client sees one: the old device unplugged, then the new one plugged in. +__attribute__((visibility("hidden"))) static void *pad_type_thread(void *) { + static const char *kNames[] = {"Steam Deck controller", "Steam Controller", "Xbox 360 controller", + "DualShock 4", "DualSense"}; + uint32_t was = live_pad_type(); + bool paired = fake_triton_enabled() && triton_connected(); + Logger::log("pad: a %s at start%s\n", kNames[was % 5], paired ? ", the paired Steam Controller connected" : ""); + for (;;) { + struct timespec interval = {0, 50 * 1000 * 1000}; + nanosleep(&interval, nullptr); + bool connected = fake_triton_enabled() && triton_connected(); + if (connected != paired) { + paired = connected; + int sent = inject_uevent(connected ? "add" : "remove", TRITON_DEVPATH, "hidraw", TRITON_HIDRAW_PATH, + TRITON_HIDRAW_MAJOR, TRITON_HIDRAW_MINOR); + Logger::log("pad: the paired Steam Controller %s (udev event to %d monitors)\n", + connected ? "connected" : "disconnected", sent); + } + uint32_t now = live_pad_type(); + if (now == was || now > PAD_TYPE_LAST) continue; + int removed = pad_type_uevent(was, "remove"); + // Time for the client to let the old device go before the new one appears. + struct timespec settle = {0, 300 * 1000 * 1000}; + nanosleep(&settle, nullptr); + int added = pad_type_uevent(now, "add"); + if (was != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(was)); + if (now != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(now)); + // The pad's evdev node comes or goes with the Xbox 360 type. Its hotplug is watched with + // inotify on /dev/input (SDL's, with udev off), so it is moved out and back in: everyone + // watching sees it removed and added, and opens it again only if it is the pad now. + if (was == PAD_TYPE_XBOX || now == PAD_TYPE_XBOX) { + std::string node = std::string(fake_hook_dir()) + "/event0"; + std::string aside = std::string(fake_hook_dir()) + "/.event0-switching"; + if (rename(node.c_str(), aside.c_str()) == 0) { + nanosleep(&settle, nullptr); + if (rename(aside.c_str(), node.c_str()) != 0) + Logger::log("pad: event0 not put back (%s)\n", strerror(errno)); + } else { + Logger::log("pad: event0 not moved (%s)\n", strerror(errno)); + } + } + Logger::log("pad: now a %s (udev events to %d/%d monitors)\n", kNames[now], removed, added); + was = now; + } + return nullptr; +} + +__attribute__((constructor)) static void start_pad_type_watch() { + config(); + if (!process_is_steam_client() || !fake_deck_enabled()) return; + pthread_t thread; + if (pthread_create(&thread, nullptr, pad_type_thread, nullptr) == 0) pthread_detach(thread); +} + +__attribute__((visibility("hidden"))) static void *touch_plug_thread(void *) { + bool was = touch_plugged(); + Logger::log("touch: %s at start\n", was ? "plugged in" : "unplugged"); + for (;;) { + struct timespec interval = {0, 50 * 1000 * 1000}; + nanosleep(&interval, nullptr); + bool now = touch_plugged(); + if (now == was) continue; + was = now; + touch_uevent(now ? "add" : "remove"); + } + return nullptr; +} + +__attribute__((constructor)) static void start_touch_controller() { + config(); + if (!process_is_steam_client() || !touch_ring()) return; + pthread_t thread; + if (pthread_create(&thread, nullptr, touch_plug_thread, nullptr) == 0) pthread_detach(thread); +} + // libudev (systemd's sd-device) accepts a device only where its directory is on sysfs, which it // checks with fstatfs on the directory it resolved. The Deck's sysfs is the app's own files bound // into /sys, so those paths are said to be sysfs; nothing else is touched. @@ -1567,6 +2573,41 @@ __attribute__((visibility("hidden"))) static void log_deck_feature(const char *w if ((n & (n - 1)) == 0) Logger::log("deck: feature 0x%02x %s (x%u)\n", feature, what, n); } +// A settings report (ID_SET_SETTINGS_VALUES) is a list of (setting id, 16-bit value) triples after +// the length byte. Returns SETTING_IMU_MODE (48, a SETTING_GYRO_MODE_* bitmask from SDL's +// controller_constants.h) when the report changes it, logged, else -1: the client repeats its +// settings for as long as it has the pad. +static constexpr uint8_t DECK_SET_SETTINGS_VALUES = 0x87; +static constexpr uint8_t DECK_SETTING_IMU_MODE = 48; + +__attribute__((visibility("hidden"))) static int deck_imu_mode_change(const uint8_t *buf, size_t size) { + static std::atomic last{-1}; + size_t end = std::min(size, static_cast(3) + buf[2]); + for (size_t i = 3; i + 3 <= end; i += 3) { + if (buf[i] != DECK_SETTING_IMU_MODE) continue; + int32_t value = buf[i + 1] | buf[i + 2] << 8; + if (last.exchange(value) == value) return -1; + Logger::log("deck: imu mode 0x%04x\n", value); + return value; + } + return -1; +} + +// Tells the app whether the client wants motion (DeckImu::imu_mode, FakeInputWriter.readImuMode): +// PadMotion reads the phone's sensors only while it does. The mapping is read-only, and the +// client changes the mode a few times a minute at most, so the file is written directly. +__attribute__((visibility("hidden"))) static void publish_imu_mode(const DeckHidraw &deck, int mode) { + static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); + if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return; + std::string path = get_ring_path_for_slot(0); + int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC); + if (fd < 0) return; + uint32_t value = 0x80000000u | static_cast(mode); + if (pwrite(fd, &value, sizeof(value), FAKE_INPUT_RING_SIZE + offsetof(DeckImu, imu_mode)) != sizeof(value)) + Logger::log("deck: imu mode not published (%s)\n", strerror(errno)); + syscall(SYS_close, fd); +} + __attribute__((visibility("hidden"))) static int deck_feature(DeckHidraw &deck, ioctl_request_t op, uint8_t *buf, bool set) { size_t size = _IOC_SIZE(op); @@ -1580,6 +2621,10 @@ deck_feature(DeckHidraw &deck, ioctl_request_t op, uint8_t *buf, bool set) { int left = buf[6] | buf[7] << 8, right = buf[8] | buf[9] << 8; send_vibration(left, right, left || right ? 1000 : 0, 0); } + if (buf[1] == DECK_SET_SETTINGS_VALUES && size >= 3) { + int imu_mode = deck_imu_mode_change(buf, size); + if (imu_mode >= 0) publish_imu_mode(deck, imu_mode); + } log_deck_feature("set", buf[1]); return static_cast(size); } @@ -1616,6 +2661,117 @@ deck_feature(DeckHidraw &deck, ioctl_request_t op, uint8_t *buf, bool set) { return static_cast(length); } +// The PlayStation pads' report descriptor: a gamepad with input report 1, the output report the +// model takes (5 on a DualShock 4, 2 on a DualSense) and the feature reports a driver reads. +static const uint8_t kDs4ReportDescriptor[] = { + 0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, + 0x85, 0x01, 0x09, 0x20, 0x95, 0x3f, 0x81, 0x02, 0x85, 0x05, 0x09, 0x21, 0x95, 0x1f, 0x91, 0x02, + 0x85, 0x02, 0x09, 0x24, 0x95, 0x24, 0xb1, 0x02, 0x85, 0x12, 0x09, 0x25, 0x95, 0x0f, 0xb1, 0x02, + 0x85, 0xa3, 0x09, 0x26, 0x95, 0x30, 0xb1, 0x02, 0x85, 0x81, 0x09, 0x27, 0x95, 0x3f, 0xb1, 0x02, + 0xc0}; +static const uint8_t kDualSenseReportDescriptor[] = { + 0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, + 0x85, 0x01, 0x09, 0x20, 0x95, 0x3f, 0x81, 0x02, 0x85, 0x02, 0x09, 0x21, 0x95, 0x2f, 0x91, 0x02, + 0x85, 0x05, 0x09, 0x22, 0x95, 0x28, 0xb1, 0x02, 0x85, 0x09, 0x09, 0x23, 0x95, 0x13, 0xb1, 0x02, + 0x85, 0x20, 0x09, 0x24, 0x95, 0x3f, 0xb1, 0x02, 0xc0}; + +// Calibration both models report the same way (SDL: LoadCalibrationData): no bias, and the +// ranges that make a unit 1/16 degree/s and 1/8192 g, the scale build_sony_report writes in. +__attribute__((visibility("hidden"))) static void put_sony_calibration(uint8_t *reply) { + for (int axis = 0; axis < 3; axis++) { + put16(reply + 7 + axis * 4, 8640); + put16(reply + 9 + axis * 4, -8640); + put16(reply + 23 + axis * 4, 8192); + put16(reply + 25 + axis * 4, -8192); + } + put16(reply + 19, 540); + put16(reply + 21, 540); +} + +__attribute__((visibility("hidden"))) static int sony_feature(const DeckHidraw &pad, uint8_t *buf, size_t size) { + if (!buf || size < 1) { + errno = EINVAL; + return -1; + } + uint8_t id = buf[0]; + uint8_t reply[64] = {}; + reply[0] = id; + size_t length = size; + if ((pad.sony == 4 && id == 0x02) || (pad.sony == 5 && id == 0x05)) { + put_sony_calibration(reply); + } else if ((pad.sony == 4 && (id == 0x12 || id == 0x81)) || (pad.sony == 5 && id == 0x09)) { + for (int i = 0; i < 6; i++) reply[1 + i] = SONY_MAC[5 - i]; // the address, last byte first + } else if (pad.sony == 5 && id == 0x20) { + reply[44] = 0x30; // firmware 0x0430: past the versions SDL treats as old + reply[45] = 0x04; + } + log_deck_feature("read", id); + length = std::min(length, sizeof(reply)); + memcpy(buf, reply, length); + return static_cast(length); +} + +// Rumble from the output report, when its flags say it carries rumble: a DualShock 4's report 5 +// (right/weak, then left/strong at 4 and 5), a DualSense's report 2 (at 3 and 4). +__attribute__((visibility("hidden"))) static void sony_output(const DeckHidraw &pad, const uint8_t *data, size_t size) { + if (!data || size < 6) return; + int weak, strong; + if (pad.sony == 4 && data[0] == 0x05) { + if (!(data[1] & 0x01)) return; + weak = data[4]; + strong = data[5]; + } else if (pad.sony == 5 && data[0] == 0x02) { + if (!(data[1] & 0x03)) return; + weak = data[3]; + strong = data[4]; + } else { + return; + } + // The drivers send a new report when the rumble changes and a zero one to stop it. + send_vibration(strong * 257, weak * 257, strong || weak ? 2000 : 0, 0); +} + +__attribute__((visibility("hidden"))) static int ioctl_sony(DeckHidraw &pad, ioctl_request_t op, void *argp) { + if (_IOC_TYPE(op) != 'H') { + errno = ENOTTY; + return -1; + } + const uint8_t *descriptor = pad.sony == 4 ? kDs4ReportDescriptor : kDualSenseReportDescriptor; + size_t descriptor_size = pad.sony == 4 ? sizeof(kDs4ReportDescriptor) : sizeof(kDualSenseReportDescriptor); + switch (_IOC_NR(op)) { + case 0x01: + *static_cast(argp) = static_cast(descriptor_size); + return 0; + case 0x02: { + auto *out = static_cast(argp); + uint32_t size; + memcpy(&size, out, sizeof(size)); + memcpy(out + 4, descriptor, std::min(size, descriptor_size)); + return 0; + } + case 0x03: { + struct { + uint32_t bustype; + int16_t vendor; + int16_t product; + } info = {BUS_USB, static_cast(0x054c), static_cast(pad.sony == 4 ? 0x09cc : 0x0ce6)}; + memcpy(argp, &info, sizeof(info)); + return 0; + } + case 0x04: + return copy_ioctl_string(op, argp, pad.sony == 4 ? "Sony Interactive Entertainment Wireless Controller" + : "Sony Interactive Entertainment DualSense Wireless Controller"); + case 0x05: return copy_ioctl_string(op, argp, pad.sony == 4 ? "usb-droiddeck-4/input3" : "usb-droiddeck-5/input3"); + case 0x08: return copy_ioctl_string(op, argp, "5e:43:4b:44:44:02"); + case 0x06: // HIDIOCSFEATURE: nothing the pads need is set this way + return static_cast(_IOC_SIZE(op)); + case 0x07: return sony_feature(pad, static_cast(argp), _IOC_SIZE(op)); + default: + errno = EINVAL; + return -1; + } +} + __attribute__((visibility("hidden"))) static int ioctl_deck(DeckHidraw &deck, ioctl_request_t op, void *argp) { if (_IOC_TYPE(op) != 'H') { @@ -1654,6 +2810,204 @@ ioctl_deck(DeckHidraw &deck, ioctl_request_t op, void *argp) { } } +__attribute__((visibility("hidden"))) static void triton_queue_output(DeckHidraw &triton, const uint8_t *data, + size_t size, bool feature) { + if (!data || !size || size > 64 || triton.mapping_size < TRITON_SHARED_OFFSET + TRITON_SHARED_BLOCK_SIZE) return; + auto *shared = reinterpret_cast(reinterpret_cast(triton.ring) + TRITON_SHARED_OFFSET); + if (__atomic_load_n(&shared->magic, __ATOMIC_ACQUIRE) != TRITON_SHARED_MAGIC) return; + uint64_t seq = __atomic_load_n(&shared->output_seq, __ATOMIC_RELAXED); + if (seq & 1) seq++; + __atomic_store_n(&shared->output_seq, seq + 1, __ATOMIC_RELEASE); + shared->output_feature = feature ? 1 : 0; + shared->output_length = static_cast(size); + memcpy(shared->output, data, size); + if (size < sizeof(shared->output)) memset(shared->output + size, 0, sizeof(shared->output) - size); + __atomic_thread_fence(__ATOMIC_RELEASE); + __atomic_store_n(&shared->output_seq, seq + 2, __ATOMIC_RELEASE); + static std::atomic counts[2][256]; + uint8_t report_id = feature ? (size > 1 ? data[1] : 0) : data[0]; + unsigned n = ++counts[feature ? 1 : 0][report_id]; + if ((n & (n - 1)) == 0) + Logger::log("triton: %s report 0x%02x (x%u, %zu bytes)\n", feature ? "feature" : "output", report_id, n, size); +} + +// HIDIOCGFEATURE: the client reads the controller's info (report 1) this way, and a device that +// answers with nothing is dropped as a zombie. The read goes to the controller itself, as SDL's +// BLE backend does it (hid.m, get_feature_report): its reply is the report, with the report ID +// put in front when the controller left it out. Called without controller_mutex: it waits. +__attribute__((visibility("hidden"))) static int triton_get_feature(DeckHidraw &triton, uint8_t *report, size_t size) { + if (!report || size < 2 || triton.mapping_size < TRITON_SHARED_OFFSET + TRITON_SHARED_BLOCK_SIZE) { + errno = EINVAL; + return -1; + } + auto *shared = reinterpret_cast(reinterpret_cast(triton.ring) + TRITON_SHARED_OFFSET); + static std::mutex one_at_a_time; + std::lock_guard guard(one_at_a_time); + uint8_t report_id = report[0]; + __atomic_store_n(&shared->get_report_id, report_id, __ATOMIC_RELAXED); + uint64_t request = __atomic_add_fetch(&shared->get_request, 1, __ATOMIC_RELEASE); + for (int waited = 0; waited < TRITON_FEATURE_TIMEOUT_MS * 4; waited++) { + if (__atomic_load_n(&shared->get_reply, __ATOMIC_ACQUIRE) == request) { + int32_t length = __atomic_load_n(&shared->get_length, __ATOMIC_RELAXED); + if (length <= 0 || length > static_cast(sizeof(shared->get))) break; + size_t copied; + memset(report, 0, size); + if (shared->get[0] == report_id) { + copied = std::min(size, static_cast(length)); + memcpy(report, shared->get, copied); + } else { + report[0] = report_id; + copied = 1 + std::min(size - 1, static_cast(length)); + memcpy(report + 1, shared->get, copied - 1); + } + static std::atomic reads[256]; + unsigned n = ++reads[report_id]; + if ((n & (n - 1)) == 0) + Logger::log("triton: feature 0x%02x read, %d bytes from the controller [%02x %02x %02x %02x] (x%u)\n", report_id, + length, shared->get[0], shared->get[1], shared->get[2], shared->get[3], n); + return static_cast(copied); + } + struct timespec interval = {0, 250 * 1000L}; + nanosleep(&interval, nullptr); + } + static std::atomic failures; + unsigned n = ++failures; + if ((n & (n - 1)) == 0) Logger::log("triton: feature 0x%02x read got no answer from the controller (x%u)\n", report_id, n); + errno = EIO; + return -1; +} + +// The emulated controller's feature reports: report ID 1, then the Valve message (type, length, +// payload), answered here as the Deck's are. The identity is the one a 2025 Steam Controller gave +// on device (HWID 72, its firmware timestamp), with this library's serial. +static constexpr uint32_t TRITON_HWID = 72; +static constexpr uint32_t TRITON_FW_TIMESTAMP = 0x6AC686B3; + +__attribute__((visibility("hidden"))) static int triton_pad_feature(DeckHidraw &triton, uint8_t *buf, size_t size, bool set) { + if (!buf || size < 2) { + errno = EINVAL; + return -1; + } + if (set) { + triton.pending_feature = buf[1]; + if (buf[1] == DECK_SET_SETTINGS_VALUES && size >= 3) { + int imu_mode = deck_imu_mode_change(buf, size); + if (imu_mode >= 0) publish_imu_mode(triton, imu_mode); + } + log_deck_feature("set", buf[1]); + return static_cast(size); + } + uint8_t reply[65] = {}; + reply[0] = buf[0]; + reply[1] = triton.pending_feature; + switch (triton.pending_feature) { + case DECK_GET_ATTRIBUTES_VALUES: { + // (attribute, 32-bit value) pairs: product id, capabilities, firmware timestamp, hardware id. + static const uint8_t kIds[] = {0x01, 0x02, 0x04, 0x09, 0x0a, 0x0b}; + const uint32_t values[] = {static_cast(TRITON_WIRED_PRODUCT), 0, TRITON_FW_TIMESTAMP, TRITON_HWID, 0, 4000}; + reply[2] = sizeof(kIds) * 5; + for (size_t i = 0; i < sizeof(kIds); i++) { + reply[3 + i * 5] = kIds[i]; + put32(reply + 4 + i * 5, values[i]); + } + break; + } + case DECK_GET_STRING_ATTRIBUTE: + reply[2] = 0x14; + reply[3] = 0x01; // the unit serial + memcpy(reply + 4, TRITON_SERIAL, strlen(TRITON_SERIAL)); + break; + case DECK_GET_CHIP_ID: + reply[2] = 0x11; + memcpy(reply + 4, "DROIDDECKCHIP02", 15); + break; + default: + break; + } + log_deck_feature("read", triton.pending_feature); + size_t length = std::min(size, sizeof(reply)); + memcpy(buf, reply, length); + return static_cast(length); +} + +// The emulated controller's haptic output reports (SDL, controller_structs.h) on the handheld's +// own motor: rumble as asked, the trackpad pulses and effects as short ticks. +__attribute__((visibility("hidden"))) static void triton_pad_output(const uint8_t *data, size_t size) { + if (!data || size < 2) return; + switch (data[0]) { + case 0x80: // ID_OUT_REPORT_HAPTIC_RUMBLE: type, intensity, left {speed, gain}, right {speed, gain} + if (size >= 10) { + int left = data[4] | data[5] << 8, right = data[7] | data[8] << 8; + // SDL repeats a held rumble every 40 ms, so each report lasts a little longer than that. + send_vibration(left, right, left || right ? 100 : 0, 0); + } + break; + case 0x81: // ID_OUT_REPORT_HAPTIC_PULSE: side, on_us, off_us, repeat count + if (size >= 8) { + int on_ms = (data[2] | data[3] << 8) / 1000, repeat = data[6] | data[7] << 8; + send_vibration(0, 40000, std::max(8, std::min(200, on_ms * std::max(1, repeat))), 0); + } + break; + case 0x82: case 0x83: case 0x84: case 0x85: // command, tone, sweep, script + send_vibration(0, 30000, 15, 0); + break; + default: + break; + } +} + +__attribute__((visibility("hidden"))) static int ioctl_triton(DeckHidraw &triton, ioctl_request_t op, void *argp) { + if (_IOC_TYPE(op) != 'H') { + errno = ENOTTY; + return -1; + } + switch (_IOC_NR(op)) { + case 0x01: + *static_cast(argp) = sizeof(kTritonReportDescriptor); + return 0; + case 0x02: { + auto *descriptor = static_cast(argp); + uint32_t size; + memcpy(&size, descriptor, sizeof(size)); + memcpy(descriptor + 4, kTritonReportDescriptor, std::min(size, sizeof(kTritonReportDescriptor))); + // The wired controller's state report (SteamDeckPad's TRITON_WIRED_REPORT_DESCRIPTOR). + if (triton.emulated && size > 15) descriptor[4 + 15] = TRITON_STATE_WIRED; + return 0; + } + case 0x03: { + struct { + uint32_t bustype; + int16_t vendor; + int16_t product; + } info = {triton.emulated ? static_cast(BUS_USB) : static_cast(BUS_BLUETOOTH), + static_cast(0x28de), triton.emulated ? TRITON_WIRED_PRODUCT : static_cast(0x1303)}; + memcpy(argp, &info, sizeof(info)); + return 0; + } + case 0x04: return copy_ioctl_string(op, argp, TRITON_NAME); + case 0x05: return copy_ioctl_string(op, argp, triton.emulated ? "usb-droiddeck-3/input0" : "bluetooth-droiddeck-1"); + case 0x08: return copy_ioctl_string(op, argp, TRITON_SERIAL); + case 0x06: { + // The client's feature reports are the report ID and 64 bytes; the last is padding the BLE + // characteristic does not take (SteamControllerBle.sendOutputReport drops it), so 64 are kept. + size_t size = _IOC_SIZE(op); + if (!argp || size < 2 || size > 65) { + errno = EINVAL; + return -1; + } + if (triton.emulated) return triton_pad_feature(triton, static_cast(argp), size, true); + triton_queue_output(triton, static_cast(argp), std::min(size, 64), true); + return static_cast(size); + } + case 0x07: + if (triton.emulated) return triton_pad_feature(triton, static_cast(argp), _IOC_SIZE(op), false); + return triton_get_feature(triton, static_cast(argp), _IOC_SIZE(op)); + default: + errno = EINVAL; + return -1; + } +} + // A device scan that fails on a phone and not on the Thor: libudev gives up its whole scan on any // sysfs directory it cannot read for a reason other than its absence, and a phone's SELinux policy // denies directories a permissive device lets through. The client's /sys failures that are not @@ -1823,6 +3177,10 @@ EXPORT int open(const char *pathname, int flags, ...) { if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags); if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags); + if (is_triton_hidraw_path(pathname)) return open_triton_hidraw(flags, false); + if (is_triton_pad_path(pathname)) return open_triton_hidraw(flags, true); + if (int sony = sony_pad_path(pathname)) return open_deck_hidraw(flags, static_cast(sony)); + if (is_touch_hidraw_path(pathname)) return open_touch_hidraw(flags); if (is_withdrawn_pad_path(pathname)) { errno = ENOENT; return -1; @@ -1897,6 +3255,10 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) { if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags); if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags); + if (is_triton_hidraw_path(pathname)) return open_triton_hidraw(flags, false); + if (is_triton_pad_path(pathname)) return open_triton_hidraw(flags, true); + if (int sony = sony_pad_path(pathname)) return open_deck_hidraw(flags, static_cast(sony)); + if (is_touch_hidraw_path(pathname)) return open_touch_hidraw(flags); if (is_withdrawn_pad_path(pathname)) { errno = ENOENT; return -1; @@ -1953,16 +3315,36 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) { template static int fake_stat_path(const char *pathname, S *statbuf, Real real) { - if (is_withdrawn_pad_path(pathname) || (is_deck_hidraw_path(pathname) && !process_is_steam_client())) { + if (is_withdrawn_pad_path(pathname) || + ((is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || + sony_pad_path(pathname)) && !process_is_steam_client())) { errno = ENOENT; return -1; } + if (is_touch_hidraw_path(pathname)) { + memset(statbuf, 0, sizeof(*statbuf)); + statbuf->st_mode = S_IFCHR | 0666; + statbuf->st_rdev = makedev(DECK_HIDRAW_MAJOR, TOUCH_HIDRAW_MINOR); + return 0; + } if (is_deck_hidraw_path(pathname)) { memset(statbuf, 0, sizeof(*statbuf)); statbuf->st_mode = S_IFCHR | 0666; statbuf->st_rdev = makedev(DECK_HIDRAW_MAJOR, DECK_HIDRAW_MINOR); return 0; } + if (int sony = sony_pad_path(pathname)) { + memset(statbuf, 0, sizeof(*statbuf)); + statbuf->st_mode = S_IFCHR | 0666; + statbuf->st_rdev = makedev(DECK_HIDRAW_MAJOR, sony == 4 ? DS4_HIDRAW_MINOR : DUALSENSE_HIDRAW_MINOR); + return 0; + } + if (is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname)) { + memset(statbuf, 0, sizeof(*statbuf)); + statbuf->st_mode = S_IFCHR | 0666; + statbuf->st_rdev = makedev(TRITON_HIDRAW_MAJOR, is_triton_pad_path(pathname) ? TRITON_PAD_HIDRAW_MINOR : TRITON_HIDRAW_MINOR); + return 0; + } const char *event = nullptr; char *fake_path = nullptr; @@ -2004,11 +3386,18 @@ static int fake_stat_path(const char *pathname, S *statbuf, Real real) { template static int fake_stat_fd(int fd, S *buf, Real real) { int ret = real(fd, buf); + if (ret != 0 || !watched(fd)) return ret; std::lock_guard guard(controller_mutex()); if (ret == 0 && deck_map().count(fd)) { buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFCHR; - buf->st_rdev = makedev(DECK_HIDRAW_MAJOR, DECK_HIDRAW_MINOR); + const auto &device = *deck_map()[fd]; + unsigned int minor = device.touch ? TOUCH_HIDRAW_MINOR + : device.sony == 4 ? DS4_HIDRAW_MINOR + : device.sony == 5 ? DUALSENSE_HIDRAW_MINOR + : device.emulated ? TRITON_PAD_HIDRAW_MINOR + : device.triton ? TRITON_HIDRAW_MINOR : DECK_HIDRAW_MINOR; + buf->st_rdev = makedev(DECK_HIDRAW_MAJOR, minor); return ret; } auto controller = controller_map().find(fd); @@ -2054,7 +3443,12 @@ EXPORT int access(const char *pathname, int mode) { static auto my_access = reinterpret_cast(dlsym(RTLD_NEXT, "access")); if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0; if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0; - if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname)) { + if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) && + process_is_steam_client()) + return 0; + if (is_touch_hidraw_path(pathname)) return 0; + if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) || + is_triton_pad_path(pathname) || sony_pad_path(pathname)) { errno = ENOENT; return -1; } @@ -2090,7 +3484,12 @@ EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) { static auto my_faccessat = reinterpret_cast(dlsym(RTLD_NEXT, "faccessat")); if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0; if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0; - if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname)) { + if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) && + process_is_steam_client()) + return 0; + if (is_touch_hidraw_path(pathname)) return 0; + if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) || + is_triton_pad_path(pathname) || sony_pad_path(pathname)) { errno = ENOENT; return -1; } @@ -2153,6 +3552,11 @@ EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) { pathname = fake_path; } else if (!strcmp(pathname, "/dev/input")) { pathname = fake_hook_dir(); + } else if (!strcmp(pathname, "/dev") && fake_deck_enabled() && process_is_steam_client()) { + // Beside /dev itself, not instead: the same descriptor gets both directories' events. + std::string events = hidraw_event_dir(); + mkdir(events.c_str(), 0700); + my_inotify_add_watch(fd, events.c_str(), mask); } } @@ -2177,7 +3581,7 @@ static bool wait_snapshot(std::shared_ptr fake, errno = EBADF; return false; } - if (ring_generation(fake->ring) != fake->generation) { + if (controller_gone(*fake)) { errno = ENODEV; return false; } @@ -2207,11 +3611,21 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { // The lock must not be held across the passthrough: binder's transport is a // blocking ioctl(BINDER_WRITE_READ), so a parked binder pool thread would own // controller_mutex() for as long as it waits and deadlock every other ioctl. + if (!watched(fd)) return syscall(SYS_ioctl, fd, op, argp); std::unique_lock guard(controller_mutex()); auto maker = uinput_map().find(fd); if (maker != uinput_map().end()) return ioctl_uinput(*maker->second, op, argp); auto deck = deck_map().find(fd); - if (deck != deck_map().end()) return ioctl_deck(*deck->second, op, argp); + if (deck != deck_map().end()) { + if (deck->second->touch) return ioctl_touch(*deck->second, op, argp); + if (deck->second->sony) return ioctl_sony(*deck->second, op, argp); + if (deck->second->triton) { + std::shared_ptr triton = deck->second; + guard.unlock(); + return ioctl_triton(*triton, op, argp); + } + return ioctl_deck(*deck->second, op, argp); + } auto controller = controller_map().find(fd); if (controller == controller_map().end()) { guard.unlock(); @@ -2418,6 +3832,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { EXPORT int close(int fd) { static auto my_close = reinterpret_cast(dlsym(RTLD_NEXT, "close")); + if (!watched(fd)) return my_close(fd); close_uinput(fd); std::unique_lock guard(controller_mutex()); deck_map().erase(fd); @@ -2428,6 +3843,7 @@ EXPORT int close(int fd) { controller->second->closed = true; controller_map().erase(fd); } + unwatch_fd(fd); guard.unlock(); return my_close(fd); @@ -2436,6 +3852,7 @@ EXPORT int close(int fd) { static constexpr int kMaxRingWaitMs = 2; EXPORT ssize_t read(int fd, void *buf, size_t count) { + if (!watched(fd)) return syscall(SYS_read, fd, buf, count); std::unique_lock guard(controller_mutex()); auto controller = controller_map().find(fd); if (controller == controller_map().end()) { @@ -2459,7 +3876,7 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) { errno = EBADF; return -1; } - if (ring_generation(fake.ring) != fake.generation) { + if (controller_gone(fake)) { errno = ENODEV; return -1; } @@ -2534,10 +3951,17 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) { EXPORT ssize_t write(int fd, const void *buf, size_t count) { static auto my_write = reinterpret_cast(dlsym(RTLD_NEXT, "write")); + if (!watched(fd)) return my_write(fd, buf, count); std::unique_lock guard(controller_mutex()); auto made = uinput_map().find(fd); if (made != uinput_map().end()) return write_uinput(*made->second, buf, count); - if (deck_map().count(fd)) return static_cast(count); + if (deck_map().count(fd)) { + if (deck_map()[fd]->touch) touch_output(static_cast(buf), count); + else if (deck_map()[fd]->sony) sony_output(*deck_map()[fd], static_cast(buf), count); + else if (deck_map()[fd]->emulated) triton_pad_output(static_cast(buf), count); + else if (deck_map()[fd]->triton) triton_queue_output(*deck_map()[fd], static_cast(buf), count, false); + return static_cast(count); + } auto controller = controller_map().find(fd); if (controller != controller_map().end()) { if (fake_fd_is_stale(fd)) { @@ -2559,10 +3983,18 @@ EXPORT ssize_t write(int fd, const void *buf, size_t count) { } EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) { + if (!watched(fd)) return syscall(SYS_writev, fd, iov, iovcnt); std::unique_lock guard(controller_mutex()); if (deck_map().count(fd)) { ssize_t total = 0; - for (int i = 0; i < iovcnt; i++) total += static_cast(iov[i].iov_len); + auto device = deck_map()[fd]; + for (int i = 0; i < iovcnt; i++) { + if (device->touch) touch_output(static_cast(iov[i].iov_base), iov[i].iov_len); + else if (device->sony) sony_output(*device, static_cast(iov[i].iov_base), iov[i].iov_len); + else if (device->emulated) triton_pad_output(static_cast(iov[i].iov_base), iov[i].iov_len); + else if (device->triton) triton_queue_output(*device, static_cast(iov[i].iov_base), iov[i].iov_len, false); + total += static_cast(iov[i].iov_len); + } return total; } auto made = uinput_map().find(fd); @@ -2604,11 +4036,14 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout, static auto my_poll = reinterpret_cast(dlsym(RTLD_NEXT, "poll")); static auto my_ppoll = reinterpret_cast(dlsym(RTLD_NEXT, "ppoll")); + nfds_t first = 0; + while (first < nfds && !watched(fds[first].fd)) first++; bool has_fake_fds = false; std::vector real_fds; - real_fds.reserve(nfds); - std::vector> fake_fds(nfds); - { + std::vector> fake_fds; + if (first < nfds) { + real_fds.reserve(nfds); + fake_fds.resize(nfds); std::lock_guard guard(controller_mutex()); for (nfds_t i = 0; i < nfds; i++) { real_fds.push_back(fds[i]); diff --git a/app/src/main/cpp/termux/termux.c b/app/src/main/cpp/termux/termux.c index 195098169f..7d4f86e31f 100644 --- a/app/src/main/cpp/termux/termux.c +++ b/app/src/main/cpp/termux/termux.c @@ -136,6 +136,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess( if (!arg_utf8) return throw_runtime_exception(env, "GetStringUTFChars() failed for argv"); argv[i] = strdup(arg_utf8); (*env)->ReleaseStringUTFChars(env, arg_java_string, arg_utf8); + (*env)->DeleteLocalRef(env, arg_java_string); } argv[size] = NULL; } @@ -151,6 +152,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess( if (!env_utf8) return throw_runtime_exception(env, "GetStringUTFChars() failed for env"); envp[i] = strdup(env_utf8); (*env)->ReleaseStringUTFChars(env, env_java_string, env_utf8); + (*env)->DeleteLocalRef(env, env_java_string); } envp[size] = NULL; } @@ -160,7 +162,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess( char const* cmd_utf8 = (*env)->GetStringUTFChars(env, cmd, NULL); int ptm = create_subprocess(env, cmd_utf8, cmd_cwd, argv, envp, &procId, rows, columns); (*env)->ReleaseStringUTFChars(env, cmd, cmd_utf8); - (*env)->ReleaseStringUTFChars(env, cmd, cmd_cwd); + (*env)->ReleaseStringUTFChars(env, cwd, cmd_cwd); if (argv) { for (char** tmp = argv; *tmp; ++tmp) free(*tmp); diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index ddf19d05f7..c2f9cb6543 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -17,6 +17,7 @@ add_library(droiddeckwayland SHARED src/wl_clipboard.c src/wl_text_input.c src/wl_toplevel_icon.c + src/wl_single_pixel.c src/wl_color_mgmt.c src/hdr_compose.c src/blend_pass.c @@ -31,6 +32,7 @@ add_library(droiddeckwayland SHARED generated/wlr-data-control-unstable-v1-protocol.c generated/text-input-unstable-v3-protocol.c generated/xdg-toplevel-icon-v1-protocol.c + generated/single-pixel-buffer-v1-protocol.c generated/banner-ahb-v1-protocol.c src/framegen_bridge.c src/framegen_jni.c diff --git a/app/src/main/cpp/waylandcomp/generated/single-pixel-buffer-v1-protocol.c b/app/src/main/cpp/waylandcomp/generated/single-pixel-buffer-v1-protocol.c new file mode 100644 index 0000000000..01434221c6 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/generated/single-pixel-buffer-v1-protocol.c @@ -0,0 +1,61 @@ +/* Generated by wayland-scanner 1.26.0 */ + +/* + * Copyright © 2022 Simon Ser + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#include +#include +#include +#include "wayland-util.h" + +#ifndef __has_attribute +# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */ +#endif + +#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4) +#define WL_PRIVATE __attribute__ ((visibility("hidden"))) +#else +#define WL_PRIVATE +#endif + +extern const struct wl_interface wl_buffer_interface; + +static const struct wl_interface *single_pixel_buffer_v1_types[] = { + &wl_buffer_interface, + NULL, + NULL, + NULL, + NULL, +}; + +static const struct wl_message wp_single_pixel_buffer_manager_v1_requests[] = { + { "destroy", "", single_pixel_buffer_v1_types + 0 }, + { "create_u32_rgba_buffer", "nuuuu", single_pixel_buffer_v1_types + 0 }, +}; + +WL_PRIVATE const struct wl_interface wp_single_pixel_buffer_manager_v1_interface = { + "wp_single_pixel_buffer_manager_v1", 1, + 2, wp_single_pixel_buffer_manager_v1_requests, + 0, NULL, +}; + diff --git a/app/src/main/cpp/waylandcomp/generated/single-pixel-buffer-v1-server-protocol.h b/app/src/main/cpp/waylandcomp/generated/single-pixel-buffer-v1-server-protocol.h new file mode 100644 index 0000000000..a030d47757 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/generated/single-pixel-buffer-v1-server-protocol.h @@ -0,0 +1,142 @@ +/* Generated by wayland-scanner 1.26.0 */ + +#ifndef SINGLE_PIXEL_BUFFER_V1_SERVER_PROTOCOL_H +#define SINGLE_PIXEL_BUFFER_V1_SERVER_PROTOCOL_H + +#include +#include +#include "wayland-server.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct wl_client; +struct wl_resource; + +/** + * @page page_single_pixel_buffer_v1 The single_pixel_buffer_v1 protocol + * single pixel buffer factory + * + * @section page_desc_single_pixel_buffer_v1 Description + * + * This protocol extension allows clients to create single-pixel buffers. + * + * Compositors supporting this protocol extension should also support the + * viewporter protocol extension. Clients may use viewporter to scale a + * single-pixel buffer to a desired size. + * + * Warning! The protocol described in this file is currently in the testing + * phase. Backward compatible changes may be added together with the + * corresponding interface version bump. Backward incompatible changes can + * only be done by creating a new major version of the extension. + * + * @section page_ifaces_single_pixel_buffer_v1 Interfaces + * - @subpage page_iface_wp_single_pixel_buffer_manager_v1 - global factory for single-pixel buffers + * @section page_copyright_single_pixel_buffer_v1 Copyright + *
+ *
+ * Copyright © 2022 Simon Ser
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ * 
+ */ +struct wl_buffer; +struct wp_single_pixel_buffer_manager_v1; + +#ifndef WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_INTERFACE +#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_INTERFACE +/** + * @page page_iface_wp_single_pixel_buffer_manager_v1 wp_single_pixel_buffer_manager_v1 + * @section page_iface_wp_single_pixel_buffer_manager_v1_desc Description + * + * The wp_single_pixel_buffer_manager_v1 interface is a factory for + * single-pixel buffers. + * @section page_iface_wp_single_pixel_buffer_manager_v1_api API + * See @ref iface_wp_single_pixel_buffer_manager_v1. + */ +/** + * @defgroup iface_wp_single_pixel_buffer_manager_v1 The wp_single_pixel_buffer_manager_v1 interface + * + * The wp_single_pixel_buffer_manager_v1 interface is a factory for + * single-pixel buffers. + */ +extern const struct wl_interface wp_single_pixel_buffer_manager_v1_interface; +#endif + +/** + * @ingroup iface_wp_single_pixel_buffer_manager_v1 + * @struct wp_single_pixel_buffer_manager_v1_interface + */ +struct wp_single_pixel_buffer_manager_v1_interface { + /** + * destroy the manager + * + * Destroy the wp_single_pixel_buffer_manager_v1 object. + * + * The child objects created via this interface are unaffected. + */ + void (*destroy)(struct wl_client *client, + struct wl_resource *resource); + /** + * create a 1×1 buffer from 32-bit RGBA values + * + * Create a single-pixel buffer from four 32-bit RGBA values. + * + * Unless specified in another protocol extension, the RGBA values + * use pre-multiplied alpha. + * + * The width and height of the buffer are 1. + * + * The r, g, b and a arguments valid range is from UINT32_MIN (0) + * to UINT32_MAX (0xffffffff). + * + * These arguments should be interpreted as a percentage, i.e. - + * UINT32_MIN = 0% of the given color component - UINT32_MAX = 100% + * of the given color component + * @param r value of the buffer's red channel + * @param g value of the buffer's green channel + * @param b value of the buffer's blue channel + * @param a value of the buffer's alpha channel + */ + void (*create_u32_rgba_buffer)(struct wl_client *client, + struct wl_resource *resource, + uint32_t id, + uint32_t r, + uint32_t g, + uint32_t b, + uint32_t a); +}; + + +/** + * @ingroup iface_wp_single_pixel_buffer_manager_v1 + */ +#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_DESTROY_SINCE_VERSION 1 +/** + * @ingroup iface_wp_single_pixel_buffer_manager_v1 + */ +#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_CREATE_U32_RGBA_BUFFER_SINCE_VERSION 1 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/app/src/main/cpp/waylandcomp/protocols/single-pixel-buffer-v1.xml b/app/src/main/cpp/waylandcomp/protocols/single-pixel-buffer-v1.xml new file mode 100644 index 0000000000..bcbd0382eb --- /dev/null +++ b/app/src/main/cpp/waylandcomp/protocols/single-pixel-buffer-v1.xml @@ -0,0 +1,76 @@ + + + + Copyright © 2022 Simon Ser + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + This protocol extension allows clients to create single-pixel buffers. + + Compositors supporting this protocol extension should also support the + viewporter protocol extension. Clients may use viewporter to scale a + single-pixel buffer to a desired size. + + Warning! The protocol described in this file is currently in the testing + phase. Backward compatible changes may be added together with the + corresponding interface version bump. Backward incompatible changes can + only be done by creating a new major version of the extension. + + + + + The wp_single_pixel_buffer_manager_v1 interface is a factory for + single-pixel buffers. + + + + + Destroy the wp_single_pixel_buffer_manager_v1 object. + + The child objects created via this interface are unaffected. + + + + + + Create a single-pixel buffer from four 32-bit RGBA values. + + Unless specified in another protocol extension, the RGBA values use + pre-multiplied alpha. + + The width and height of the buffer are 1. + + The r, g, b and a arguments valid range is from UINT32_MIN (0) + to UINT32_MAX (0xffffffff). + + These arguments should be interpreted as a percentage, i.e. + - UINT32_MIN = 0% of the given color component + - UINT32_MAX = 100% of the given color component + + + + + + + + + diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index fbbd09886e..805eff9fa1 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -745,6 +745,21 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res if (ci && ci->asked_feedback) ci->shm_frames++; /* since it asked for GPU buffers */ } +/* A single-pixel buffer (wl_single_pixel.c) as a 1x1 image, which the surface's viewport stretches. */ +static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) { + if (s->shm_img && (vkp_image_width(s->shm_img) != 1 || vkp_image_height(s->shm_img) != 1)) { + vkp_image_destroy(s->shm_img); + s->shm_img = NULL; + } + if (!s->shm_img) s->shm_img = vkp_image_create_shm(1, 1); + if (s->shm_img) vkp_image_upload_shm(s->shm_img, bgra, 4); + wl_buffer_send_release(buffer); + s->buf_w = 1; + s->buf_h = 1; + s->buf_alpha = bgra[3] != 0xff; + s->has_content = s->shm_img != NULL; +} + /* The window the app's performance HUD follows: the latest one at least as big as the last to * start presenting GPU frames (take_dmabuf) (X11 binds the HUD to the _MESA_DRV window and counts X presents instead). JNI upcalls. */ static struct surface *g_hud_surface; @@ -1084,6 +1099,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { 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]; /* The previous content is replaced before reaching the screen. */ feedback_discard_all(&s->feedback); @@ -1113,6 +1129,9 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { } else if (shm) { drop_dmabuf(s, 1); take_shm(s, shm, buffer); + } else if (single_pixel_buffer_get(buffer, pixel)) { + drop_dmabuf(s, 1); + take_pixel(s, pixel, buffer); } else { drop_dmabuf(s, 1); s->has_content = 0; @@ -1661,15 +1680,24 @@ static void bind_desktop(struct wl_client *c, void *data, uint32_t ver, uint32_t static void output_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } static const struct wl_output_interface output_impl = { .release = output_release }; -static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { - struct wl_resource *r = wl_resource_create(c, &wl_output_interface, ver, id); - if (!r) { wl_client_post_no_memory(c); return; } - wl_resource_set_implementation(r, &output_impl, NULL, NULL); - wl_output_send_geometry(r, 0, 0, 340, 190, WL_OUTPUT_SUBPIXEL_UNKNOWN, - "DroidDeck", "Wayland", WL_OUTPUT_TRANSFORM_NORMAL); +/* Every bound wl_output, so a resized output (a foldable opening) can send its new mode. */ +static struct wl_list g_outputs; +static void output_resource_destroy(struct wl_resource *r) { wl_list_remove(wl_resource_get_link(r)); } + +static void output_send_mode(struct wl_resource *r) { wl_output_send_mode(r, WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED, g_output_w > 0 ? g_output_w : 1920, g_output_h > 0 ? g_output_h : 1080, g_output_refresh_mhz > 0 ? g_output_refresh_mhz : 60000); +} + +static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { + struct wl_resource *r = wl_resource_create(c, &wl_output_interface, ver, id); + if (!r) { wl_client_post_no_memory(c); return; } + wl_resource_set_implementation(r, &output_impl, NULL, output_resource_destroy); + wl_list_insert(&g_outputs, wl_resource_get_link(r)); + wl_output_send_geometry(r, 0, 0, 340, 190, WL_OUTPUT_SUBPIXEL_UNKNOWN, + "DroidDeck", "Wayland", WL_OUTPUT_TRANSFORM_NORMAL); + output_send_mode(r); if (ver >= WL_OUTPUT_NAME_SINCE_VERSION) { wl_output_send_name(r, "DroidDeck-1"); wl_output_send_description(r, "DroidDeck display"); @@ -3200,6 +3228,23 @@ static void key_event(uint32_t evdev, int pressed) { wl_display_flush_clients(g_display); } +/* The output changed size under a running session (a foldable opened or closed, with the + * session following the screen). Every client that has had its first configure is told the new + * size: gamescope's Wayland backend and the desktop's KWin both resize their output to it, and + * the next buffers they commit fill the new panel instead of being letterboxed onto it. */ +static void output_resized(void) { + struct surface *s; + struct wl_resource *r; + wl_resource_for_each(r, &g_outputs) { + output_send_mode(r); + if (wl_resource_get_version(r) >= 2) wl_output_send_done(r); + } + wl_list_for_each(s, &g_surfaces, link) + if (s->xdg_toplevel && s->toplevel_committed) send_toplevel_configure(s); + droiddeck_log("display", "output resized to %dx%d", g_output_w, g_output_h); + wl_display_flush_clients(g_display); +} + /* wl event-loop callback: drain queued input events written by the Android UI thread. */ static int on_input_readable(int fd, uint32_t mask, void *data) { struct input_msg m; @@ -3212,6 +3257,7 @@ static int on_input_readable(int fd, uint32_t mask, void *data) { case 5: on_vsync(((int64_t)m.p1 << 32) | (uint32_t)m.p2); break; case 6: pointer_delta(m.p1 / 256.0, m.p2 / 256.0); break; /* relative motion, 1/256 px */ case 7: deliver_touch(&m); break; + case 8: output_resized(); break; default: deliver_pointer(&m); break; } } @@ -3242,6 +3288,14 @@ void droiddeck_wayland_send_key(int evdev, int state) { (void)n; } +/* Called from JNI after g_output_w/h changed: the compositor thread re-sends the size. */ +void droiddeck_wayland_output_resized(void) { + if (g_input_pipe[1] < 0) return; + struct input_msg m = { 8, 0, 0, 0, 0 }; + ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); + (void)n; +} + /* Called from JNI on every screen refresh (Choreographer). */ void droiddeck_wayland_vsync(int64_t frame_time_ns) { if (g_input_pipe[1] < 0) return; @@ -3439,6 +3493,7 @@ static struct wl_listener g_client_created = { .notify = on_client_created }; int droiddeck_wayland_run(void) { wl_list_init(&g_surfaces); wl_list_init(&g_toplevels); + wl_list_init(&g_outputs); wl_list_init(&g_constraints); wl_list_init(&g_relative_pointers); open_session_log(); diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c index 74ddc6adaf..913f713d38 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c @@ -122,4 +122,5 @@ void droiddeck_ext_init(struct wl_display *display) { clipboard_init(display); text_input_init(display); toplevel_icon_init(display); + single_pixel_init(display); } diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h index e21014fbf5..0dc8ae41aa 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h @@ -48,3 +48,6 @@ void text_input_host_commit(const char *utf8, size_t len); void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end); void text_input_host_delete(int before, int after); void toplevel_icon_init(struct wl_display *display); +void single_pixel_init(struct wl_display *display); +/* A wp_single_pixel_buffer_manager_v1 buffer: 1 and its pixel (B, G, R, A, premultiplied), else 0. */ +int single_pixel_buffer_get(struct wl_resource *buffer, uint8_t bgra[4]); diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 3af9a8c254..4551c4806f 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -160,6 +160,11 @@ static const char *vk_result_name(VkResult r); static pthread_mutex_t g_req_lock = PTHREAD_MUTEX_INITIALIZER; static ANativeWindow *g_req_window; static int g_req_pending; +/* A detach was asked for since the compositor thread last looked. A rebind (null, then the same + * window) to rebuild the swapchain at a new size can land in full before the thread gets to it, + * and would otherwise read as the same window handed over again - nothing rebuilt, and the old + * size's buffers scaled onto the rotated or refolded panel. */ +static int g_req_detached; /* Scale mode + alignment (app values, see vk_present.h); written from any thread, read per frame. */ static volatile int g_mode = VKP_MODE_STRETCH, g_align = VKP_ALIGN_CENTER; @@ -252,6 +257,7 @@ void vk_present_set_window(ANativeWindow *window) { if (g_req_pending && g_req_window && g_req_window != window) superseded = g_req_window; g_req_window = window; g_req_pending = 1; + if (!window) g_req_detached = 1; pthread_mutex_unlock(&g_req_lock); if (superseded) ANativeWindow_release(superseded); } @@ -261,13 +267,20 @@ int vkp_apply_window_request(void) { pthread_mutex_lock(&g_req_lock); if (!g_req_pending) { pthread_mutex_unlock(&g_req_lock); return 0; } w = g_req_window; + const int detached = g_req_detached; g_req_window = NULL; g_req_pending = 0; + g_req_detached = 0; pthread_mutex_unlock(&g_req_lock); if (w == g_window) { /* The same window handed over again (ANativeWindow_fromSurface adds a reference each time). */ if (w) ANativeWindow_release(w); - return 0; + if (!w || !detached) return 0; + /* ... after a detach: a rebind for a resized surface. Rebuilt at its size on the next frame. */ + sc_layer_window_gone(); + destroy_swapchain(); + droiddeck_log("gpu", "screen surface rebound: rebuilding the swapchain at its new size"); + return 1; } sc_layer_window_gone(); /* the layer (if any) belongs to the old window */ destroy_swapchain(); /* recreated against the new window on the next frame */ @@ -1516,6 +1529,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i const struct vkp_hdr_frame *hf, int *how) { if (how) *how = 0; vkp_apply_window_request(); + check_surface_changed(); /* a rotation or a fold the rebind did not cover: rebuild at the new size */ if (g_dev_state == -2) return -1; if (dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1; @@ -2099,6 +2113,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw const struct vkp_hdr_frame *hf, int *rw, int *rh) { if (g_pass.active) vkp_pass_abort(); if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1; + check_surface_changed(); /* as in render_impl: the effects pass maps onto the output's size */ if (!g_swapchain && swap_init() != 0) return -1; /* the mapping is in output pixels */ update_map(scene_w, scene_h); if (!g_map.valid) return -1; diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 4d11a54192..8ec4b96b64 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -30,6 +30,7 @@ extern int droiddeck_cursor_serial(void); extern void droiddeck_wayland_send_key(int evdev, int state); extern void droiddeck_wayland_send_scene_input(int type, int a, int b); extern void droiddeck_wayland_vsync(int64_t frame_time_ns); +extern void droiddeck_wayland_output_resized(void); extern volatile int g_fps_limit; extern volatile int g_hide_shell; extern volatile int g_zero_copy; @@ -401,6 +402,17 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetOutputSize(JNIEnv g_output_h = h > 0 ? h : 0; } +/* The output's size changed while the compositor runs (a foldable opening or closing with the + * session following the screen): store it and have the compositor thread tell the clients. */ +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeResizeOutput(JNIEnv *env, jclass clazz, jint w, jint h) { + (void)env; (void)clazz; + if (w <= 0 || h <= 0) return; + g_output_w = w; + g_output_h = h; + droiddeck_wayland_output_resized(); +} + /* Fullscreen mode + screen alignment (Container.FULLSCREEN_* / ALIGN_* values): how the scene is * fitted onto the output. Any thread, any time; the next frame uses it. */ JNIEXPORT void JNICALL diff --git a/app/src/main/cpp/waylandcomp/src/wl_single_pixel.c b/app/src/main/cpp/waylandcomp/src/wl_single_pixel.c new file mode 100644 index 0000000000..9dfe78233c --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/wl_single_pixel.c @@ -0,0 +1,51 @@ +/* + * wp_single_pixel_buffer_manager_v1 (version 1): a wl_buffer of one pixel of one colour, which a + * client stretches over a surface with wp_viewporter. KWin's Wayland backend - the desktop's KWin + * nested in this compositor - refuses to start without it. The surface takes the pixel as a 1x1 + * image, the way it takes a wl_shm buffer (compositor.c, take_pixel). + */ +#include +#include "droiddeck_ext.h" +#include "single-pixel-buffer-v1-server-protocol.h" + +struct single_pixel { + uint8_t bgra[4]; /* premultiplied, as wl_shm's ARGB8888 lies in memory */ +}; + +static void buffer_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } +static const struct wl_buffer_interface buffer_impl = { .destroy = buffer_destroy }; + +static void buffer_free(struct wl_resource *r) { free(wl_resource_get_user_data(r)); } + +int single_pixel_buffer_get(struct wl_resource *buffer, uint8_t bgra[4]) { + if (!buffer || !wl_resource_instance_of(buffer, &wl_buffer_interface, &buffer_impl)) return 0; + struct single_pixel *p = wl_resource_get_user_data(buffer); + for (int i = 0; i < 4; i++) bgra[i] = p->bgra[i]; + return 1; +} + +static void mgr_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } +static void mgr_create_buffer(struct wl_client *c, struct wl_resource *r, uint32_t id, + uint32_t red, uint32_t green, uint32_t blue, uint32_t alpha) { + struct single_pixel *p = calloc(1, sizeof(*p)); + struct wl_resource *buffer = p ? wl_resource_create(c, &wl_buffer_interface, 1, id) : NULL; + if (!buffer) { free(p); wl_client_post_no_memory(c); return; } + /* The protocol's values span the whole u32 range; the top byte is the 8-bit channel. */ + p->bgra[0] = blue >> 24; + p->bgra[1] = green >> 24; + p->bgra[2] = red >> 24; + p->bgra[3] = alpha >> 24; + wl_resource_set_implementation(buffer, &buffer_impl, p, buffer_free); +} +static const struct wp_single_pixel_buffer_manager_v1_interface mgr_impl = { + .destroy = mgr_destroy, .create_u32_rgba_buffer = mgr_create_buffer, +}; +static void bind_manager(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { + struct wl_resource *r = wl_resource_create(c, &wp_single_pixel_buffer_manager_v1_interface, ver, id); + if (!r) { wl_client_post_no_memory(c); return; } + wl_resource_set_implementation(r, &mgr_impl, NULL, NULL); +} + +void single_pixel_init(struct wl_display *display) { + wl_global_create(display, &wp_single_pixel_buffer_manager_v1_interface, 1, NULL, bind_manager); +} diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 4271956465..e12aefb38d 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -22,12 +22,15 @@ class App : Application() { override fun onCreate() { super.onCreate() CrashHandler.install(this) - // Before anything else touches the session prefs, so the first session already runs in Deck mode. - com.droiddeck.launcher.session.SessionPrefs.settleDeckModeDefault(this) com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this) com.droiddeck.launcher.update.AppUpdates.init(this) GpuClockPin.clearLeftover(this) BwrapSpawner.start(this) com.droiddeck.launcher.frontend.GameFileSync.start(this) + // The game stores the Stores section can talk to; the native engine loads only when one needs it. + com.droiddeck.launcher.stores.StoresState.init(this) + com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend) + com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend) + com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend) } } diff --git a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt index 74c14f964a..7a6c60cbf5 100644 --- a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt @@ -14,6 +14,7 @@ class HomeActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this) routeHome() } diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index 0c101a51a5..1db0681286 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -10,6 +10,7 @@ import java.io.File import android.content.pm.PackageManager import android.hardware.display.DisplayManager import android.net.Uri +import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper @@ -17,6 +18,7 @@ import android.util.Log import android.view.Display import android.view.KeyEvent import android.view.View +import android.view.WindowManager import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts @@ -119,7 +121,6 @@ class MainActivity : ComponentActivity() { private var showNonAdreno by mutableStateOf(null) private var glThread by mutableStateOf(true) private var noGlError by mutableStateOf(true) - private var steamDeckMode by mutableStateOf(false) private var steamRepairQueued by mutableStateOf(false) private var mangoapp by mutableStateOf(true) private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK) @@ -139,6 +140,7 @@ class MainActivity : ComponentActivity() { private var pkgStage by mutableStateOf(null) private var pkgPercent by mutableIntStateOf(-1) private var desktopInstalled by mutableStateOf(false) + private var desktopPresent by mutableStateOf(false) private var offlineAccount by mutableStateOf(null) private var offline by mutableStateOf(false) private var showPerformance by mutableStateOf(false) @@ -161,9 +163,16 @@ class MainActivity : ComponentActivity() { private var showPhantomGate by mutableStateOf(false) private var directAudio by mutableStateOf(false) private var stretch16x9 by mutableStateOf(false) + private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) private var launcherFullscreen by mutableStateOf(true) private var animationsEnabled by mutableStateOf(true) private var storeEnabled by mutableStateOf(false) + private var gameStoresEnabled by mutableStateOf(false) + private var gameStoresSpeedTier by mutableStateOf("fast") + private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY) + /** A page a notification asked for ("stores:downloads", "app:"), until the front end has gone there. */ + private var navRequest by mutableStateOf(null) + private var storesShowMature by mutableStateOf(false) private var mic by mutableStateOf(false) private var wifiDiscovery by mutableStateOf(false) private var wifiDiscoveryPermission by mutableStateOf(false) @@ -295,29 +304,34 @@ class MainActivity : ComponentActivity() { GameSaves.savesDir().mkdirs() pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_saves_pick_folder, name, layout.label(this)), GameSaves.savesDir().path)) } - private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> - if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> - SessionPrefs.setAddedGamesDirs(this, addedGamesDirs + path) - addedGamesDirs = SessionPrefs.addedGamesDirs(this) - addedGamesArt = SessionPrefs.addedGamesArt(this) - refreshAddedGames() - refresh() - } + /** The Games tab's +: the picked .exe becomes a game (or selects / switches the one it belongs to). */ + private fun addGameExe(path: String) { + val exe = java.io.File(path) + Thread({ + val result = try { com.droiddeck.launcher.frontend.AddedGames.addExe(this, exe) } catch (e: Exception) { + Log.w(TAG, "add game: ${e.message}"); com.droiddeck.launcher.frontend.AddedGames.AddResult.NotFound + } + val game = when (result) { + is com.droiddeck.launcher.frontend.AddedGames.AddResult.Added -> result.game + is com.droiddeck.launcher.frontend.AddedGames.AddResult.Existing -> result.game + is com.droiddeck.launcher.frontend.AddedGames.AddResult.Switched -> result.game + else -> null + } + ui.post { + if (game == null) { + if (result is com.droiddeck.launcher.frontend.AddedGames.AddResult.Unreachable) + android.widget.Toast.makeText(this, R.string.games_add_unreachable, android.widget.Toast.LENGTH_LONG).show() + return@post + } + updateAddedGames(listOf(game.folder.path), then = { fetchAddedGameArt() }) + navRequest = "app:${game.steamAppId ?: game.appId.toInt()}" + } + }, "add-game-exe").start() } - private var pendingAddedGame: String? = null - private val pickAddedGameExe = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> - val folder = pendingAddedGame ?: return@registerForActivityResult - pendingAddedGame = null - if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> - SessionPrefs.setAddedGameExe(this, folder, path) - refreshAddedGames() - refresh() - } - } - private var addedGamesDirs by mutableStateOf>(emptyList()) private var addedGamesArt by mutableStateOf(true) @Volatile private var artFetchRunning = false - private var addedGames by mutableStateOf>(emptyList()) + /** The user entered a SteamGridDB API key of their own. */ + private var sgdbUserKey by mutableStateOf(false) private val pickRomsDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> SessionPrefs.setRomsDir(this, path) @@ -329,7 +343,6 @@ class MainActivity : ComponentActivity() { private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION) private var fexPreset by mutableStateOf("") private var forceSsbs by mutableStateOf(false) - private var steamChannel by mutableStateOf("steamdeck_publicbeta") private var runSteamAtStartup by mutableStateOf(false) private var theme by mutableStateOf("graphite") private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) @@ -343,7 +356,6 @@ class MainActivity : ComponentActivity() { private var steamDownloadsInBackground by mutableStateOf(false) private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO) private var backActionsInverted by mutableStateOf(false) - private var renderer by mutableStateOf("vulkan") private var gameStorage by mutableStateOf("") private var storageDiagnostics by mutableStateOf(false) private var storageOptions by mutableStateOf>(emptyList()) @@ -352,6 +364,8 @@ class MainActivity : ComponentActivity() { } private var romsDir by mutableStateOf(null) private var steamGames by mutableStateOf>(emptyList()) + @Volatile private var componentSweepDone = false + @Volatile private var componentSweepSession: String? = null private var emulatorList by mutableStateOf>(emptyList()) private var runningLabel by mutableStateOf(null) private var logsEnabled by mutableStateOf(true) @@ -437,6 +451,7 @@ class MainActivity : ComponentActivity() { } private fun readGameIntent(request: Intent) { + request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) } shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT if (shortcutPicker) { // The shortcut picker must only offer games from the scan started for this request. @@ -520,9 +535,15 @@ class MainActivity : ComponentActivity() { // Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it. steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this) backActionsInverted = SessionPrefs.backActionsInverted(this) + orientation = SessionPrefs.orientation(this) + requestedOrientation = orientation launcherFullscreen = SessionPrefs.launcherFullscreen(this) animationsEnabled = SessionPrefs.animationsEnabled(this) storeEnabled = SessionPrefs.storeEnabled(this) + gameStoresEnabled = SessionPrefs.gameStoresEnabled(this) + gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this) + storesOpenTab = SessionPrefs.storesOpenTab(this) + storesShowMature = SessionPrefs.storesShowMature(this) applyLauncherFullscreen() updates.start() setContent { @@ -545,7 +566,7 @@ class MainActivity : ComponentActivity() { shortcutLibraryScanning = shortcutLibraryScanning, gameSyncFolder = gameSyncFolder, busy = busy, stage = stage, percent = percent, - desktopInstalled = desktopInstalled, + desktopInstalled = desktopInstalled, desktopPresent = desktopPresent, offlineAccount = offlineAccount, offline = offline, frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, agentCommands = agentCommands, steamGames = steamGames, emulators = emulatorList, running = runningLabel, @@ -573,23 +594,54 @@ class MainActivity : ComponentActivity() { updates = updates.state(), phantomProcessStatus = phantomProcessStatus, showPhantomGate = showPhantomGate, + orientation = orientation, launcherFullscreen = launcherFullscreen, animationsEnabled = animationsEnabled, storeEnabled = storeEnabled, + gameStoresEnabled = gameStoresEnabled, + gameStoresSpeedTier = gameStoresSpeedTier, + storesOpenTab = storesOpenTab, + navigate = navRequest, + addedGamesArt = addedGamesArt, + sgdbUserKey = sgdbUserKey, + storesShowMature = storesShowMature, + storeDownloadsActive = com.droiddeck.launcher.stores.StoresState.activeDownloads, ), FrontEndActions( onPlay = { startSteamSession() }, - // Steam's desktop client as a window on the desktop: under gamescope the - // client puts itself into Big Picture whatever it is started with. + // The client's desktop UI, with gamescope's Deck integration disabled. onPlayDesktopUi = { startSession(Intent(this, SessionActivity::class.java) - .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP) + .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_STEAM) .putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true) }, - onSteamGame = { g -> if (shortcutPicker) chooseGameShortcut(g) else launchGame(g) }, + // A store game may need something done first (an Epic game its sign-in code). + onSteamGame = { g -> + if (shortcutPicker) chooseGameShortcut(g) + else { + // The launch takes the Windows components already on; the game's list is + // looked at again in the background once the session is over. + com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g) + com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) } + } + }, onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) }, onExportGameFile = { g -> pickGameExport(g) }, onSyncGameFiles = { pickGameExport(null) }, + onAddGameExe = { path -> addGameExe(path) }, + onAddedGamesChanged = { folders -> + // New games want art; an edit does not. + val known = steamGames.mapNotNull { it.gameFiles?.path }.toSet() + updateAddedGames(folders, then = { if (folders.any { it !in known }) fetchAddedGameArt() }) + }, + onAddedGameRemoved = { folder, appId, name -> removeAddedGame(folder, appId, name) }, + onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() }, + onSgdbKey = { key -> + Thread({ + com.droiddeck.launcher.frontend.SteamGridDb.setUserKey(this, key) + ui.post { sgdbUserKey = key.isNotBlank(); refreshAddedGames() } + }, "sgdb-key").start() + }, onStopGameFileSync = { Thread({ GameFileSync.disable(this) @@ -632,6 +684,7 @@ class MainActivity : ComponentActivity() { // The activity re-attaches to the session that is running; nothing restarts. onResume = { startActivity(Intent(this, SessionActivity::class.java)) }, onSteamSettings = { openModeSettings(SessionService.MODE_STEAM) }, + onRemoveDesktop = { removeDesktop() }, onDesktopSettings = { openModeSettings(SessionService.MODE_DESKTOP) }, onInstallPackage = { id -> installPackage(id) }, onRemovePackage = { id -> removePackage(id) }, @@ -696,12 +749,23 @@ class MainActivity : ComponentActivity() { com.droiddeck.launcher.core.AppUiPrefs.setScale(this, percent) appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this) }, + onOrientation = { value -> + SessionPrefs.setOrientation(this, value) + orientation = value + requestedOrientation = value + }, onLauncherFullscreen = { on -> SessionPrefs.setLauncherFullscreen(this, on) launcherFullscreen = on applyLauncherFullscreen() }, onStoreEnabled = { on -> SessionPrefs.setStoreEnabled(this, on); storeEnabled = on }, + onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on; if (on) com.droiddeck.launcher.stores.StoresState.refresh(this) }, + 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 }, + onLibraryChanged = { refreshAddedGames(); refresh() }, onAnimationsEnabled = { on -> SessionPrefs.setAnimationsEnabled(this, on) animationsEnabled = on @@ -779,6 +843,7 @@ class MainActivity : ComponentActivity() { onSteamButton = { on -> ControllerPrefs.setSteamButton(this, on); refreshController() }, onQamButton = { on -> ControllerPrefs.setQamButton(this, on); refreshController() }, onKeyboardButton = { on -> ControllerPrefs.setKeyboardButton(this, on); refreshController() }, + onSelectSteam = { on -> ControllerPrefs.setSelectSteam(this, on); refreshController() }, onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) }, onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() }, onMapping = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = true }, @@ -843,8 +908,13 @@ class MainActivity : ComponentActivity() { SessionPrefs.setMicAsked(this) } if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1) + // A store sign-in an earlier build left in plain text is sealed with the Keystore key. + Thread({ com.droiddeck.launcher.stores.StoreAccounts.encryptAll(this) }, "store-credentials").start() // A session folder left without its ending - the process was killed - gets it now. if (!SessionState.running) Thread({ + com.droiddeck.launcher.session.LogMigration.run(this) + com.droiddeck.launcher.frontend.GamesFolderMigration.run(this) + SessionLogShare.clear(this) SessionArtifacts.finishAbandoned(this) SessionArtifacts.scrubOlder(this) SessionArtifacts.prune(this) @@ -885,10 +955,20 @@ class MainActivity : ComponentActivity() { } else { View.SYSTEM_UI_FLAG_LAYOUT_STABLE } + if (Build.VERSION.SDK_INT >= 28) { + window.attributes = window.attributes.apply { + layoutInDisplayCutoutMode = if (launcherFullscreen) { + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + } else { + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT + } + } + } } /** On the Components page the pad's LB / RB step through GPU drivers, FEX, DXVK and VKD3D-Proton, wrapping around. */ override fun dispatchKeyEvent(event: KeyEvent): Boolean { + 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) { val all = listOf(com.droiddeck.launcher.ui.GPU_TAB) + ComponentsManager.COMPONENTS @@ -897,12 +977,26 @@ class MainActivity : ComponentActivity() { } return true } - return super.dispatchKeyEvent(event) + // Compose throws when its focus tree has lost the focused node; one key is dropped + // instead of the app. + return try { + super.dispatchKeyEvent(event) + } catch (e: IllegalStateException) { + if (e.message?.contains("active focus target") != true) throw e + android.util.Log.w("MainActivity", "key ${event.keyCode} dropped: ${e.message}") + true + } } override fun onResume() { super.onResume() + orientation = SessionPrefs.orientation(this) + requestedOrientation = orientation refreshWifiDiscovery() + // Back from a store's sign-in page: the Stores chips show the account at once. A store + // install finishing while this screen is up rebuilds the Games list through the listener. + if (gameStoresEnabled) com.droiddeck.launcher.stores.StoresState.refresh(this) + com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() } com.droiddeck.launcher.ui.Motion.refresh(this) // Back from a session stopped behind a flood: open on its blue, before the first frame. com.droiddeck.launcher.ui.QuitFlood.take()?.let { c -> @@ -960,6 +1054,8 @@ class MainActivity : ComponentActivity() { unregisterReceiver(wifiLocationReceiver) unregisterReceiver(mediaReceiver) ui.removeCallbacks(mediaRefresh) + // An install finishing while this screen is away is picked up by onResume's refresh. + com.droiddeck.launcher.stores.StoresState.libraryListener = null displayManager.unregisterDisplayListener(secondScreenDisplayListener) // The session covers the page by now; coming back finds it as it was. flood = null @@ -1136,6 +1232,7 @@ class MainActivity : ComponentActivity() { private fun refreshPackages() { packageRows = catalog?.map { PackageRow(it.id, it.kind, it.notes) } desktopInstalled = DesktopCatalog.desktopInstalled(this) + desktopPresent = DesktopCatalog.desktopPresent(this) } private fun launchProgram(path: String) { @@ -1189,20 +1286,19 @@ class MainActivity : 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, oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null, backActionsInverted = backActionsInverted, directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null, stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null, mic = if (mode == SessionService.MODE_STEAM) mic else null, - renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null, gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null, storageOptions = storageOptions, 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, - steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null, - steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode, steamRepairQueued = steamRepairQueued, mangoapp = mangoapp, steamController = if (mode == SessionService.MODE_STEAM) steamController else null, @@ -1212,9 +1308,6 @@ class MainActivity : ComponentActivity() { wifiDiscoveryLocation = wifiDiscoveryLocation, wifiDiscoveryAsked = wifiDiscoveryAsked, wifiDiscoveryBlocked = wifiDiscoveryBlocked, - addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null, - addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(), - addedGamesArt = addedGamesArt, deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null, deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null, deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent, @@ -1250,6 +1343,7 @@ class MainActivity : ComponentActivity() { steamDownloadsInBackground = enabled }, onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on }, + onUnfoldedControls = { on -> SessionPrefs.setUnfoldedControls(this, on); unfoldedControls = on }, onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o }, onBackActionsInverted = { inverted -> SessionPrefs.setBackActionsInverted(this, inverted) @@ -1266,7 +1360,6 @@ class MainActivity : ComponentActivity() { requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 2) } }, - onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r }, onGameStorage = { path, label -> setGameStorage(path, label) }, onPickGameStorageFolder = { pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_game_storage), gameStorage.ifEmpty { null })) @@ -1283,27 +1376,13 @@ class MainActivity : ComponentActivity() { fsyncFirst = SessionPrefs.fsyncFirst(this) syncFallback = SessionPrefs.syncFallback(this) }, - onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id }, onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) }, - onSteamDeckMode = { on -> - SessionPrefs.setSteamDeckMode(this, on) - steamDeckMode = on - steamChannel = SessionPrefs.steamChannel(this) - }, onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on }, onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id }, onRunSteamAtStartup = { on -> SessionPrefs.setRunSteamAtStartup(this, on) runSteamAtStartup = on }, - onPickAddedGamesDir = { pickAddedGamesDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_added_games), addedGamesDirs.lastOrNull())) }, - onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() }, - onForgetAddedGamesDir = { dir -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs - dir); addedGamesDirs = SessionPrefs.addedGamesDirs(this); refreshAddedGames(); refresh() }, - onAddedGameExe = { folder, path -> SessionPrefs.setAddedGameExe(this, folder, path); refreshAddedGames(); refresh() }, - onPickAddedGameExe = { folder -> - pendingAddedGame = folder - pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), getString(R.string.main_pick_game_exe), folder)) - }, onDeckyInstall = { release -> decky.installDecky(release) }, onDeckyCheck = { decky.refreshDecky() }, onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); decky.deckySupervisor = enabled }, @@ -1358,18 +1437,44 @@ class MainActivity : ComponentActivity() { ) } - /** The added games as the settings page lists them; a scan of the folder, on this thread (one level, small). */ - /** The added games for the session settings: a folder walk, so off the main thread. */ - private fun refreshAddedGames() { + /** + * The Games tab after these added games were added or edited: each read alone and put in + * place of its old entry (or added), no library-wide scan. [then] runs after, on the main thread. + */ + private fun updateAddedGames(folders: List, then: () -> Unit = {}) { + if (folders.isEmpty()) return Thread({ - val games = scanAddedGames() - ui.post { addedGames = games; fetchAddedGameArt() } - }, "added-games").start() + val fresh = folders.mapNotNull { f -> + com.droiddeck.launcher.frontend.AddedGames.single(this, f)?.let { com.droiddeck.launcher.frontend.Library.addedGame(this, it) } + } + // An added or edited game's Windows components, from its source's list. + fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.refreshLater(this, it) } + ui.post { + val paths = folders.toSet() + steamGames = (steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path in paths } + fresh).distinctBy { it.gameId } + then() + } + }, "added-games-update").start() } - /** Walks the added-games folders, which can sit on slow shared storage or an SD card. */ - private fun scanAddedGames() = com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g -> - com.droiddeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, (g.candidates + g.exe).map { c -> c.path to c.name }.distinctBy { it.first }) + /** An added game removed: off the Games tab now; the rest (cache, Steam, listing) off the main thread. */ + private fun removeAddedGame(folder: String, appId: Long?, name: String) { + steamGames = steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path == folder } + Thread({ com.droiddeck.launcher.frontend.AddedGames.remove(this, java.io.File(folder), appId, name) }, "added-game-remove").start() + } + + /** After the added games changed: art that is missing is fetched (off the main thread). */ + private fun refreshAddedGames() { + sgdbKeyKnown() + fetchAddedGameArt() + } + + /** Whether the user has a SteamGridDB key of their own, for Setup; read off the main thread. */ + private fun sgdbKeyKnown() { + Thread({ + val set = com.droiddeck.launcher.frontend.SteamGridDb.userKey(this).isNotEmpty() + ui.post { sgdbUserKey = set } + }, "sgdb-key-state").start() } private fun fetchAddedGameArt() { @@ -1389,9 +1494,11 @@ class MainActivity : ComponentActivity() { } private var pipAutoEnter by mutableStateOf(false) + private var unfoldedControls by mutableStateOf(false) private fun openModeSettings(mode: String) { pipAutoEnter = SessionPrefs.pipAutoEnter(this) + unfoldedControls = SessionPrefs.unfoldedControls(this) showPerformance = false showProtons = false showComponents = false @@ -1402,13 +1509,10 @@ class MainActivity : ComponentActivity() { fastSync = SessionPrefs.fastSync(this) fsyncFirst = SessionPrefs.fsyncFirst(this) syncFallback = SessionPrefs.syncFallback(this) - steamChannel = SessionPrefs.steamChannel(this) - steamDeckMode = SessionPrefs.steamDeckMode(this) steamRepairQueued = SteamRepair.queued(this) mangoapp = SessionPrefs.mangoapp(this) steamController = SessionPrefs.steamController(this) runSteamAtStartup = SessionPrefs.runSteamAtStartup(this) - addedGamesDirs = SessionPrefs.addedGamesDirs(this) hdrOn = SessionPrefs.hdr(this, mode) fpsLimit = SessionPrefs.fpsLimit(this, mode) upscaler = SessionPrefs.upscaler(this) @@ -1423,7 +1527,6 @@ class MainActivity : ComponentActivity() { stretch16x9 = SessionPrefs.stretch16x9(this) mic = SessionPrefs.micEnabled(this) refreshWifiDiscovery() - renderer = SessionPrefs.desktopRenderer(this) gameStorage = SessionPrefs.gameStorage(this) storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this) settingsMode = mode @@ -1431,12 +1534,10 @@ class MainActivity : ComponentActivity() { // added-games folders, the storage volumes) lands while it animates in. Thread({ drivers.refreshDrivers() - val games = scanAddedGames() val storage = GameStorage.options(this) val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this) ui.post { - addedGames = games storageOptions = storage if (mode == SessionService.MODE_STEAM) { decky.deckyInstalled = deckyInstalled @@ -1466,7 +1567,6 @@ class MainActivity : ComponentActivity() { clientOverride = SessionPrefs.clientCpusOverride(this) glThread = SessionPrefs.glThread(this) noGlError = SessionPrefs.noGlError(this) - steamDeckMode = SessionPrefs.steamDeckMode(this) clientCores = CpuCores.parse(SessionPrefs.clientCpus(this)).ifEmpty { CpuCores.all.toSet() } gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() } tuSysmem = SessionPrefs.tuSysmem(this) @@ -1485,7 +1585,9 @@ class MainActivity : ComponentActivity() { private fun refresh() { if (!busy && LinuxRuntimeInstaller.isBusy()) followRuntimeOperation { LinuxRuntimeInstaller.attach(it) } + addedGamesArt = SessionPrefs.addedGamesArt(this) desktopInstalled = DesktopCatalog.desktopInstalled(this) + desktopPresent = DesktopCatalog.desktopPresent(this) offlineAccount = OfflineMode.account(this) offline = OfflineMode.enabled(this) installed = LinuxRuntimeInstaller.installedVersion(this) @@ -1505,13 +1607,39 @@ class MainActivity : ComponentActivity() { val scanGeneration = ++libraryScanGeneration if (shortcutPicker) shortcutLibraryScanning = true Thread({ - // One update with the whole list: the wall places games by their position in it, so a - // partial list first would shuffle every capsule when the rest arrived. LibraryCache - // covers the wait. + // Steam's own games first, from their manifests alone (quick), beside the added games + // already listed: a game Steam installed during the session shows as the session ends, + // without waiting for the added games' walk below. Its Windows components' list is + // queued then too, on the low-priority worker, so its page is usually ready. + if (ready) { + val quick = runCatching { Library.steamGames(this) }.getOrNull() + if (quick != null) ui.post { + if (scanGeneration == libraryScanGeneration && steamGames.isNotEmpty()) { + val before = steamGames.map { it.gameId }.toSet() + val fresh = quick.filter { it.gameId !in before } + if (fresh.isNotEmpty()) { + steamGames = (quick + steamGames.filter { it.library == Library.ADDED }).distinctBy { it.gameId } + fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.queueGame(this, it, asked = false) } + } + } + } + } + // Then one update with the whole list: the wall places games by their position in it, + // so a partial list first would shuffle every capsule when the rest arrived. + // LibraryCache covers the wait. val games = if (ready) Library.launchableGames(this) else emptyList() val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null } val all = games.distinctBy { it.gameId } if (ready) com.droiddeck.launcher.frontend.LibraryCache.save(this, all) + // Once per app start: the Steam games' Windows components from Steam's lists. + // Queued only, after the launcher has been up a little; the worker takes them one at a time. + // And again after each session (a game installed in it, files changed). + val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession } + if (ready && (!componentSweepDone || endedSession != null)) { + componentSweepDone = true + endedSession?.let { componentSweepSession = it } + ui.postDelayed({ Thread({ com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all) }, "components-sweep").start() }, 10_000) + } ui.post { if (scanGeneration == libraryScanGeneration) { steamGames = all @@ -1598,6 +1726,15 @@ class MainActivity : ComponentActivity() { protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null || components.compBusy != null || saveBusy != null || com.droiddeck.launcher.store.UserAppsState.working != null + private fun removeDesktop() { + if (runtimeChangesBlocked()) return + val operation = LinuxRuntimeInstaller.beginMaintenance(this, getString(R.string.desktop_removing)) ?: return + com.droiddeck.launcher.runtime.RuntimeInstallService.keepRemovalAlive(this) + followRuntimeOperation { listener -> + operation.run(listener) { progress -> DesktopCatalog.removeDesktop(this, progress) } + } + } + private fun removeRuntime() { if (runtimeChangesBlocked()) return val removal = LinuxRuntimeInstaller.beginUninstall(this) ?: return @@ -1620,7 +1757,7 @@ class MainActivity : ComponentActivity() { private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) { busy = true failed = false - stage = getString(if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting) + stage = getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting) percent = -1 Thread({ val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p -> diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 2e9be51934..97c408b8c4 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -19,6 +19,7 @@ import android.view.MotionEvent import android.view.ViewConfiguration import android.view.Display import android.view.SurfaceHolder +import android.view.Gravity import android.view.SurfaceView import android.view.View import android.view.WindowManager @@ -51,6 +52,7 @@ 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.SteamControllerBle import com.droiddeck.launcher.input.PointerGestures import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenDisplays @@ -109,6 +111,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private lateinit var pip: com.droiddeck.launcher.session.SessionPipController private var pipUi by mutableStateOf(false) private var pipAutoEnter by mutableStateOf(false) + /** Unfolded controls: the setting, and the Deck controls under the game while they show. */ + private var unfoldedControls by mutableStateOf(false) + private var unfoldedPanel: com.droiddeck.launcher.ui.DeckControlsPanel? = null + private lateinit var sessionRoot: FrameLayout private val guestKeysDown = mutableSetOf() private lateinit var surfaceView: SurfaceView private lateinit var sessionOverlay: ComposeView @@ -119,7 +125,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var padMotion: com.droiddeck.launcher.input.PadMotion? = null /** Between onResume and onPause. */ private var resumed = false - private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion(); openDeckRing("deck pad changed") } } + private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion(); openDeckRing("deck pad changed"); applyUnfoldedControls() } } /** * A Deck's controller is there from the moment it boots, and the client looks for it once, as @@ -142,9 +148,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { /** Motion is read while the session shows and only if the pad is a Deck controller - which * the service can decide after this activity has resumed (SessionState.deckPadListener). */ private fun updatePadMotion() { - if (resumed && !pipUi && SessionState.deckPad) padMotion?.start() else padMotion?.stop() + // A Steam Controller brings its own gyro (SteamControllerBle); the phone's would fight it. + if (resumed && !pipUi && SessionState.deckPad && !SteamControllerBle.connected) padMotion?.start() + else padMotion?.stop() } + private var steamController: SteamControllerBle? = null private var onScreenControls: OnScreenControls? = null + /** Steam's touch controls (SteamTouchControls), made once the session offers the device. */ + private var steamTouchControls: com.droiddeck.launcher.input.SteamTouchControls? = null + private var steamTouchAvailable by mutableStateOf(false) + private val steamTouchRetry = Runnable { updateOnScreenControls() } + /** While Steam's touch controls are up: how the game's touch config says touches outside them + * act (Steam Link's input and mouse modes), in place of the drawer's touch mode. */ + private var steamTouchOptions: com.droiddeck.launcher.input.SteamTouchConfig.Options? = null + /** The touch mode touches are routed by: the drawer's, or the game's while Steam's controls are up. */ + private var routedTouchMode = SessionPrefs.TOUCH_AUTO private var keyboard: KeyboardHost? = null private var controllerSettings by mutableStateOf(null) private val sessionClipboard by lazy { @@ -232,6 +250,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER) private var drawerControllerActive by mutableStateOf(false) private var backActionsInverted by mutableStateOf(false) + /** What the pad is to the Steam client (SessionPrefs.CONTROLLER_*), switched from the drawer. */ + private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK) /** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */ private var pcKeyboardOpen by mutableStateOf(false) private var hudOn by mutableStateOf(true) @@ -295,6 +315,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onInputDeviceRemoved(deviceId: Int) { Log.i(TAG, "input device $deviceId disconnected") + padBridge?.onDeviceRemoved(deviceId) updateOnScreenControls() updatePointerCapture() } @@ -305,7 +326,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving()) { + requestedOrientation = SessionPrefs.orientation(this) + if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() || + com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isMaintaining()) { runtimeRemovalBlocked = true android.widget.Toast.makeText(this, R.string.session_wait_removal, android.widget.Toast.LENGTH_SHORT).show() finish() @@ -336,6 +359,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { ) } Log.i(TAG, "perf: " + PerfMode.apply(this, SessionState.fpsLimit)) + if (!SessionState.running) SessionState.followScreen = followChoice() + applyFollowOrientation(resources.configuration) goFullscreen() // The device's volume keys change the stream the session plays on (the relay and // PulseAudio are media playback); they are never forwarded to the guest. @@ -357,13 +382,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { Log.i(TAG, "pointer capture " + if (hasCapture) "on" else "off") } } + sessionRoot = root surfaceView = SurfaceView(this) surfaceView.holder.addCallback(this) root.addView(surfaceView) + // The window's size is only known once laid out, and changes as the phone folds or turns. + root.addOnLayoutChangeListener { _, l, t, r, b, ol, ot, or, ob -> + if (r - l != or - ol || b - t != ob - ot) uiHandler.post { applyUnfoldedControls() } + } val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input")) + bridge.setSelectSteam(ControllerPrefs.read(this).selectSteam) padBridge = bridge SessionState.padBridge = bridge + // A paired Steam Controller is read over Bluetooth LE, out of lizard mode, as Steam Link reads it. + SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); updateOnScreenControls() } } + steamController = SteamControllerBle(this).also { it.start() } padMotion = com.droiddeck.launcher.input.PadMotion(this) { @Suppress("DEPRECATION") (if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0 @@ -555,12 +589,30 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onKeyboardButton = { on -> updateControllerPrefs { ControllerPrefs.setKeyboardButton(this@SessionActivity, on) } }, onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null, onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null, + // Only where the session set the pad up to be switched (SessionService: deckPad). + padType = if (SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad) padType else null, + onPadType = { id -> + SessionPrefs.setSteamController(this@SessionActivity, id) + com.droiddeck.launcher.session.SteamDeckPad.showPad(SessionPrefs.padType(id)) + com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(id)) + padType = id + }, backActionsInverted = backActionsInverted, onBackActionsInverted = { inverted -> SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted) backActionsInverted = inverted }, - onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() }, + onOsc = { v -> + SessionPrefs.setOscMode(this@SessionActivity, v) + readPrefs() + updateOnScreenControls() + if (v == SessionPrefs.OSC_STEAM_TOUCH && com.droiddeck.launcher.input.SteamTouchDevice.current == null) + Toast.makeText(this@SessionActivity, R.string.osc_style_next_session, Toast.LENGTH_LONG).show() + }, + onEditSteamTouch = if (steamTouchAvailable && oscMode == SessionPrefs.OSC_STEAM_TOUCH && onScreenButtonsVisible) ({ + drawerOpen = false + steamTouchControls?.startEditing() + }) else null, onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy) suspendPolicy = policy @@ -597,6 +649,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { pipAutoEnter = on pip.refresh(true) }, + unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null, + onUnfoldedControls = ::chooseUnfoldedControls, onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) }, onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() }, onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() }, @@ -743,9 +797,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } private fun loadingTitle(): String = when (loadingMode()) { - SessionService.MODE_DESKTOP -> - if (!SessionState.running && intent.getStringExtra(SessionService.EXTRA_STEAM_UI) != null) getString(R.string.session_starting_steam_desktop) - else getString(R.string.session_starting_desktop) + // Also when the desktop was asked for with Steam (Big Picture's Switch to Desktop): the client + // does not open on it. + SessionService.MODE_DESKTOP -> getString(R.string.session_starting_desktop) SessionService.MODE_RUN -> { val program = if (SessionState.running) SessionState.program else intent.getStringExtra(SessionService.EXTRA_PROGRAM) com.droiddeck.launcher.frontend.Library.nameForProgram(program)?.let { getString(R.string.session_starting_named, it) } @@ -777,6 +831,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun readPrefs() { pipAutoEnter = SessionPrefs.pipAutoEnter(this) + unfoldedControls = SessionPrefs.unfoldedControls(this) hudOn = SessionPrefs.hudEnabled(this) upscaler = SessionPrefs.upscaler(this) upscaleSharpness = SessionPrefs.upscaleSharpness(this) @@ -792,15 +847,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { WaylandCompositor.nativeSendSceneInput(3, it, 0) } } - if (nextTouchMode == SessionPrefs.TOUCH_OFF) cursorVisible = false + if (nextTouchMode == SessionPrefs.TOUCH_OFF || !usingTouchpad()) cursorVisible = false } touchMode = nextTouchMode + routedTouchMode = effectiveTouchMode() frameGen = FrameGen.mode(this) fexPreset = SessionPrefs.fexPreset(this) suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this) oscMode = SessionPrefs.oscMode(this) backActionsInverted = SessionPrefs.backActionsInverted(this) + padType = SessionPrefs.steamController(this) } // ── Compositor ────────────────────────────────────────────────────────────────────────── @@ -927,8 +984,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { /** Null when the desktop package is in, else the loading screen's closing line. */ private fun installDesktop(): String? { uiHandler.post { loading.percent = -1; loading.say(getString(DESKTOP_LINES.downloading), DESKTOP_LINES.topic, readable = true) } - val entry = com.droiddeck.launcher.runtime.DesktopCatalog.fetch()?.firstOrNull { it.id == "desktop" } - ?: return getString(R.string.session_desktop_catalog_unreachable) + val entry = com.droiddeck.launcher.runtime.DesktopCatalog.desktopEntry(this) val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry, progressFor(DESKTOP_LINES, entry.size / 1_000_000)) return problem?.let { getString(R.string.session_desktop_install_failed, it) } @@ -962,7 +1018,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // sized once when the session starts and cannot change. A foldable recreates the Surface // on the other panel, and recomputing the size there told the compositor a 21:9 buffer // was 16:9 - the picture came back squashed sideways. While a session runs, keep its size. - val size = if (SessionState.running) SessionState.outputSize else outputSize() + // Follow screen is the exception: there the compositor tells gamescope the new size, so the + // session takes the shape of the Surface it now has. + val previous = SessionState.outputSize + val live = if (SessionState.followScreen && !isInPictureInPictureMode) + com.droiddeck.launcher.session.SessionDisplay.followSize(holder.surfaceFrame.width(), holder.surfaceFrame.height()) + else null + val size = live ?: if (SessionState.running) previous else outputSize() SessionState.outputSize = size if (!SessionState.running) SessionState.refreshHz = refreshHz() // How far the panel enlarges the session, for texture sharpness "Auto" (TextureFiltering): @@ -1021,6 +1083,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) }, applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), SessionState.fpsLimit, ) + if (SessionState.running && size != previous) { + Log.i(TAG, "follow screen: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface") + WaylandCompositor.nativeResizeOutput(size.first, size.second) + } if (!SessionState.running) SessionEvents.record("compositor.started") // The service owns everything below the compositor. It is started whenever no session is // running - NOT only when the compositor was just started: the compositor lives for the @@ -1049,9 +1115,52 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (resized) { Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor") CompositorHost.resize(holder.surface) { applyFrameGen() } + followWindow(width, height) } } + /** + * Follow screen: the session's display takes the window's new size (a Fold opening onto its + * inner panel, or closing onto the cover), so the picture fills the panel instead of being + * letterboxed onto it. Not in picture-in-picture: that window is a preview of the session, + * and resizing the guest to it would leave Steam laid out for a thumbnail. + */ + private fun followWindow(width: Int, height: Int) { + if (!SessionState.followScreen || isInPictureInPictureMode || !CompositorHost.isStarted) return + val size = com.droiddeck.launcher.session.SessionDisplay.followSize(width, height) ?: return + if (size == SessionState.outputSize) return + Log.i(TAG, "follow screen: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}") + SessionState.outputSize = size + val panel = panelBounds() + SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1) + WaylandCompositor.nativeResizeOutput(size.first, size.second) + } + + /** Whether this session's resolution is Follow screen; decided once, when it starts. */ + private fun followChoice(): Boolean { + val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) + return SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) == + com.droiddeck.launcher.session.SessionDisplay.FOLLOW_SCREEN + } + + /** + * Follow screen on a large panel (a Fold's inner screen) may turn with the device: a window + * locked to landscape on a squarer panel is letterboxed by the system itself, which no output + * size can undo. A phone-sized panel (the cover screen) stays landscape as before. + */ + private fun applyFollowOrientation(config: android.content.res.Configuration) { + if (!SessionState.followScreen) return + val wanted = if (config.smallestScreenWidthDp >= 600) android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER + else android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + if (requestedOrientation != wanted) requestedOrientation = wanted + } + + override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { + super.onConfigurationChanged(newConfig) + applyFollowOrientation(newConfig) + applyUnfoldedControls() + } + override fun surfaceDestroyed(holder: SurfaceHolder) { surfaceW = 0 surfaceH = 0 @@ -1277,7 +1386,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { return super.dispatchKeyEvent(event) } if (pipUi) return true - val fromController = event.device != null && PadBridge.isFromController(event.device) + val fromController = PadBridge.isControllerKeyEvent(event) if (fromController && event.action == KeyEvent.ACTION_DOWN) { if (drawerOpen && !drawerControllerActive) sessionOverlay.requestFocus() drawerControllerActive = true @@ -1329,12 +1438,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } return true } - if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchKeyEvent(event) + if (pcKeyboardOpen && fromController) return super.dispatchKeyEvent(event) if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true // A hardware keyboard, forwarded to the compositor's wl_keyboard. Back is left to the // activity, which opens the drawer. - val fromPad = event.device != null && PadBridge.isFromController(event.device) - if (CompositorHost.isStarted && event.keyCode != KeyEvent.KEYCODE_BACK && !fromPad) { + if (CompositorHost.isStarted && event.keyCode != KeyEvent.KEYCODE_BACK && !fromController) { val down = event.action == KeyEvent.ACTION_DOWN if (down || event.action == KeyEvent.ACTION_UP) { var evdev = EvdevKeys.fromKeyCode(event.keyCode) @@ -1372,7 +1480,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { if (pipUi) return true - if (drawerOpen && event.device != null && PadBridge.isFromController(event.device)) { + if (drawerOpen && PadBridge.isControllerMotionEvent(event)) { if (!drawerControllerActive) sessionOverlay.requestFocus() drawerControllerActive = true if (event.actionMasked == MotionEvent.ACTION_MOVE && @@ -1383,7 +1491,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { return true } if (drawerDirectionKey != KeyEvent.KEYCODE_UNKNOWN) releaseDrawerDirection() - if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event) + if (pcKeyboardOpen && PadBridge.isControllerMotionEvent(event)) return super.dispatchGenericMotionEvent(event) if (padBridge?.onMotionEvent(event) == true) return true if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true return super.dispatchGenericMotionEvent(event) @@ -1607,17 +1715,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { WaylandCompositor.nativeSendSceneInput(3, button, if (pressed) 1 else 0) }, sendWheel = { steps -> WaylandCompositor.nativeSendSceneInput(4, steps, 0) }, - onSteamMenu = { - if (SessionState.mode == SessionService.MODE_STEAM) { - padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) } - Handler(Looper.getMainLooper()).postDelayed({ - padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, false) } - }, 90) - } - }, - onQam = { - if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam() - }, + onSteamMenu = ::tapSteamButton, + onQam = ::tapQam, onClose = { selectSecondScreenMode(SecondScreenMode.NONE) }, ) secondScreenPresentation = presentation @@ -1634,6 +1733,64 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } + private fun tapSteamButton() { + if (SessionState.mode == SessionService.MODE_STEAM) { + padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) } + Handler(Looper.getMainLooper()).postDelayed({ + padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, false) } + }, 90) + } + } + + private fun tapQam() { + if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam() + } + + private fun chooseUnfoldedControls(on: Boolean) { + SessionPrefs.setUnfoldedControls(this, on) + unfoldedControls = on + applyUnfoldedControls() + } + + /** + * Unfolded controls: on a foldable's inner screen, the game above and the Steam Deck controller's + * trackpads and back grips below ([com.droiddeck.launcher.ui.DeckControlsPanel], as a second + * screen shows them, plus a whole gamepad). The on-screen pad is hidden meanwhile. The surface shrinks to the top part, so a Follow screen session resizes + * to it and any other is fitted into it. Folded onto the cover screen - a phone-sized panel - + * or in picture-in-picture, the game is full screen again. + */ + private fun applyUnfoldedControls() { + if (!::sessionRoot.isInitialized) return + val width = sessionRoot.width + val height = sessionRoot.height + val wanted = unfoldedControls && com.droiddeck.launcher.session.SessionDisplay.foldable(this) && + SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad && + !pipUi && !isInPictureInPictureMode && width > 0 && height > 0 && + resources.configuration.smallestScreenWidthDp >= com.droiddeck.launcher.session.SessionDisplay.UNFOLDED_MIN_DP + val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height) + else FrameLayout.LayoutParams.MATCH_PARENT + val params = surfaceView.layoutParams as FrameLayout.LayoutParams + if (params.height != gameHeight) { + surfaceView.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, gameHeight, Gravity.TOP) + Log.i(TAG, if (wanted) "unfolded controls: game ${width}x$gameHeight, controls ${width}x${height - gameHeight}" + else "unfolded controls: game full screen") + } + var panel = unfoldedPanel + if (!wanted) { + if (panel != null) { sessionRoot.removeView(panel); unfoldedPanel = null; updateOnScreenControls() } + return + } + if (panel == null) { + panel = com.droiddeck.launcher.ui.DeckControlsPanel(this, onClose = { chooseUnfoldedControls(false) }, + onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge) + // Just above the surface: the on-screen pad, keyboard and drawer still draw over it. + sessionRoot.addView(panel, sessionRoot.indexOfChild(surfaceView) + 1) + unfoldedPanel = panel + updateOnScreenControls() + } + panel.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM) + } + private fun moveSecondScreenPointer(x: Float, y: Float, width: Float, height: Float) { if (width <= 0f || height <= 0f) return val nx = (x / width).coerceIn(0f, 1f) @@ -1654,8 +1811,32 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } + /** The touch mode in force: the game's own while Steam's touch controls are shown. */ + private fun effectiveTouchMode(): String { + val options = steamTouchOptions + if (options == null || steamTouchControls?.visibility != View.VISIBLE) return SessionPrefs.touchMode(this) + return when { + options.inputMode == com.droiddeck.launcher.input.SteamTouchConfig.INPUT_CONTROLLER -> SessionPrefs.TOUCH_OFF + options.mouseMode == com.droiddeck.launcher.input.SteamTouchConfig.MOUSE_RELATIVE -> SessionPrefs.TOUCH_PAD + else -> SessionPrefs.TOUCH_DIRECT + } + } + + private fun applyTouchRouting() { + val next = effectiveTouchMode() + if (::touchpad.isInitialized) { + val speed = steamTouchOptions?.trackpadSensitivity?.takeIf { steamTouchControls?.visibility == View.VISIBLE } ?: 1f + touchpad.sensitivity = 1.15f * speed + } + if (next == routedTouchMode) return + if (::touchpad.isInitialized) touchpad.cancel() + if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0) + if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false + routedTouchMode = next + } + /** Touchpad on the desktop, direct in Steam, unless the drawer says otherwise. */ - private fun usingTouchpad(): Boolean = when (SessionPrefs.touchMode(this)) { + private fun usingTouchpad(): Boolean = when (routedTouchMode) { SessionPrefs.TOUCH_PAD -> true SessionPrefs.TOUCH_DIRECT -> false else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop" @@ -1677,7 +1858,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onTouchEvent(event: MotionEvent): Boolean { if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event) // Child views get the event first, so menus, keyboards and the on-screen pad still work. - if (touchMode == SessionPrefs.TOUCH_OFF) return true + if (routedTouchMode == SessionPrefs.TOUCH_OFF) return true if (usingTouchpad()) { val rect = drawnRect() ?: return false if (touchpad.bounds != rect) { @@ -1796,30 +1977,97 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { what, d.name, d.vendorId, d.productId, d.id, d.sources)) } + /** Steam's touch controls, once the session has made the device (SessionService). */ + private fun steamTouch(): com.droiddeck.launcher.input.SteamTouchControls? { + val device = com.droiddeck.launcher.input.SteamTouchDevice.current ?: return null + steamTouchControls?.let { view -> + if (view.device === device) return view + // A new session made a new device: the view of the old one goes. + view.releaseAll() + (view.parent as? android.view.ViewGroup)?.removeView(view) + steamTouchControls = null + } + val root = onScreenControls?.parent as? android.view.ViewGroup ?: return null + val view = com.droiddeck.launcher.input.SteamTouchControls(this, device, + onMenu = { drawerOpen = true }, onKeyboard = ::togglePcKeyboard) + view.visibility = View.GONE + view.onOptions = { options -> + steamTouchOptions = options + applyTouchRouting() + } + // Paste: the clipboard is shared with the session's X servers; Ctrl+V types it. + view.onPaste = { + sendGuestKey(29, true); sendGuestKey(47, true) // KEY_LEFTCTRL, KEY_V + sendGuestKey(47, false); sendGuestKey(29, false) + } + // The client reads a controller's config when it connects: after a save, plug the device + // out and back in so it takes the new one. + view.onSaved = { + device.plugged = false + uiHandler.postDelayed({ updateOnScreenControls() }, 700) + } + root.addView(view, root.indexOfChild(onScreenControls) + 1) + steamTouchControls = view + steamTouchAvailable = true + return view + } + private fun updateOnScreenControls() { val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc") .takeIf { it.isFile } ?.let { FileUtils.readString(it)?.trim()?.lowercase() } ?: SessionPrefs.oscMode(this) val controls = onScreenControls ?: return - if (pipUi) { + // In picture-in-picture, or with the unfolded screen's gamepad below the game, the on-screen + // pad would only cover the picture or that panel. + if (pipUi || unfoldedPanel != null) { onScreenButtonsVisible = false controls.releaseAll() controls.visibility = View.GONE + steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE } + com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false return } val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM + // Steam's touch controller stands in for the app's pad, and is plugged into the client only + // while it is shown - as Steam Link withdraws its controls when a physical pad is in use. + val wantsSteam = forced == SessionPrefs.OSC_STEAM_TOUCH && SessionState.mode == SessionService.MODE_STEAM + val steam = if (wantsSteam) steamTouch() else null + // The service makes the device while the session starts, after this activity: the app's + // own pad until then, and another look in a moment. + if (wantsSteam && steam == null && !isFinishing && !isDestroyed) { + uiHandler.removeCallbacks(steamTouchRetry) + uiHandler.postDelayed(steamTouchRetry, 1000) + } + if (steam == null) { + steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE } + com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false + } controls.setButtonsOnly(buttonsOnly) val show = when (forced) { SessionPrefs.OSC_ALWAYS -> true SessionPrefs.OSC_STEAM_QAM -> true SessionPrefs.OSC_NEVER -> false + // Shown throughout a Steam session: a handheld's built-in pad would keep Auto off for good. + // Outside Steam it is Auto. + SessionPrefs.OSC_STEAM_TOUCH -> SessionState.mode == SessionService.MODE_STEAM || + (!PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP) // Auto: the touch pad when there is no controller - except on the desktop, where the // screen is a touchpad for the pointer and a pad over it would be in the way. A game // started from the rail, or Steam, gets it; the drawer turns it on anywhere. - else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP + else -> !PadBridge.anyControllerConnected() && !SteamControllerBle.connected && + SessionState.mode != SessionService.MODE_DESKTOP } onScreenButtonsVisible = show + if (steam != null) { + if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE } + if (!show) steam.releaseAll() + steam.visibility = if (show) View.VISIBLE else View.GONE + com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = show + applyTouchRouting() + Log.i(TAG, "on-screen controls: Steam's touch controller " + if (show) "shown" else "hidden") + return + } if (show == (controls.visibility == View.VISIBLE)) return if (!show) controls.releaseAll() controls.visibility = if (show) View.VISIBLE else View.GONE @@ -1891,6 +2139,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) { super.onPictureInPictureModeChanged(inPip, newConfig) if (::pip.isInitialized) pip.changed(inPip) + // The panel may have changed while the session was a thumbnail (folded or unfolded in PiP). + if (!inPip && surfaceW > 0) followWindow(surfaceW, surfaceH) + applyUnfoldedControls() } override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) { @@ -1947,6 +2198,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onResume() { super.onResume() + requestedOrientation = SessionPrefs.orientation(this) if (runtimeRemovalBlocked) return com.droiddeck.launcher.ui.Motion.refresh(this) refreshHomeApp() @@ -2018,10 +2270,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) + // ALWAYS from Android 11: SHORT_EDGES left a black strip along a camera on the long edge, + // which is where a Fold's inner-screen camera sits with the device held in landscape. if (Build.VERSION.SDK_INT >= 28) { window.attributes = window.attributes.apply { - layoutInDisplayCutoutMode = - WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES + layoutInDisplayCutoutMode = if (Build.VERSION.SDK_INT >= 30) + WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS + else WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES } } } @@ -2038,6 +2293,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun onDestroy() { + uiHandler.removeCallbacks(steamTouchRetry) if (runtimeRemovalBlocked) { super.onDestroy(); return } // Deliberately does NOT end the session: this activity can be destroyed while the user is // in another app, and the whole point of the service is that Steam survives that. @@ -2049,6 +2305,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { closeSecondScreen(reset = false) if (::hud.isInitialized) hud.stop() padBridge?.stop() + steamController?.stop() if (SessionState.padBridge === padBridge) SessionState.padBridge = null padMotion?.stop() if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt index 80648e8875..2b8ba775b0 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.agent +import com.droiddeck.launcher.session.SessionPaths import android.Manifest import android.content.ContentProvider import android.content.ContentValues @@ -107,7 +108,7 @@ class AgentBridgeProvider : ContentProvider() { private fun state(context: Context): JSONObject { val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context) - val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: latestSessionDirectory() + val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull() val session = JSONObject() .put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL) .put("phase", SessionState.phase.name) @@ -163,12 +164,6 @@ class AgentBridgeProvider : ContentProvider() { .put("session", session) } - private fun latestSessionDirectory(): File? { - val parent = LinuxRuntime.debugLogDir() - return parent.listFiles { file -> file.isDirectory && file.name.startsWith("session-") } - ?.maxWithOrNull(compareBy { it.lastModified() }.thenBy { it.name }) - } - private fun stop(context: Context): JSONObject { if (SessionState.running) { SessionService.stop(context) diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentStartActivity.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentStartActivity.kt index 99a6f784c6..edf38dde68 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentStartActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentStartActivity.kt @@ -14,6 +14,7 @@ import org.json.JSONObject class AgentStartActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this) val request = decodeRequest(intent.getStringExtra(EXTRA_REQUEST)) if (request == null) { finish() diff --git a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java index 9af7ab959f..c4e1db8c7d 100644 --- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java +++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java @@ -182,26 +182,30 @@ public class PulseAudioComponent extends SessionPart { * client is never left without an output. Says so in the audio log either way. */ private void ensureClientSink(java.io.PrintWriter out) { - long deadline = System.currentTimeMillis() + 15000L; - String sinks = null; - while (System.currentTimeMillis() < deadline && pid > 1) { - if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break; - try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } + try { + long deadline = System.currentTimeMillis() + 15000L; + String sinks = null; + while (System.currentTimeMillis() < deadline && pid > 1) { + if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break; + try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } + } + String line; + if (sinks == null) { + line = "== client sink: the daemon did not answer in 15 s; no fallback attempted"; + } else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) { + line = "== client sink: DirectAudio (module-directaudio-native-sink)"; + } else { + boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null + && pactl("set-default-sink", "AAudioSink") != null; + line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)" + : "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound"; + Log.w(TAG, line); + } + Log.i(TAG, line); + if (out != null) synchronized (out) { out.println(line); out.flush(); } + } catch (Throwable t) { + Log.w(TAG, "ensureClientSink failed", t); } - String line; - if (sinks == null) { - line = "== client sink: the daemon did not answer in 15 s; no fallback attempted"; - } else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) { - line = "== client sink: DirectAudio (module-directaudio-native-sink)"; - } else { - boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null - && pactl("set-default-sink", "AAudioSink") != null; - line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)" - : "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound"; - Log.w(TAG, line); - } - Log.i(TAG, line); - if (out != null) synchronized (out) { out.println(line); out.flush(); } } /** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */ @@ -223,8 +227,14 @@ public class PulseAudioComponent extends SessionPart { builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath()); process = builder.start(); String output; - try (InputStream in = process.getInputStream()) { - output = new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8); + try (InputStream in = process.getInputStream(); + java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream()) { + byte[] buf = new byte[4096]; + int n; + while ((n = in.read(buf)) != -1) { + outStream.write(buf, 0, n); + } + output = outStream.toString(java.nio.charset.StandardCharsets.UTF_8.name()); } if (!process.waitFor(5, TimeUnit.SECONDS)) { process.destroyForcibly(); @@ -234,7 +244,7 @@ public class PulseAudioComponent extends SessionPart { } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; - } catch (Exception e) { + } catch (Throwable t) { return null; } finally { if (process != null && process.isAlive()) process.destroyForcibly(); diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index c16ad51f85..5fa562da95 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -53,7 +53,7 @@ object DeviceReport { b.append("DroidDeck session report\n") b.append("========================\n") k("Written", SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz", Locale.US).format(Date())) - k("Session mode", when (mode) { SessionService.MODE_DESKTOP -> "desktop (labwc/LXQt)"; SessionService.MODE_RUN -> "a program under gamescope"; else -> "Steam client (gamescope)" }) + k("Session mode", when (mode) { SessionService.MODE_DESKTOP -> "desktop (KDE Plasma)"; SessionService.MODE_RUN -> "a program under gamescope"; else -> "Steam client (gamescope)" }) h("App") runCatching { @@ -152,7 +152,6 @@ object DeviceReport { k("Zink lazy descriptors", SessionPrefs.zinkLazy(context)) k("Threaded GL (glthread)", SessionPrefs.glThread(context)) k("No GL error checks", SessionPrefs.noGlError(context)) - k("Steam Deck mode", SessionPrefs.steamDeckMode(context)) k("Steam controller", SessionPrefs.steamController(context)) k("Upscaler", (SessionPrefs.upscalerChoices.firstOrNull { it.first == SessionPrefs.upscaler(context) }?.second ?: "Off") + " (sharpness ${SessionPrefs.upscaleSharpness(context)}%)") @@ -189,7 +188,7 @@ object DeviceReport { } for (name in listOf("droiddeck-tu-debug", "droiddeck-driver", "droiddeck-osc", "droiddeck-no-pad", - "droiddeck-no-hud", "droiddeck-wlr-renderer")) { + "droiddeck-no-hud")) { val f = File(Environment.getExternalStorageDirectory(), "Download/$name") if (f.isFile) k(name, FileUtils.readString(f)?.trim()?.replace('\n', ' ')?.ifEmpty { "(present, empty)" } ?: "(present)") } diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt index e621372380..daa7e5d9d3 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt @@ -26,4 +26,8 @@ object DeviceSupport { val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null return soc?.let { "$it (${Build.HARDWARE})" } ?: Build.HARDWARE.ifBlank { context.getString(R.string.gpu_this_gpu) } } + + /** False on the Odin 3 (CQ8725S): a low-latency Wi-Fi lock makes its WLAN firmware hang, and + * that firmware reboots the whole device instead of restarting Wi-Fi. */ + fun lowLatencyWifiSafe(): Boolean = Build.VERSION.SDK_INT < 31 || Build.SOC_MODEL != "CQ8725S" } diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt index b2a8611f4e..6e6369228e 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt @@ -33,7 +33,8 @@ object GameEnvironment { "VKD3D_SHADER_MODEL" to "6_9", // .NET 7 and later reserve 256 GB of address space for the GC heap at startup, more than an // Android process has free, and the runtime fails to start. 32 GB is plenty for a game. - "DOTNET_GCRegionRange" to "0x800000000", + // Older NativeAOT runtimes require bare hex digits. CoreCLR accepts this form too. + "DOTNET_GCRegionRange" to "800000000", // .NET's W^X writes JIT code through a second mapping that FEX does not watch, so FEX keeps // running the stale translation and the game hangs at startup. "DOTNET_EnableWriteXorExecute" to "0", diff --git a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt index bac157b82e..4406a7028b 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt @@ -75,12 +75,30 @@ object LogRedactor { * user who signs in with a plain account name, not an email, had it in every log. The single * space then a non-space keeps "OnLoginStateChange 0 1 0 0" (no account yet) as it is. */ - private val LOGIN_STATE = Regex("(OnLoginStateChange )(\\S+)") + private val LOGIN_STATE = Regex("(?i)(OnLoginStateChange:? )([^\\s<]\\S*)") private val LOGIN_USERS = Regex("(OnLoginUsersChanged )(\\S.*)$") + /** + * An account name as a field: `AccountName`, `account_name`, `username` (`"AccountName" + * "someone"` in a VDF, `account_name=...`, `"username": "..."`) and `login` - the last only + * as `login=`, a quoted key or a VDF pair, so "Login: OnLoginStateChange ..." keeps its label. + * A quoted value is blanked whole; one already blanked is left as it is. + */ + private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)" + private val ACCOUNT_KV = Regex( + "(?i)(? = emptyList() + private var accounts: List = emptyList() /** * Learns every Steam account on the device from the client's loginusers.vdf - its AccountName @@ -88,12 +106,13 @@ object LogRedactor { * Names under three characters are skipped: blanking every "a" would ruin a log. */ fun learnAccounts(loginUsers: java.io.File) { - val found = ArrayList() + val found = ArrayList() try { if (loginUsers.isFile) { val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"") kv.findAll(loginUsers.readText()).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.distinct().forEach { name -> - found += Regex("(?i)(? = emptyList() + private var own: List = emptyList() /** * Learns the device's addresses from the link file the app writes for the session @@ -118,7 +137,7 @@ object LogRedactor { * private, link-local and loopback addresses identify nobody and are left out. */ fun learnOwnAddresses(linkFile: java.io.File) { - val found = ArrayList() + val found = ArrayList() try { if (linkFile.isFile) linkFile.forEachLine { line -> val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine @@ -127,9 +146,12 @@ object LogRedactor { val groups = expand6(addr)?.take(4) ?: return@forEachLine // Any spelling of an address in this /64: leading zeros dropped, :: anywhere after. val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) } - found += Regex("(?i)(? found += Regex("(? found += Learned(Regex("(? out.write(redact(line)); out.write("\n") } } + /** + * The last pass for a file going into a shared zip: [redact], then the rules the stores' log + * uses too ([SecretScrub]) - URLs without query, fragment and user:password and with any + * token-bearing path segment blanked, token values and Authorization / Cookie headers blanked + * - and private IPv4 addresses as ``. A line already clean comes out unchanged. + */ + fun redactForShare(line: String): String { + if (line.isEmpty()) return line + return try { + val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "") + LAN_IPV4.replace(out, "") + } catch (t: Throwable) { + "" + } + } + + /** [src]'s lines through [redactForShare], to [out]: the pass every text file in a shared zip gets. */ + fun scrubForShare(src: java.io.File, out: java.io.Writer) { + src.forEachLine { line -> out.write(redactForShare(line)); out.write("\n") } + } + + /** ``, inside [value]'s quotes when it had them. */ + private fun quoted(value: String): String { + val q = value.first().takeIf { it == '"' || it == '\'' }?.toString().orEmpty() + return "$q$q" + } + + /** + * A line on its way through [redact]. Each rule runs only on a line holding what it cannot match + * without - a word, enough separators, a long enough run: most of a Steam log is lines no rule + * touches, and a session's logs went through every rule at about a megabyte a second. A line with anything but ASCII in it goes through + * every case-insensitive rule, since Android's regex folds case more widely than lowercase(). + */ + private class Line(var text: String) { + private val unfolded = text.any { it.code >= 0x80 } + private var lower: String? = null + + fun has(vararg words: String): Boolean { + if (unfolded) return true + val folded = lower ?: text.lowercase().also { lower = it } + return words.any { folded.contains(it) } + } + + fun set(next: String) { + if (next != text) { + text = next + lower = null + } + } + + fun holds(c: Char, times: Int): Boolean { + var n = 0 + for (ch in text) if (ch == c && ++n >= times) return true + return false + } + + inline fun hasRun(length: Int, inRun: (Char) -> Boolean): Boolean { + var n = 0 + for (ch in text) if (!inRun(ch)) n = 0 else if (++n >= length) return true + return false + } + } + + private fun isHex(c: Char) = c in '0'..'9' || c in 'a'..'f' || c in 'A'..'F' + /** [line] with every credential shape replaced. Null- and exception-safe by construction. */ fun redact(line: String): String { if (line.isEmpty()) return line return try { - var out = line - out = MAC_FIELD.replace(out) { "${it.groupValues[1]}" } - out = MAC.replace(out, "") - out = DEVICE_IDENTIFIER.replace(out) { + val out = Line(line) + if (out.has("mac")) out.set(MAC_FIELD.replace(out.text) { "${it.groupValues[1]}" }) + if (out.holds(':', 5) || out.holds('-', 5)) out.set(MAC.replace(out.text, "")) + if (out.has("serial", "android")) out.set(DEVICE_IDENTIFIER.replace(out.text) { val value = it.groupValues[2] val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty() "${it.groupValues[1]}${quote}${quote}" + }) + if (out.holds('-', 4)) out.set(GUID.replace(out.text, "")) + if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}" }) + if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "")) + if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) { + out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}" }) } - out = GUID.replace(out, "") - out = JWT_LABELLED.replace(out) { "${it.groupValues[1]}" } - out = JWT_BASE64.replace(out, "") - out = SECRET_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}" } - out = GUARD_CODE.replace(out) { "${it.groupValues[1]}" } - out = WEBAPI_KEY.replace(out, "") + if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}" }) + if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "")) // Mask, not delete: the last four digits let a reader correlate lines to one account. - out = STEAMID64.replace(out) { "${it.groupValues[1]}********${it.groupValues[3]}" } - out = STEAMID3.replace(out) { m -> + if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" }) + if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m -> val id = m.groupValues[1] "[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]" + }) + if (out.has("external")) out.set(EXTERNAL_ADDR.replace(out.text) { "${it.groupValues[1]}" }) + for (r in own) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "")) + if (out.has("onloginstatechange")) out.set(LOGIN_STATE.replace(out.text) { "${it.groupValues[1]}" }) + if ("OnLoginUsersChanged " in out.text) out.set(LOGIN_USERS.replace(out.text) { "${it.groupValues[1]}" }) + if (out.has("account", "user")) { + out.set(ACCOUNT_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }) } - out = EXTERNAL_ADDR.replace(out) { "${it.groupValues[1]}" } - for (r in own) out = r.replace(out, "") - out = LOGIN_STATE.replace(out) { "${it.groupValues[1]}" } - out = LOGIN_USERS.replace(out) { "${it.groupValues[1]}" } - for (r in accounts) out = r.replace(out, "") - out = EMAIL.replace(out, "") - out = RESIDUAL.replace(out) { "${it.groupValues[1]}=" } - out = LONG_TOKEN.replace(out, "") - out + if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }) + for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "")) + if ('@' in out.text) out.set(EMAIL.replace(out.text, "")) + if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) { + out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=" }) + } + if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) { + out.set(LONG_TOKEN.replace(out.text, "")) + } + out.text } catch (t: Throwable) { // A log line is never worth crashing a session over, but an unscrubbed one must not // reach the file either. diff --git a/app/src/main/java/com/droiddeck/launcher/core/SecretScrub.kt b/app/src/main/java/com/droiddeck/launcher/core/SecretScrub.kt new file mode 100644 index 0000000000..c91ca60ef9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/SecretScrub.kt @@ -0,0 +1,72 @@ +package com.droiddeck.launcher.core + +/** + * The one set of rules that keeps URLs and tokens out of anything the app writes or shares: the + * stores' log ([com.droiddeck.launcher.stores.StoreLog.redactLine]) and the last pass over every + * text file in a shared log zip ([LogRedactor.redactForShare]). + * + * - Every URL loses its query, fragment and `user:password@`. [Urls.SHORT] then keeps only the host + * and a plain first path segment (the stores' lines, where a GOG secure link carries its token in + * the path); [Urls.KEEP_PATH] keeps the path but blanks any segment that carries a token. + * - Outside URLs, the values of token-like keys (`token`, `__token__`, `f_token`, `hdnts`, access / + * refresh / id tokens; exchange and authorization codes of four characters or more, and a bare + * `code=` where it is one: in a query string or on a line with OAuth keys such as `client_id`, + * `redirect_uri` or `state`, never an 8-hex exception code like Proton's `code=c0000005`) and of + * Authorization / Cookie headers are blanked with [mark]. + * + * A line already scrubbed comes out unchanged. + */ +object SecretScrub { + enum class Urls { SHORT, KEEP_PATH } + + private val URL = Regex("""[A-Za-z][A-Za-z0-9+.\-]*://[^\s"'<>]+""") + private val SAFE_SEGMENT = Regex("""[A-Za-z0-9._\-]{1,40}""") + private val TOKEN_SEGMENT = Regex("""(?i)(token|hdnts|hmac|signature|sig|exp)=""") + private val TOKEN = Regex("""(?i)(?}]+""") + /** Codes that are only ever OAuth grants. */ + private val GRANT_CODE = Regex("""(?i)(?}]{4,}""") + /** A bare `code=`: a grant only right after `?` / `&` (a query string) or beside OAuth keys ([OAUTH_CONTEXT]). */ + private val CODE = Regex("""(?i)(?}]{4,})""") + private val OAUTH_CONTEXT = Regex("""(?i)(? if (urls == Urls.SHORT) short(m.value) else keepPath(m.value, mark) } + out = TOKEN.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark } + out = GRANT_CODE.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark } + val oauth = OAUTH_CONTEXT.containsMatchIn(text) + val src = out + out = CODE.replace(src) { m -> + val inQuery = m.range.first > 0 && src[m.range.first - 1] in "?&" + val grant = !STATUS_CODE.matches(m.groupValues[3]) && (oauth || inQuery) + if (grant) m.groupValues[1] + m.groupValues[2] + mark else m.value + } + out = HEADER.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark } + return out + } + + private fun split(url: String): Triple { + val schemeEnd = url.indexOf("://") + val rest = url.substring(schemeEnd + 3).substringBefore('#').substringBefore('?') + val slash = rest.indexOf('/') + val authority = (if (slash >= 0) rest.substring(0, slash) else rest).substringAfterLast('@') + return Triple(url.substring(0, schemeEnd), authority, if (slash >= 0) rest.substring(slash + 1) else null) + } + + private fun short(url: String): String { + val (scheme, authority, path) = split(url) + if (path == null) return "$scheme://$authority" + val first = path.substringBefore('/') + if (first.isEmpty()) return "$scheme://$authority/" + val shown = if (SAFE_SEGMENT.matches(first)) first else "…" + return "$scheme://$authority/$shown" + if (path.length > first.length && shown != "…") "/…" else "" + } + + private fun keepPath(url: String, mark: String): String { + val (scheme, authority, path) = split(url) + val clean = path?.split('/')?.joinToString("/") { seg -> if (TOKEN_SEGMENT.containsMatchIn(seg)) mark else seg } + return "$scheme://$authority" + (clean?.let { "/$it" } ?: "") + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt index cc0586d6fe..2395d1c80d 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt @@ -22,6 +22,7 @@ class FileManagerActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this) if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1) } diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt index 9f9361ad7b..46f2f708b2 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -1020,7 +1020,8 @@ fun FileManagerScreen( // The ROMs folder chosen on the main screen: what the session shows as /root/ROMs. SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory } ?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) } - File("/storage/emulated/0/Download/DroidDeck").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) } + // The app's own logs folder: private, which this file manager (the app itself) can read. + com.droiddeck.launcher.runtime.LinuxRuntime.logDir(context).takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) } File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) } } val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } } diff --git a/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt b/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt index 36ec427cf0..8f8782719f 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt @@ -35,6 +35,7 @@ class FilePickerActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this) // targetSdk 28: the old storage permission is exactly what lets us list the card. if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1) diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedExes.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedExes.kt new file mode 100644 index 0000000000..62afb0b8af --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedExes.kt @@ -0,0 +1,48 @@ +package com.droiddeck.launcher.frontend + +import android.content.Context +import org.json.JSONArray +import org.json.JSONObject +import java.io.File + +/** + * Games added from the Games tab's + rather than a Games folder: one picked .exe, or each game + * "Add all games in this folder" found. Kept by the game's folder in `files/added-exes.json`, + * which [AddedGames.scan] merges in. The exe chosen later, the shortcut appid, the edits and the + * removal live where every added game keeps them ([com.droiddeck.launcher.session.SessionPrefs]); + * this holds which folders are games and the exe they came with. + */ +object AddedExes { + /** [picked]: the user chose [exe]; false = [GameExePicker]'s best guess, which a scan ranks again. */ + class Entry(val folder: String, val exe: String, val picked: Boolean = true) + + private fun file(context: Context) = File(context.filesDir, "added-exes.json") + + @Synchronized + fun list(context: Context): List = try { + val array = JSONArray(file(context).takeIf { it.isFile }?.readText() ?: "[]") + (0 until array.length()).mapNotNull { i -> + val o = array.optJSONObject(i) ?: return@mapNotNull null + val folder = o.optString("folder"); val exe = o.optString("exe") + if (folder.isEmpty() || exe.isEmpty()) null else Entry(folder, exe, o.optBoolean("picked", true)) + } + } catch (e: Exception) { + emptyList() + } + + /** Adds [entry], replacing one for the same folder. */ + @Synchronized + fun put(context: Context, entry: Entry) = write(context, list(context).filter { it.folder != entry.folder } + entry) + + @Synchronized + fun drop(context: Context, folder: String) = write(context, list(context).filter { it.folder != folder }) + + private fun write(context: Context, entries: List) { + val array = JSONArray() + entries.forEach { array.put(JSONObject().put("folder", it.folder).put("exe", it.exe).put("picked", it.picked)) } + val f = file(context) + val tmp = File(f.path + ".tmp") + tmp.writeText(array.toString()) + if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt index ecc92a1db6..1fb5bb272d 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt @@ -12,8 +12,9 @@ import java.net.URL import java.net.URLEncoder /** - * Artwork for an added game: what the user put in the game's folder first, else what Steam's - * store has for the same title, fetched once into the app's cache. Four pieces, named the way + * Artwork for an added game: what the user put in the game's folder first, else what Steam has + * for it - by the Steam appid its files name, else by a store search on its title - else what + * SteamGridDB has ([SteamGridDb]), fetched once into the app's cache. Four pieces, named the way * the client names them in its grid folder: the portrait capsule, the wide header, the hero * background and the logo; plus an icon pulled out of the game's own .exe. The session hands * the paths to the runtime's shortcuts writer, which copies them into the client's grid. @@ -28,13 +29,40 @@ object AddedGameArt { val any get() = portrait != null || header != null || hero != null || logo != null } + /** + * The pieces a user can choose, as the client takes them: [assetType] is its custom-artwork + * number (null: the icon, set by path); [cacheName] the automatic file in the game's cache. + */ + enum class Slot(val key: String, val cacheName: String, val assetType: Int?) { + COVER("p", "p.jpg", 0), BACKGROUND("hero", "hero.jpg", 1), LOGO("logo", "logo.png", 2), ICON("icon", "icon.png", null), + } + + /** Where a piece came from; [AUTO] = nothing found yet. */ + const val FOLDER = "folder" + const val STEAM = "steam" + const val SGDB = "sgdb" + const val FILE = "file" + const val EXE = "exe" + const val AUTO = "" + + /** A slot as it stands: the file shown and where it came from (one of [FOLDER].. [AUTO]); [chosen] = the user picked it. */ + class SlotState(val slot: Slot, val file: File?, val source: String, val chosen: Boolean) + + /** One image the chooser offers: its group ([FOLDER], [STEAM], [SGDB]), a thumbnail and the full image (URL or path). */ + class Option(val group: String, val thumb: String, val full: String) + + private val CHOSEN = Regex("""chosen-(\w+)\.(\w+)""") + + private fun chosen(cache: File, slot: Slot): File? = + cache.listFiles { f -> CHOSEN.matchEntire(f.name)?.groupValues?.get(1) == slot.key }?.firstOrNull() + private val IMAGE = listOf("png", "jpg", "jpeg") private val PORTRAIT = listOf("cover", "poster", "grid", "boxart", "capsule", "folder", "library_600x900", "portrait") private val HEADER = listOf("header", "banner", "library_header", "wide") private val HERO = listOf("hero", "background", "library_hero") private val LOGO = listOf("logo") - private fun cacheDir(context: Context, game: AddedGames.Game) = File(context.filesDir, "added-art/${game.appId}") + internal fun cacheDir(context: Context, game: AddedGames.Game) = File(context.filesDir, "added-art/${game.appId}") /** An image in the folder (or its `art` subfolder) under one of the given names, any image extension. */ private fun find(folder: File, names: List): File? { @@ -58,20 +86,111 @@ object AddedGameArt { ) } - /** The folder's art, else the cached Steam art, without touching the network. */ + /** The user's choice for each piece, else the folder's art, else the cached art; no network. */ fun resolve(context: Context, game: AddedGames.Game): Art { val own = local(game) val cache = cacheDir(context, game) fun cached(name: String) = File(cache, name).takeIf { it.isFile } return Art( - portrait = own.portrait ?: cached("p.jpg"), - header = own.header ?: cached("header.jpg"), - hero = own.hero ?: cached("hero.jpg"), - logo = own.logo ?: cached("logo.png"), - icon = own.icon ?: exeIcon(context, game), + portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: cached("p.jpg") ?: exeArt(context, game, cover = true), + header = own.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false), + hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: cached("hero.jpg"), + logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"), + icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game), ) } + /** Each choosable piece with its file and where it came from, for the game's editor; no network. */ + fun describe(context: Context, game: AddedGames.Game): List { + val own = local(game) + val cache = cacheDir(context, game) + fun cached(name: String): Pair? = File(cache, name).takeIf { it.isFile }?.let { f -> + f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM) + } + return Slot.values().map { slot -> + chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) } + val auto: Pair? = when (slot) { + Slot.COVER -> own.portrait?.let { it to FOLDER } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE } + Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: cached("hero.jpg") + Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png") + Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB } + ?: exeIcon(context, game)?.let { it to EXE } + } + SlotState(slot, auto?.first, auto?.second ?: AUTO, false) + } + } + + private val CHOOSABLE = setOf("png", "jpg", "jpeg", "webp") + + /** Images in the game's folder (and its art folders) that could stand for a piece. */ + internal fun folderImages(folder: File): List = + listOf(folder, File(folder, "art"), File(folder, ".art")).flatMap { dir -> + dir.listFiles { f -> f.isFile && f.extension.lowercase() in CHOOSABLE }?.sortedBy { it.name.lowercase() }.orEmpty() + }.take(12) + + /** + * What the chooser offers for [slot]: the game folder's images, Steam's official piece (when the + * game has a Steam appid and Steam has the piece), and SteamGridDB's best few (with a key). + * Blocking: it asks the network. + */ + fun options(context: Context, game: AddedGames.Game, slot: Slot): List