diff --git a/.github/trusted-test-builds.txt b/.github/trusted-test-builds.txt index 4f94e6c268..99d73b6ac9 100644 --- a/.github/trusted-test-builds.txt +++ b/.github/trusted-test-builds.txt @@ -6,3 +6,4 @@ KeegantheVeganat0r kingokksa ovurrsl KeegantheVeganat0r +EnzoDLofi diff --git a/.github/workflows/build-fex.yml b/.github/workflows/build-fex.yml index deb099100a..08d3ba957b 100644 --- a/.github/workflows/build-fex.yml +++ b/.github/workflows/build-fex.yml @@ -29,11 +29,14 @@ jobs: persist-credentials: false - name: Build in Arch Linux ARM env: + GH_TOKEN: ${{ github.token }} FEX_EXTRA_CXXFLAGS: ${{ inputs.cxxflags }} FEX_THUNKS: ${{ inputs.thunks == 'true' && '1' || '0' }} run: | set -euo pipefail - docker run --rm -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh + FEX_VERSION=$(gh api repos/FEX-Emu/FEX/releases/latest --jq .tag_name) + echo "Building $FEX_VERSION, FEX's latest release" + docker run --rm -e FEX_VERSION="$FEX_VERSION" -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh sudo chown -R "$(id -u):$(id -g)" . - uses: actions/upload-artifact@v4 with: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3816c1a52c..43d90e5d17 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -164,6 +164,9 @@ jobs: !/docs/releases/media/ sparse-checkout-cone-mode: false persist-credentials: false + - name: Clear scratch earlier runs left behind + if: runner.environment == 'self-hosted' + run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE" - name: Merge the pinned APK base if: github.event_name == 'pull_request' env: @@ -367,6 +370,10 @@ jobs: persist-credentials: false submodules: recursive + - name: Clear scratch earlier runs left behind + if: runner.environment == 'self-hosted' + run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE" + - name: Check human authorship env: EVENT_NAME: ${{ github.event_name }} @@ -565,17 +572,65 @@ jobs: SOURCE_TREE: ${{ needs.source.outputs.tree-sha }} run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE" + # A hosted runner needs over 20 minutes per launcher; rebuild only when its sources change, and save each + # build as soon as it finishes so a later timeout cannot discard it. + - name: Restore the Ubisoft launcher build + id: ubisoft-cache + uses: actions/cache/restore@v4 + with: + path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft + key: ubisoft-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/ubisoft-launcher/src/**', 'tools/ubisoft-launcher/Cargo.toml', 'tools/ubisoft-launcher/Cargo.lock', 'tools/ubisoft-launcher/build.sh', 'tools/ubisoft-launcher/build.rs', 'tools/ubisoft-launcher/.cargo/**') }} - name: Ubisoft launcher service (x86_64-pc-windows-gnu) + if: steps.ubisoft-cache.outputs.cache-hit != 'true' run: | set -euo pipefail command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; } bash tools/ubisoft-launcher/build.sh + - name: Save the Ubisoft launcher build + if: steps.ubisoft-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@v4 + with: + path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft + key: ${{ steps.ubisoft-cache.outputs.cache-primary-key }} + - name: Restore the Rockstar launcher build + id: rockstar-cache + uses: actions/cache/restore@v4 + with: + path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar + key: rockstar-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/rockstar-launcher/src/**', 'tools/rockstar-launcher/Cargo.toml', 'tools/rockstar-launcher/Cargo.lock', 'tools/rockstar-launcher/build.sh', 'tools/rockstar-launcher/build.rs', 'tools/rockstar-launcher/.cargo/**') }} - name: Rockstar launcher service (32-bit and 64-bit) + if: steps.rockstar-cache.outputs.cache-hit != 'true' run: | set -euo pipefail command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; } + command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; } bash tools/rockstar-launcher/build.sh + - name: Save the Rockstar launcher build + if: steps.rockstar-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@v4 + with: + path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar + key: ${{ steps.rockstar-cache.outputs.cache-primary-key }} + + - name: Restore the Epic launcher build + id: epic-cache + uses: actions/cache/restore@v4 + with: + path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic + key: epic-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/epic-launcher/src/**', 'tools/epic-launcher/Cargo.toml', 'tools/epic-launcher/Cargo.lock', 'tools/epic-launcher/build.sh', 'tools/epic-launcher/build.rs', 'tools/epic-launcher/.cargo/**') }} + - name: Epic Games Launcher parent stand-in (x86_64-pc-windows-gnu) + if: steps.epic-cache.outputs.cache-hit != 'true' + run: | + set -euo pipefail + command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; } + bash tools/epic-launcher/build.sh + - name: Save the Epic launcher build + if: steps.epic-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@v4 + with: + path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic + key: ${{ steps.epic-cache.outputs.cache-primary-key }} - uses: actions/download-artifact@v4 with: @@ -588,7 +643,7 @@ jobs: path: | ~/.cache/droiddeck-pack-inputs ~/.cache/droiddeck-build - key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/powervr/release.json') }} + key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/packs/zstd/release.env', 'tools/powervr/release.json') }} restore-keys: pack-inputs-v2- - name: Build the add-on packs run: | @@ -679,6 +734,32 @@ jobs: if-no-files-found: ignore overwrite: true + - name: Resolve the Robolectric version + id: robolectric + run: | + echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT" + # Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes. + # The cache path sits beside the workspace because runner homes are at different depths from it, and + # actions/cache stores paths relative to the workspace. Runners that keep their own ~/.m2 skip the cache. + - name: Place Robolectric's Android jars beside the workspace + id: robolectric-jars + run: | + set -euo pipefail + jars="$GITHUB_WORKSPACE/../robolectric-jars" + m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented" + if [ -d "$m2" ] && [ ! -L "$m2" ]; then + echo "cache=false" >> "$GITHUB_OUTPUT" + else + mkdir -p "$jars" "$(dirname "$m2")" + ln -sfn "$(cd "$jars" && pwd)" "$m2" + echo "cache=true" >> "$GITHUB_OUTPUT" + fi + - name: Cache Robolectric's Android jars + if: steps.robolectric-jars.outputs.cache == 'true' + uses: actions/cache@v4 + with: + path: ../robolectric-jars + key: robolectric-android-all-v2-${{ steps.robolectric.outputs.version }} - name: Unit tests id: unit-tests env: @@ -823,6 +904,7 @@ jobs: run: | cargo test --locked --manifest-path tools/ubisoft-launcher/Cargo.toml cargo test --locked --manifest-path tools/rockstar-launcher/Cargo.toml + cargo test --locked --manifest-path tools/epic-launcher/Cargo.toml python-tests: name: Python and native regression tests diff --git a/.github/workflows/publish-packs.yml b/.github/workflows/publish-packs.yml index c9e036f2db..a3c46b8f8b 100644 --- a/.github/workflows/publish-packs.yml +++ b/.github/workflows/publish-packs.yml @@ -55,7 +55,7 @@ jobs: jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty' } commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA") - for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt; do + for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt epic; do file="packs/$name.tar.zst" [ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; } sha=$(sha256sum "$file" | cut -d' ' -f1) diff --git a/.gitignore b/.gitignore index eeb1404467..395d551a1f 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,4 @@ app/src/main/assets/directaudio/ app/src/main/assets/hybris/ /tools/vr/out/ app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar/ +app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic/ diff --git a/AGENTS.md b/AGENTS.md index 447807615b..97930d6563 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,42 @@ - Comments should be rare, factual, and explain only non-obvious external constraints or business invariants. -# Working on the device +# Building and testing + +- For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step. +- `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`. +- Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout. +- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally. +- Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests ''` and `python3 -m unittest discover -s tools/tests -p 'test_*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI. +- For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape. +- After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`. +- Compile errors in code you didn't touch, after switching branches, are usually stale incremental state. Rebuild once before you change anything. + +# Worktrees and shared machines + +- After `git worktree add`, run `git submodule update --init --recursive`. Without it, `buildVkBridgeServer` fails on missing `external/MaliBridge`. Do not commit the `tools/syncthing/syncthing-android` pointer the build dirties. +- Other agents may be building on the same machine. Never run `./gradlew --stop` or kill Gradle/Kotlin daemons you did not start. If you need isolation, use `GRADLE_USER_HOME= GRADLE_RO_DEP_CACHE=$HOME/.gradle/caches`. + +# Driving the app and device + +- Do it yourself with `tools/droiddeckctl` (see `docs/agent-control.md`) instead of asking the user: `cdp eval` for Steam's UI (`SteamClient.Apps.TerminateApp('', false)` quits a game, including on a Remote Play host), `input`, `quit`, `displays`, `screenshot --display `. +- A stream has started only when the session state reads `Streaming`. `SteamClient.Apps.StreamGame` alone can leave Steam on its menu, so open the game page and press Stream. +- Test controller navigation with `tools/droiddeckctl input gamepad ...`, a real uinput pad. `adb shell input keyevent DPAD_*` does not arrive as a joystick event and hides d-pad/stick bugs. +- A release-signed build installs over a release-signed install with `adb install -r`. Don't back up, uninstall or clear data to update. Scope `pm` and permission resets to `com.droiddeck.launcher`, never the whole device. + +# CI + +- Before pushing a PR, run `tools/pre_pr.sh`. It checks authorship and the merge onto `main`, then, when app sources change, compiles and runs lint as CI does. It picks tests by name: `*Test` for changed Kotlin files, and `tools/tests` modules that mention a changed path. Add any other tests that cover your change, and leave the full suites to CI. +- CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge. +- Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors. +- Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them. +- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs//logs`, or `gh run download -n unit-test-results`. Don't call a failure a runner problem until you have read it. +- Only these are known flakes worth a `gh run rerun --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real. +- A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`. + +# Agents running on the device (DroidDeck's in-app agent) + +These apply only where `dd-lab-build` exists. Agents on a dev host use `tools/quick_deploy.sh` instead. - `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess. - Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build. diff --git a/README.md b/README.md index 7154309b06..71024514c4 100644 --- a/README.md +++ b/README.md @@ -70,8 +70,9 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05. - mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). -- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. +- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122). - x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. +- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence. - x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes. - `WriteProcessMemory` hooks fall back to `/proc//mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11. - Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim. @@ -91,7 +92,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
Stores -- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send. +- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send. Deleted GOG cloud saves are recognised by the empty-gzip deletion hash gogdl and Lutris skip. - Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support. - The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268). - Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. @@ -99,7 +100,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader. - The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code. - World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used. -- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key. +- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. Installed addons show their `.toc` version and `X-WoWI-ID`, and are checked against that list for updates, as [WowUp](https://github.com/WowUp/WowUp) does. The Addons tab installs the official [CurseForge](https://www.curseforge.com/download/app) Linux app from CurseForge's own update feed (downloaded at install time and checked against its SHA-512, not included), which keeps its own sign-in. - The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). - The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`. - The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive). diff --git a/app/build.gradle b/app/build.gradle index c271f963b9..f2cb40169b 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -93,7 +93,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines() .findAll { it.contains('=') && !it.startsWith('#') } .collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] } -def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt'].collectEntries { name -> +def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].collectEntries { name -> def pack = file("build/packs/${name}.tar.zst") if (!pack.isFile()) { if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") @@ -125,7 +125,8 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines() android { namespace 'com.droiddeck.launcher' compileSdk 34 - ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724' + ndkVersion project.findProperty('ndkVersion') ?: providers.fileContents(rootProject.layout.projectDirectory.file('tools/ci/toolchains.env')) + .asText.get().readLines().find { it.startsWith('CI_ANDROID_NDK_VERSION=') }.split('=', 2)[1].trim() defaultConfig { applicationId "com.droiddeck.launcher" @@ -202,7 +203,7 @@ android { } androidResources { - ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*~:droiddeck-xbox:droiddeck-comet:droiddeck-ubisoft:droiddeck-rockstar:droiddeck-dirt:directaudio:hybris' + ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*~:droiddeck-xbox:droiddeck-comet:droiddeck-ubisoft:droiddeck-rockstar:droiddeck-dirt:droiddeck-epic:directaudio:hybris' } packagingOptions { @@ -232,6 +233,9 @@ android { } maxHeapSize = '2g' maxParallelForks = 2 + def jvmTemp = new File(temporaryDir, 'jvm') + systemProperty 'java.io.tmpdir', jvmTemp.absolutePath + doFirst { jvmTemp.mkdirs() } def logTarget = providers.systemProperty('robolectric.logging').orNull if (logTarget != null) systemProperty 'robolectric.logging', logTarget } @@ -261,11 +265,9 @@ if (vitureSdkDir) { tasks.named('preBuild').configure { dependsOn(stageVitureNotices) } } -def stageSessionScripts = tasks.register('stageSessionScripts', Copy) { - from(rootProject.file('tools/linuxfs/overlay')) { - include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**' - } - into(layout.projectDirectory.dir('src/main/assets/linuxfs')) +def stageSessionScripts = tasks.register('stageSessionScripts', Exec) { + workingDir rootProject.projectDir + commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage' } tasks.named('preBuild').configure { dependsOn(stageSessionScripts) } diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt index e0003e1348..681b32a10b 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt @@ -15,6 +15,7 @@ private fun Launcher(tab: String, games: List }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) /** The in-game menu's actions with settled sample values; its switches do nothing. */ diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index aff5658bbe..55b75d36df 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -232,6 +232,7 @@ android:exported="false" android:screenOrientation="user" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density" + android:windowSoftInputMode="adjustResize" android:theme="@style/AppTheme" /> - 0); + const char *d = num + i; + while (*d && *d == *execfn) d++, execfn++; + return !*d && seq(execfn, "/exe"); +} + +static const char *guest_interp(char **envp, const char *interp, char *buf, size_t size) { + const char *root = env_get(envp, "DDNATV_ROOT"); + if (!root || interp[0] != '/') return interp; + size_t a = slen(root), b = slen(interp); + if (a + b + 1 > size) return interp; + for (size_t i = 0; i < a; i++) buf[i] = root[i]; + for (size_t i = 0; i <= b; i++) buf[a + i] = interp[i]; + if (sys6(SYS_faccessat, AT_FDCWD_, (long)buf, 0, 0, 0, 0) != 0) return interp; + return buf; +} + __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) { long argc = (long)sp[0]; char **argv = (char **)(sp + 1); @@ -211,25 +274,66 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) { uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1); long naux = 0; while (auxv[naux * 2] != AT_NULL) naux++; - if (argc < 3) die("usage: libddexec.so [args...]", 0, 0); + int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0)); + const char *path; + char **args = argv + 2; + long nargs = argc - 2; + char interp_buf[4096]; + char hook_buf[4096]; + if (reexec) { + path = env_get(envp, "DDNATV_REAL_EXE"); + if (!path || !path[0]) die("re-executed without DDNATV_REAL_EXE", 0, 0); + args = argv; + nargs = argc; + const char *lib_path = env_get(envp, "DDNATV_LIBRARY_PATH"); + char prog_interp[256]; + interp_of(path, prog_interp, sizeof(prog_interp)); + if (prog_interp[0] && lib_path && lib_path[0]) { + const char *ld_so = guest_interp(envp, prog_interp, interp_buf, sizeof(interp_buf)); + const char *hook = guest_interp(envp, "/usr/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf)); + if (hook != (const char *)hook_buf) hook = guest_interp(envp, "/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf)); + long n = argc > 1 ? argc - 1 : 0; + char **v = (char **)__builtin_alloca((size_t)(n + 9) * sizeof(char *)); + long k = 0; + v[k++] = (char *)ld_so; + if (hook == (const char *)hook_buf) { + v[k++] = (char *)"--preload"; + v[k++] = (char *)hook; + } + v[k++] = (char *)"--library-path"; + v[k++] = (char *)lib_path; + v[k++] = (char *)"--argv0"; + v[k++] = argc > 0 ? argv[0] : (char *)path; + v[k++] = (char *)path; + for (long i = 0; i < n; i++) v[k++] = argv[1 + i]; + v[k] = 0; + args = v; + nargs = k; + path = ld_so; + } + } else if (argc < 3) { + die("usage: libddexec.so [args...]", 0, 0); + } else { + path = argv[1]; + } uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096); - const char *path = argv[1]; struct image prog, interp; load(path, &prog, page); int has_interp = prog.interp[0] != 0; - if (has_interp) load(prog.interp, &interp, page); + if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : prog.interp, &interp, page); // The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one. // The strings stay where the kernel put them. static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN}; long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0])); - long new_argc = argc - 2; + long new_argc = nargs; long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2; - uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15); + uintptr_t top = (uintptr_t)args < (uintptr_t)sp ? (uintptr_t)args : (uintptr_t)sp; + uintptr_t *nsp = (uintptr_t *)((top - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15); uintptr_t *w = nsp; *w++ = (uintptr_t)new_argc; - for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2]; + for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i]; *w++ = 0; for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i]; *w++ = 0; diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index 13e9e1b3e0..5bdc1e8385 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -8,6 +8,7 @@ add_library(droiddeckwayland SHARED src/vk_loader.c src/sc_layer.c src/ahb_swapchain.c + src/display_buffers.c src/waylandcomp_jni.c src/gpu_clock_pin.c src/droiddeck_ext.c @@ -34,7 +35,8 @@ add_library(droiddeckwayland SHARED 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 + generated/droiddeck-ahb-v1-protocol.c + generated/droiddeck-refresh-v1-protocol.c src/framegen_bridge.c src/framegen_jni.c src/hudframes.c diff --git a/app/src/main/cpp/waylandcomp/ZERO_COPY_SPIKE.md b/app/src/main/cpp/waylandcomp/ZERO_COPY_SPIKE.md index 37b08b2334..f5e7177244 100644 --- a/app/src/main/cpp/waylandcomp/ZERO_COPY_SPIKE.md +++ b/app/src/main/cpp/waylandcomp/ZERO_COPY_SPIKE.md @@ -19,8 +19,8 @@ exactly how Turnip already imports every gralloc buffer on Android (`vk_android. in play already have every extension needed; nothing is missing in the drivers. What is missing is a **WSI hook**: Mesa's Wayland WSI always allocates its own dma-bufs and has no way to receive or allocate compositor-visible buffers, so **option (a) or (c) each need a ~300-line patch to -`wsi_common_wayland.c` in our own Wayland Turnip build** (banners-turnip-wayland -`build_turnip_wayland_wsi.sh`, Mesa `7cda7850`) plus a small private Wayland protocol. Nothing in +`wsi_common_wayland.c` in our own Wayland Turnip build** +(`build_turnip_wayland_wsi.sh`, Mesa `7cda7850`) plus a small private Wayland protocol. Nothing in the app can remove the copy on its own. Recommended: **option (a′) - the game's WSI allocates its swapchain images as `AHardwareBuffer`s (gralloc-native, UBWC), imports them through the AHB path Turnip already has, and hands the compositor the AHB over a Unix socket (`AHardwareBuffer_send/ @@ -77,7 +77,7 @@ Mesa's Wayland WSI creates every native swapchain image with `wsi_create_native_ (the Android-WSI import path, `tu_image.cc:880-925`) is only reachable from the Android swapchain. The patch (in our Wayland Turnip build): a new `create_mem` for the Wayland chain, selected when the -compositor advertises a private global `banner_layer_buffer_v1`: +compositor advertises a private global `droiddeck_layer_buffer_v1`: 1. `AHardwareBuffer_allocate(w, h, R8G8B8A8, GPU_COLOR_OUTPUT | GPU_SAMPLED_IMAGE)`; `vkGetAndroidHardwareBufferPropertiesANDROID` → `vkAllocateMemory` with `VkImportAndroidHardwareBufferInfoANDROID` (Turnip: `tu_device.cc:3828`), bind - the image was @@ -85,7 +85,7 @@ compositor advertises a private global `banner_layer_buffer_v1`: 2. `wsi_image.dma_buf_fd = dup(native_handle->data[0])`, `drm_modifier` / `row_pitches[0]` from the same layout → the existing `zwp_linux_dmabuf_v1` path stays untouched: the compositor keeps importing a dma-buf and can keep the blit path as the fallback. -3. `banner_layer_buffer_v1.attach(wl_buffer, socket_fd)`: the WSI creates a `socketpair`, sends one +3. `droiddeck_layer_buffer_v1.attach(wl_buffer, socket_fd)`: the WSI creates a `socketpair`, sends one end in the request, and calls `AHardwareBuffer_sendHandleToUnixSocket(ahb, other_end)`; the compositor's request handler does `AHardwareBuffer_recvHandleFromUnixSocket` and stores the AHB on `struct dmabuf_buffer`. Per swapchain image, once - not per frame. @@ -262,7 +262,7 @@ D3D12 tabs) as the workload, session log in `Download/Wayland-logs/`. since the blit only changed its destination) and `dumpsys gfxinfo`/battery for 5 min each. This is the baseline the WSI patch is measured against. 4. **Fence probe outcome → choose the acquire-fence design** (§3) before starting the WSI patch. -5. **WSI patch (option a) in banners-turnip-wayland**, wcp rebuild, then the same steps 1–3 with +5. **WSI patch (option a) in the Wayland Turnip build**, wcp rebuild, then the same steps 1–3 with the AHB arriving from the guest: log line to add on the compositor side `layer: buffer N of "" received from the game (AHardwareBuffer WxH, UBWC)` and the fps delta vs X11. @@ -296,7 +296,7 @@ unchanged. Off by default: with the variable unset no new code runs. Not zero-copy yet - it is the receive side. The copy disappears when step 5 lands and `sc_layer_present` is handed the game's own `AHardwareBuffer` instead of a pool slot. -## 7. Step 5 implemented (feat/wayland-zero-copy-wsi + banners-turnip-wayland `banner_ahb_wsi.py`) +## 7. Step 5 implemented (feat/wayland-zero-copy-wsi + the Wayland Turnip build `droiddeck_ahb_wsi.py`) Option (a′) as recommended, with one deviation forced by the build: the Wayland Turnip is a `platforms=wayland` build with Android detection off, so `VK_ANDROID_external_memory_android_hardware_buffer` diff --git a/app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-protocol.c b/app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-protocol.c similarity index 76% rename from app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-protocol.c rename to app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-protocol.c index 17b0c0dfd1..1c7e42dbf5 100644 --- a/app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-protocol.c +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-protocol.c @@ -38,7 +38,7 @@ extern const struct wl_interface wl_buffer_interface; -static const struct wl_interface *banner_ahb_v1_types[] = { +static const struct wl_interface *droiddeck_ahb_v1_types[] = { NULL, &wl_buffer_interface, NULL, @@ -50,18 +50,18 @@ static const struct wl_interface *banner_ahb_v1_types[] = { NULL, }; -static const struct wl_message banner_ahb_v1_requests[] = { - { "destroy", "", banner_ahb_v1_types + 0 }, - { "attach", "ohuuuuuu", banner_ahb_v1_types + 1 }, +static const struct wl_message droiddeck_ahb_v1_requests[] = { + { "destroy", "", droiddeck_ahb_v1_types + 0 }, + { "attach", "ohuuuuuu", droiddeck_ahb_v1_types + 1 }, }; -static const struct wl_message banner_ahb_v1_events[] = { - { "mode", "2u", banner_ahb_v1_types + 0 }, +static const struct wl_message droiddeck_ahb_v1_events[] = { + { "mode", "2u", droiddeck_ahb_v1_types + 0 }, }; -WL_PRIVATE const struct wl_interface banner_ahb_v1_interface = { - "banner_ahb_v1", 2, - 2, banner_ahb_v1_requests, - 1, banner_ahb_v1_events, +WL_PRIVATE const struct wl_interface droiddeck_ahb_v1_interface = { + "droiddeck_ahb_v1", 2, + 2, droiddeck_ahb_v1_requests, + 1, droiddeck_ahb_v1_events, }; diff --git a/app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-server-protocol.h b/app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-server-protocol.h similarity index 73% rename from app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-server-protocol.h rename to app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-server-protocol.h index 788982c105..118ca6c611 100644 --- a/app/src/main/cpp/waylandcomp/generated/banner-ahb-v1-server-protocol.h +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-ahb-v1-server-protocol.h @@ -1,6 +1,6 @@ -#ifndef BANNER_AHB_V1_SERVER_PROTOCOL_H -#define BANNER_AHB_V1_SERVER_PROTOCOL_H +#ifndef DROIDDECK_AHB_V1_SERVER_PROTOCOL_H +#define DROIDDECK_AHB_V1_SERVER_PROTOCOL_H #include #include @@ -14,7 +14,7 @@ struct wl_client; struct wl_resource; /* - * @section page_copyright_banner_ahb_v1 Copyright + * @section page_copyright_droiddeck_ahb_v1 Copyright * * Copyright 2026 The412Banner * @@ -42,15 +42,15 @@ struct wl_resource; -struct banner_ahb_v1; +struct droiddeck_ahb_v1; struct wl_buffer; -#ifndef BANNER_AHB_V1_INTERFACE -#define BANNER_AHB_V1_INTERFACE -extern const struct wl_interface banner_ahb_v1_interface; +#ifndef DROIDDECK_AHB_V1_INTERFACE +#define DROIDDECK_AHB_V1_INTERFACE +extern const struct wl_interface droiddeck_ahb_v1_interface; #endif -struct banner_ahb_v1_interface { +struct droiddeck_ahb_v1_interface { void (*destroy)(struct wl_client *client, struct wl_resource *resource); void (*attach)(struct wl_client *client, @@ -65,17 +65,17 @@ struct banner_ahb_v1_interface { uint32_t image_count); }; -#define BANNER_AHB_V1_MODE 0 +#define DROIDDECK_AHB_V1_MODE 0 -#define BANNER_AHB_V1_MODE_SINCE_VERSION 2 +#define DROIDDECK_AHB_V1_MODE_SINCE_VERSION 2 -#define BANNER_AHB_V1_DESTROY_SINCE_VERSION 1 -#define BANNER_AHB_V1_ATTACH_SINCE_VERSION 1 +#define DROIDDECK_AHB_V1_DESTROY_SINCE_VERSION 1 +#define DROIDDECK_AHB_V1_ATTACH_SINCE_VERSION 1 static inline void -banner_ahb_v1_send_mode(struct wl_resource *resource_, uint32_t enabled) +droiddeck_ahb_v1_send_mode(struct wl_resource *resource_, uint32_t enabled) { - wl_resource_post_event(resource_, BANNER_AHB_V1_MODE, enabled); + wl_resource_post_event(resource_, DROIDDECK_AHB_V1_MODE, enabled); } #ifdef __cplusplus diff --git a/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-protocol.c b/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-protocol.c new file mode 100644 index 0000000000..bd26d77a28 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-protocol.c @@ -0,0 +1,59 @@ +/* + * Copyright 2026 DroidDeck contributors + * + * 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 "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 + + +static const struct wl_interface *droiddeck_refresh_v1_types[] = { + NULL, + NULL, +}; + +static const struct wl_message droiddeck_refresh_v1_requests[] = { + { "destroy", "", droiddeck_refresh_v1_types + 0 }, + { "set_target", "uu", droiddeck_refresh_v1_types + 0 }, +}; + +static const struct wl_message droiddeck_refresh_v1_events[] = { + { "rate", "u", droiddeck_refresh_v1_types + 0 }, + { "done", "", droiddeck_refresh_v1_types + 0 }, +}; + +WL_PRIVATE const struct wl_interface droiddeck_refresh_v1_interface = { + "droiddeck_refresh_v1", 1, + 2, droiddeck_refresh_v1_requests, + 2, droiddeck_refresh_v1_events, +}; + diff --git a/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-server-protocol.h b/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-server-protocol.h new file mode 100644 index 0000000000..32d1c17782 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-refresh-v1-server-protocol.h @@ -0,0 +1,175 @@ + +#ifndef DROIDDECK_REFRESH_V1_SERVER_PROTOCOL_H +#define DROIDDECK_REFRESH_V1_SERVER_PROTOCOL_H + +#include +#include +#include "wayland-server.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct wl_client; +struct wl_resource; + +/** + * @page page_droiddeck_refresh_v1 The droiddeck_refresh_v1 protocol + * @section page_ifaces_droiddeck_refresh_v1 Interfaces + * - @subpage page_iface_droiddeck_refresh_v1 - panel refresh rates a nested compositor may ask for + * @section page_copyright_droiddeck_refresh_v1 Copyright + *
+ *
+ * Copyright 2026 DroidDeck contributors
+ *
+ * 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 droiddeck_refresh_v1; + +#ifndef DROIDDECK_REFRESH_V1_INTERFACE +#define DROIDDECK_REFRESH_V1_INTERFACE +/** + * @page page_iface_droiddeck_refresh_v1 droiddeck_refresh_v1 + * @section page_iface_droiddeck_refresh_v1_desc Description + * + * A nested compositor paces its clients against the refresh rate of the + * panel it is shown on. When its clients are held to a frame rate the + * panel's current rate does not divide evenly, frames are shown for an + * uneven number of refreshes. This interface lets the nested compositor + * see every refresh rate the panel can run at its current size and ask + * for the one that suits the frame rate it is pacing to. + * + * On bind the compositor sends one rate event per refresh rate, lowest + * first, followed by done. The list is sent again, in full, whenever it + * changes (a different panel, or a limit the user placed on the panel's + * rate). The rate the panel is running at is still reported the standard + * way, through wl_output.mode. + * + * A request is a preference, not a guarantee: the user, the platform or + * another output mirroring the panel may hold the panel at another rate. + * The client reads the result from wl_output.mode. + * @section page_iface_droiddeck_refresh_v1_api API + * See @ref iface_droiddeck_refresh_v1. + */ +/** + * @defgroup iface_droiddeck_refresh_v1 The droiddeck_refresh_v1 interface + * + * A nested compositor paces its clients against the refresh rate of the + * panel it is shown on. When its clients are held to a frame rate the + * panel's current rate does not divide evenly, frames are shown for an + * uneven number of refreshes. This interface lets the nested compositor + * see every refresh rate the panel can run at its current size and ask + * for the one that suits the frame rate it is pacing to. + * + * On bind the compositor sends one rate event per refresh rate, lowest + * first, followed by done. The list is sent again, in full, whenever it + * changes (a different panel, or a limit the user placed on the panel's + * rate). The rate the panel is running at is still reported the standard + * way, through wl_output.mode. + * + * A request is a preference, not a guarantee: the user, the platform or + * another output mirroring the panel may hold the panel at another rate. + * The client reads the result from wl_output.mode. + */ +extern const struct wl_interface droiddeck_refresh_v1_interface; +#endif + +/** + * @ingroup iface_droiddeck_refresh_v1 + * @struct droiddeck_refresh_v1_interface + */ +struct droiddeck_refresh_v1_interface { + /** + * destroy the object + * + * The preference set through this object is dropped. + */ + void (*destroy)(struct wl_client *client, + struct wl_resource *resource); + /** + * ask for a refresh rate + * + * refresh is the panel rate the client would like, in Hz, taken + * from the advertised list; 0 withdraws the preference. frame_rate + * is the frame rate the client holds its content to, in frames per + * second, or 0 when the content is not held to a rate. The + * compositor may multiply the content's frame rate itself + * (generated frames); when it does, it picks the advertised rate + * that the multiplied frame rate divides evenly instead of the + * requested one. + * @param refresh wanted panel refresh rate in Hz, 0 for none + * @param frame_rate content frame rate in frames per second, 0 for unpaced + */ + void (*set_target)(struct wl_client *client, + struct wl_resource *resource, + uint32_t refresh, + uint32_t frame_rate); +}; + +#define DROIDDECK_REFRESH_V1_RATE 0 +#define DROIDDECK_REFRESH_V1_DONE 1 + +/** + * @ingroup iface_droiddeck_refresh_v1 + */ +#define DROIDDECK_REFRESH_V1_RATE_SINCE_VERSION 1 +/** + * @ingroup iface_droiddeck_refresh_v1 + */ +#define DROIDDECK_REFRESH_V1_DONE_SINCE_VERSION 1 + +/** + * @ingroup iface_droiddeck_refresh_v1 + */ +#define DROIDDECK_REFRESH_V1_DESTROY_SINCE_VERSION 1 +/** + * @ingroup iface_droiddeck_refresh_v1 + */ +#define DROIDDECK_REFRESH_V1_SET_TARGET_SINCE_VERSION 1 + +/** + * @ingroup iface_droiddeck_refresh_v1 + * Sends an rate event to the client owning the resource. + * @param resource_ The client's resource + * @param refresh panel refresh rate in Hz + */ +static inline void +droiddeck_refresh_v1_send_rate(struct wl_resource *resource_, uint32_t refresh) +{ + wl_resource_post_event(resource_, DROIDDECK_REFRESH_V1_RATE, refresh); +} + +/** + * @ingroup iface_droiddeck_refresh_v1 + * Sends an done event to the client owning the resource. + * @param resource_ The client's resource + */ +static inline void +droiddeck_refresh_v1_send_done(struct wl_resource *resource_) +{ + wl_resource_post_event(resource_, DROIDDECK_REFRESH_V1_DONE); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/app/src/main/cpp/waylandcomp/protocols/banner-ahb-v1.xml b/app/src/main/cpp/waylandcomp/protocols/droiddeck-ahb-v1.xml similarity index 98% rename from app/src/main/cpp/waylandcomp/protocols/banner-ahb-v1.xml rename to app/src/main/cpp/waylandcomp/protocols/droiddeck-ahb-v1.xml index 1560c8f7cb..a40b0dcd88 100644 --- a/app/src/main/cpp/waylandcomp/protocols/banner-ahb-v1.xml +++ b/app/src/main/cpp/waylandcomp/protocols/droiddeck-ahb-v1.xml @@ -1,5 +1,5 @@ - + Copyright 2026 The412Banner @@ -23,7 +23,7 @@ DEALINGS IN THE SOFTWARE. - + Zero-copy window layers on Android. A Vulkan swapchain image that the client allocated as an Android AHardwareBuffer (gralloc) is still shared diff --git a/app/src/main/cpp/waylandcomp/protocols/droiddeck-refresh-v1.xml b/app/src/main/cpp/waylandcomp/protocols/droiddeck-refresh-v1.xml new file mode 100644 index 0000000000..c4464a0416 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/protocols/droiddeck-refresh-v1.xml @@ -0,0 +1,81 @@ + + + + Copyright 2026 DroidDeck contributors + + 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. + + + + + A nested compositor paces its clients against the refresh rate of the + panel it is shown on. When its clients are held to a frame rate the + panel's current rate does not divide evenly, frames are shown for an + uneven number of refreshes. This interface lets the nested compositor + see every refresh rate the panel can run at its current size and ask + for the one that suits the frame rate it is pacing to. + + On bind the compositor sends one rate event per refresh rate, lowest + first, followed by done. The list is sent again, in full, whenever it + changes (a different panel, or a limit the user placed on the panel's + rate). The rate the panel is running at is still reported the standard + way, through wl_output.mode. + + A request is a preference, not a guarantee: the user, the platform or + another output mirroring the panel may hold the panel at another rate. + The client reads the result from wl_output.mode. + + + + + The preference set through this object is dropped. + + + + + + refresh is the panel rate the client would like, in Hz, taken from + the advertised list; 0 withdraws the preference. frame_rate is the + frame rate the client holds its content to, in frames per second, or + 0 when the content is not held to a rate. The compositor may multiply + the content's frame rate itself (generated frames); when it does, it + picks the advertised rate that the multiplied frame rate divides + evenly instead of the requested one. + + + + + + + + Sent once per rate, lowest first, in Hz rounded to the nearest whole + number. + + + + + + + Ends a list of rate events. The rates received since the previous + done replace the earlier list. + + + + diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c index e33b0c77b4..c31915a45b 100644 --- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c +++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c @@ -4,7 +4,7 @@ #include "droiddeck_ext.h" #include "sc_layer.h" #include "vk_present.h" -#include "banner-ahb-v1-server-protocol.h" +#include "droiddeck-ahb-v1-server-protocol.h" #include #include #include @@ -25,6 +25,7 @@ struct droiddeck_dma_buf_sync_file { uint32_t flags; int32_t fd; }; #define DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE _IOW('b', 3, struct droiddeck_dma_buf_sync_file) extern volatile int g_zero_copy; +void droiddeck_dmabuf_formats_stale(void); struct ahb_buf { uint64_t id; @@ -37,6 +38,7 @@ struct ahb_buf { struct wl_client *client; struct wl_resource *resource; struct wl_listener resource_destroy; + int display; int on_layer; int release_pending; int64_t deferred_ns; @@ -131,10 +133,10 @@ static void handle_released(uint64_t id, int fd) { if (fd >= 0) { struct droiddeck_dma_buf_sync_file imp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = fd}; int dmabuf_fd = droiddeck_dmabuf_fd(ab->b); - if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) { + if (!ab->display && dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) { close(fd); } else { - if (!g_import_failed_logged) { + if (!ab->display && !g_import_failed_logged) { g_import_failed_logged = 1; droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_IMPORT_SYNC_FILE failed (%s): releases wait for the display's fence here instead", strerror(errno)); @@ -187,7 +189,7 @@ int ahb_swapchain_has_ahb(const struct dmabuf_buffer *b) { return b && *droiddeck_dmabuf_ahb_slot((struct dmabuf_buffer *)b) != NULL; } -int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h) { +int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h, const struct vkp_draw *draw) { struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot(b) : NULL; if (!ab) return -1; int dmabuf_fd = droiddeck_dmabuf_fd(b); @@ -205,7 +207,7 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_ int r; do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); } - int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, + int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw, s ? droiddeck_surface_color(s) : NULL, ab->format); if (r < 0) return -1; if (r == 1) return 0; @@ -259,6 +261,58 @@ uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b) { } +static int adopt(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b, AHardwareBuffer *ahb, + uint32_t stride, uint32_t image_count, uint64_t modifier) { + AHardwareBuffer_Desc d; + AHardwareBuffer_describe(ahb, &d); + int bw, bh; + droiddeck_dmabuf_size(b, &bw, &bh); + struct ahb_buf *ab = calloc(1, sizeof(*ab)); + if (!ab) return -1; + ab->id = g_next_id++; + ab->b = b; + droiddeck_dmabuf_ref(b); + ab->ahb = ahb; + ab->w = bw; ab->h = bh; + ab->stride = d.stride ? d.stride : stride; + ab->image_count = image_count; + ab->format = d.format; + ab->modifier = modifier; + ab->client = c; + ab->resource = buffer; + ab->resource_destroy.notify = on_buffer_resource_destroyed; + wl_resource_add_destroy_listener(buffer, &ab->resource_destroy); + ab->fence_fd = -1; + wl_list_insert(g_bufs.prev, &ab->link); + *droiddeck_dmabuf_ahb_slot(b) = ab; + + if (g_last_chain.client != c || g_last_chain.w != bw || g_last_chain.h != bh || + g_last_chain.image_count != image_count || g_last_chain.modifier != modifier || g_last_chain.format != d.format) { + char count[32] = ""; + if (image_count) snprintf(count, sizeof(count), "%u images, ", image_count); + g_last_chain = (struct chain_seen){c, bw, bh, image_count, modifier, d.format}; + droiddeck_log("layer", "zero-copy: %s from %s (%s%dx%d, %s, %s, stride %u px)", + image_count ? "AHB swapchain" : "display buffers", droiddeck_client_name(c), count, bw, bh, + droiddeck_ahb_format_name(d.format), modifier == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)" + : modifier == 0 ? "linear" : "unknown modifier", ab->stride); + } + return 0; +} + +int ahb_swapchain_adopt(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b, AHardwareBuffer *ahb, + uint64_t modifier) { + if (!g_advertised || *droiddeck_dmabuf_ahb_slot(b)) return -1; + AHardwareBuffer_acquire(ahb); + if (adopt(c, buffer, b, ahb, 0, 0, modifier) != 0) { AHardwareBuffer_release(ahb); return -1; } + ((struct ahb_buf *)*droiddeck_dmabuf_ahb_slot(b))->display = 1; + return 0; +} + +AHardwareBuffer *ahb_swapchain_display_buffer(const struct dmabuf_buffer *b) { + struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot((struct dmabuf_buffer *)b) : NULL; + return ab && ab->display ? ab->ahb : NULL; +} + static void ahb_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } static void ahb_attach(struct wl_client *c, struct wl_resource *r, struct wl_resource *buffer, int32_t sock, @@ -295,36 +349,13 @@ static void ahb_attach(struct wl_client *c, struct wl_resource *r, struct wl_res AHardwareBuffer_release(ahb); return; } - - struct ahb_buf *ab = calloc(1, sizeof(*ab)); - if (!ab) { AHardwareBuffer_release(ahb); wl_client_post_no_memory(c); return; } - ab->id = g_next_id++; - ab->b = b; - droiddeck_dmabuf_ref(b); - ab->ahb = ahb; - ab->w = bw; ab->h = bh; - ab->stride = d.stride ? d.stride : stride; - ab->image_count = image_count; - ab->format = d.format; - ab->modifier = modifier; - ab->client = c; - ab->resource = buffer; - ab->resource_destroy.notify = on_buffer_resource_destroyed; - wl_resource_add_destroy_listener(buffer, &ab->resource_destroy); - ab->fence_fd = -1; - wl_list_insert(g_bufs.prev, &ab->link); - *slot = ab; - - if (g_last_chain.client != c || g_last_chain.w != bw || g_last_chain.h != bh || - g_last_chain.image_count != image_count || g_last_chain.modifier != modifier || g_last_chain.format != d.format) { - g_last_chain = (struct chain_seen){c, bw, bh, image_count, modifier, d.format}; - droiddeck_log("layer", "zero-copy: AHB swapchain from %s (%u images, %dx%d, %s, %s, stride %u px)", droiddeck_client_name(c), - image_count, bw, bh, droiddeck_ahb_format_name(d.format), modifier == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)" - : modifier == 0 ? "linear" : "unknown modifier", ab->stride); + if (adopt(c, buffer, b, ahb, stride, image_count, modifier) != 0) { + AHardwareBuffer_release(ahb); + wl_client_post_no_memory(c); } } -static const struct banner_ahb_v1_interface ahb_impl = { +static const struct droiddeck_ahb_v1_interface ahb_impl = { .destroy = ahb_destroy, .attach = ahb_attach, }; @@ -336,20 +367,21 @@ static void on_client_resource_destroyed(struct wl_resource *r) { static void bind_ahb(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { static struct wl_client *last_named; if (ver > 2) ver = 2; - struct wl_resource *r = wl_resource_create(c, &banner_ahb_v1_interface, (int)ver, id); + struct wl_resource *r = wl_resource_create(c, &droiddeck_ahb_v1_interface, (int)ver, id); if (!r) { wl_client_post_no_memory(c); return; } wl_resource_set_implementation(r, &ahb_impl, NULL, on_client_resource_destroyed); wl_list_insert(&g_clients, wl_resource_get_link(r)); - if (ver >= BANNER_AHB_V1_MODE_SINCE_VERSION) banner_ahb_v1_send_mode(r, g_zero_copy ? 1u : 0u); + if (ver >= DROIDDECK_AHB_V1_MODE_SINCE_VERSION) droiddeck_ahb_v1_send_mode(r, g_zero_copy ? 1u : 0u); if (last_named != c) { last_named = c; - droiddeck_log("layer", "zero-copy: %s bound banner_ahb_v1 version %u (%s)", droiddeck_client_name(c), ver, + droiddeck_log("layer", "zero-copy: %s bound droiddeck_ahb_v1 version %u (%s)", droiddeck_client_name(c), ver, ver >= 2 ? "follows the live switch" : "version 1: decides from its launch environment only"); } } void ahb_swapchain_set_mode(int on, int live) { on = on ? 1 : 0; + if (g_zero_copy != on) droiddeck_dmabuf_formats_stale(); g_zero_copy = on; if (!g_advertised) { if (live) droiddeck_log("layer", "zero-copy switched %s from the drawer, but no display layer is available on this device: no change", @@ -361,8 +393,8 @@ void ahb_swapchain_set_mode(int on, int live) { int told = 0; struct wl_resource *r; wl_resource_for_each(r, &g_clients) { - if (wl_resource_get_version(r) >= BANNER_AHB_V1_MODE_SINCE_VERSION) { - banner_ahb_v1_send_mode(r, (uint32_t)on); + if (wl_resource_get_version(r) >= DROIDDECK_AHB_V1_MODE_SINCE_VERSION) { + droiddeck_ahb_v1_send_mode(r, (uint32_t)on); told++; } } @@ -385,7 +417,7 @@ void ahb_swapchain_init(struct wl_display *display) { wl_list_init(&g_bufs); wl_list_init(&g_clients); if (!sc_layer_available()) { - droiddeck_log("layer", "zero-copy: no display layer on this device (see the line above): banner_ahb_v1 not advertised"); + droiddeck_log("layer", "zero-copy: no display layer on this device (see the line above): droiddeck_ahb_v1 not advertised"); return; } g_loop = wl_display_get_event_loop(display); @@ -395,11 +427,11 @@ void ahb_swapchain_init(struct wl_display *display) { return; } wl_event_loop_add_fd(g_loop, g_rel_pipe[0], WL_EVENT_READABLE, on_release_pipe, NULL); - if (!wl_global_create(display, &banner_ahb_v1_interface, 2, NULL, bind_ahb)) { - droiddeck_log("error", "zero-copy: banner_ahb_v1 global creation failed"); + if (!wl_global_create(display, &droiddeck_ahb_v1_interface, 2, NULL, bind_ahb)) { + droiddeck_log("error", "zero-copy: droiddeck_ahb_v1 global creation failed"); return; } g_advertised = 1; - droiddeck_log("layer", "zero-copy: banner_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)"); + droiddeck_log("layer", "zero-copy: droiddeck_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)"); ahb_swapchain_set_mode(g_zero_copy, 0); } diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h index 7774482734..9002e6fc0a 100644 --- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h +++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h @@ -2,16 +2,21 @@ #define AHB_SWAPCHAIN_H #include #include +#include #include struct dmabuf_buffer; struct surface; +struct vkp_draw; void ahb_swapchain_init(struct wl_display *display); void ahb_swapchain_set_mode(int on, int live); int ahb_swapchain_last_frame_age_ms(void); int ahb_swapchain_has_ahb(const struct dmabuf_buffer *b); -int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h); +int ahb_swapchain_adopt(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b, AHardwareBuffer *ahb, + uint64_t modifier); +AHardwareBuffer *ahb_swapchain_display_buffer(const struct dmabuf_buffer *b); +int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h, const struct vkp_draw *draw); int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *buffer, struct surface *s, int paced); void ahb_swapchain_surface_gone(struct surface *s); unsigned ahb_swapchain_stats_take(void); diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index f78f0d3f86..461a0d6798 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -23,8 +23,10 @@ #include "linux-dmabuf-v1-server-protocol.h" #include "sc_layer.h" #include "ahb_swapchain.h" +#include "display_buffers.h" #include "viewporter-server-protocol.h" #include "droiddeck-desktop-v1-server-protocol.h" +#include "droiddeck-refresh-v1-server-protocol.h" #include "presentation-time-server-protocol.h" #include "pointer-constraints-unstable-v1-server-protocol.h" #include "relative-pointer-unstable-v1-server-protocol.h" @@ -218,6 +220,7 @@ struct surface { struct vkp_image *shm_img; + int black_fill; struct wl_resource *dmabuf; struct dmabuf_buffer *dmabuf_buf; struct wl_listener dmabuf_destroy; @@ -280,6 +283,8 @@ static int g_dirty; static int64_t g_dirty_since_ns; volatile int g_render_on_commit = 1; static int64_t g_rendered_tick_ns; +static int g_tick_spare; +static int g_scene_queues; static int g_tick_held; static int64_t g_hold_missed_ns; #define HOLD_RETRY_NS 1000000000LL @@ -289,7 +294,11 @@ static struct { int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns; const void *buffers[PACE_BUFFERS]; uint64_t game_frames_seen; + unsigned gaps[4]; } g_pace; +static int64_t g_game_frame_ns; + +static void note_game_frame_gap(void); static void pace_note_buffer(const void *buffer) { for (unsigned i = 0; i < g_pace.distinct && i < PACE_BUFFERS; i++) @@ -318,6 +327,16 @@ volatile int g_hide_shell; volatile int g_zero_copy; static int g_zero_copy_paused; +extern volatile int g_display_buffer_driver; +extern void droiddeck_on_overlay_planes(int planes); +static int g_overlay_planes_told = -1; + +static void tell_overlay_planes(void) { + const int planes = (g_zero_copy && g_display_buffer_driver) ? (sc_layer_overlay_affordable() ? 1 : 0) : -1; + if (planes == g_overlay_planes_told) return; + g_overlay_planes_told = planes; + droiddeck_on_overlay_planes(planes); +} static int g_zero_copy_fx_skip_said; volatile int g_ubwc = 1; @@ -689,6 +708,13 @@ const struct wl_buffer_interface dbuf_buffer_impl = { .destroy = dbuf_buffer_destroy_req, }; +static struct vkp_image *import_dmabuf(struct dmabuf_buffer *b) { + AHardwareBuffer *ahb = ahb_swapchain_display_buffer(b); + struct vkp_image *img = ahb ? vkp_image_from_ahb(ahb) : NULL; + return img ? img : vkp_image_from_dmabuf(b->fd[0], b->format, b->modifier, b->width, b->height, b->stride[0], + b->offset[0]); +} + static struct dmabuf_buffer *get_dmabuf(struct wl_resource *buffer) { if (buffer && wl_resource_instance_of(buffer, &wl_buffer_interface, &dbuf_buffer_impl)) return wl_resource_get_user_data(buffer); @@ -711,6 +737,11 @@ static void describe(const struct surface *s, char *out, size_t size) { else snprintf(out, size, "window %#x (%s)", w->hwnd, prog); } +static int is_steam_client_surface(const struct surface *s) { + const char *name = client_name(wl_resource_get_client(s->resource)); + return strcmp(name, "steam") == 0 || strstr(name, "steamwebhelper") != NULL; +} + static struct surface *toplevel_by_hwnd(uint32_t hwnd) { struct surface *s; wl_list_for_each(s, &g_toplevels, toplevel_link) @@ -868,6 +899,13 @@ int droiddeck_hud_frame_times(float *out, int len, int64_t *total) { static uint64_t g_game_frames; extern void droiddeck_on_game_surface(const char *window, const char *gpu); extern void droiddeck_on_game_frame(void); +extern void droiddeck_on_compositor_frame(void); +extern void droiddeck_on_content_rate(int fps); +static int64_t g_cadence_ns; +static int64_t g_cadence_frames; +static int g_content_fps; +static int g_framegen_layer_said; +static int g_framegen_layer; extern void droiddeck_on_game_program(int pid, const char *program); static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_resource *buffer) { @@ -888,6 +926,7 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res s->buf_w = w; s->buf_h = h; s->buf_alpha = wl_shm_buffer_get_format(shm) == WL_SHM_FORMAT_ARGB8888; + s->black_fill = 0; s->has_content = s->shm_img != NULL; g_stat_shm++; struct client_info *ci = client_info_of(wl_resource_get_client(s->resource)); @@ -916,9 +955,10 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res g_hud_shm = s; g_hud_shm_ns = now; g_hud_new = 1; - droiddeck_on_game_frame(); } } + if (s == g_hud_shm && (!g_hud_surface || now_ns() - g_hud_last_ns > 1000000000LL)) + droiddeck_on_compositor_frame(); } static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) { @@ -932,6 +972,7 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou s->buf_w = 1; s->buf_h = 1; s->buf_alpha = bgra[3] != 0xff; + s->black_fill = !bgra[0] && !bgra[1] && !bgra[2] && bgra[3] == 0xff; s->has_content = s->shm_img != NULL; } @@ -950,8 +991,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re wl_resource_add_destroy_listener(buffer, &s->dmabuf_destroy); } if (!b->img && !b->import_failed && b->n_planes >= 1) { - b->img = vkp_image_from_dmabuf(b->fd[0], b->format, b->modifier, b->width, b->height, - b->stride[0], b->offset[0]); + b->img = import_dmabuf(b); if (b->img && g_zero_copy) sc_layer_probe_dmabuf_fd(b->fd[0]); if (!b->img) { b->import_failed = 1; @@ -992,7 +1032,8 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re droiddeck_log("error", "could not import GPU frames from %s (%dx%d, modifier %#llx)", name, b->width, b->height, (unsigned long long)b->modifier); } - if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) && + if (s != g_hud_surface && !is_steam_client_surface(s) && + (b->img || ahb_swapchain_has_ahb(b)) && (!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) || (announced_now && !below_surface(g_hud_surface, s) && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) { @@ -1017,9 +1058,30 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re : "the compositor's driver could NOT import it (nothing can show it)"); s->hdr_fmt_logged = b->format; } - if (s == g_hud_surface) { + if (s == g_hud_surface && !is_steam_client_surface(s)) { g_hud_alive_ns = now_ns(); - if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; droiddeck_on_game_frame(); } + if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; note_game_frame_gap(); droiddeck_on_game_frame(); } + } else if (is_steam_client_surface(s) && !repeat && + (!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL)) { + droiddeck_on_compositor_frame(); + } +} + +static void note_game_frame_gap(void) { + const int64_t now = now_ns(); + if (g_game_frame_ns && g_refresh_ns > 0) { + const int64_t gap = (now - g_game_frame_ns + g_refresh_ns / 2) / g_refresh_ns; + g_pace.gaps[gap < 1 ? 0 : gap > 4 ? 3 : gap - 1]++; + } + if (g_game_frame_ns && now - g_game_frame_ns >= 1000000000LL) { g_cadence_ns = 0; g_cadence_frames = 0; } + g_game_frame_ns = now; + if (!g_cadence_ns) g_cadence_ns = now; + g_cadence_frames++; + if (now - g_cadence_ns >= 1000000000LL) { + g_content_fps = (int)((g_cadence_frames * 1000000000LL + (now - g_cadence_ns) / 2) / (now - g_cadence_ns)); + droiddeck_on_content_rate(g_content_fps); + g_cadence_ns = now; + g_cadence_frames = 0; } } @@ -1204,8 +1266,7 @@ static void cursor_publish_buffer(struct surface *s, struct wl_resource *buffer) } else if (db && db->n_planes >= 1 && db->width > 0 && db->height > 0 && (int64_t)db->width * db->height <= CURSOR_MAX_PX) { if (!db->img && !db->import_failed) { - db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height, - db->stride[0], db->offset[0]); + db->img = import_dmabuf(db); if (!db->img) db->import_failed = 1; } if (!db->img) return; @@ -1213,8 +1274,9 @@ static void cursor_publish_buffer(struct surface *s, struct wl_resource *buffer) int r; do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); if (vkp_image_readback(db->img, g_cursor_rb, CURSOR_MAX_PX) != 0) return; + const int row = vkp_image_width(db->img); cursor_publish_pixels((const uint8_t *)g_cursor_rb, db->width, db->height, - (size_t)db->width * 4, g_cursor_hx, g_cursor_hy); + (size_t)(row > db->width ? row : db->width) * 4, g_cursor_hx, g_cursor_hy); } else { return; } @@ -1884,6 +1946,57 @@ static void output_send_mode(struct wl_resource *r, int mhz) { mhz); } +#define PANEL_RATES_MAX 16 +extern void droiddeck_on_refresh_target(int refresh, int frame_rate); +static pthread_mutex_t g_panel_rates_lock = PTHREAD_MUTEX_INITIALIZER; +static int g_panel_rates[PANEL_RATES_MAX], g_panel_rate_count; +static atomic_int g_panel_rates_pending; +static struct wl_list g_refresh_clients; +static struct wl_resource *g_refresh_target_owner; + +static void refresh_send_rates(struct wl_resource *r) { + int rates[PANEL_RATES_MAX]; + pthread_mutex_lock(&g_panel_rates_lock); + const int count = g_panel_rate_count; + memcpy(rates, g_panel_rates, sizeof(rates)); + pthread_mutex_unlock(&g_panel_rates_lock); + for (int i = 0; i < count; i++) droiddeck_refresh_v1_send_rate(r, (uint32_t)rates[i]); + droiddeck_refresh_v1_send_done(r); +} + +static void refresh_notify_rates(void) { + struct wl_resource *r; + wl_resource_for_each(r, &g_refresh_clients) refresh_send_rates(r); +} + +static void refresh_resource_destroy(struct wl_resource *r) { + wl_list_remove(wl_resource_get_link(r)); + if (g_refresh_target_owner != r) return; + g_refresh_target_owner = NULL; + droiddeck_on_refresh_target(0, 0); +} + +static void refresh_destroy_req(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } + +static void refresh_set_target(struct wl_client *c, struct wl_resource *r, uint32_t refresh, uint32_t frame_rate) { + if (!refresh && !frame_rate && g_refresh_target_owner && g_refresh_target_owner != r) return; + g_refresh_target_owner = refresh || frame_rate ? r : NULL; + droiddeck_on_refresh_target((int)refresh, (int)frame_rate); +} + +static const struct droiddeck_refresh_v1_interface refresh_impl = { + .destroy = refresh_destroy_req, + .set_target = refresh_set_target, +}; + +static void bind_refresh(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { + struct wl_resource *r = wl_resource_create(c, &droiddeck_refresh_v1_interface, ver, id); + if (!r) { wl_client_post_no_memory(c); return; } + wl_resource_set_implementation(r, &refresh_impl, NULL, refresh_resource_destroy); + wl_list_insert(&g_refresh_clients, wl_resource_get_link(r)); + refresh_send_rates(r); +} + 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; } @@ -2014,19 +2127,47 @@ static int on_frame_timer(void *data) { return 0; } +static int black_fill_below(const struct draw_list *dl, int n) { + for (int i = 0; i < n; i++) { + struct surface *s, *found = NULL; + wl_list_for_each(s, &g_surfaces, link) + if (s->shm_img == dl->d[i].img) { found = s; break; } + if (!found || !found->black_fill || dl->d[i].blend) return 0; + } + return 1; +} + static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) { for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) { const struct vkp_draw *d = &dl->d[i]; if (d->blend) continue; if (!vkp_image_is_dmabuf(d->img)) continue; - if (d->dx != 0 || d->dy != 0 || d->dw != scene_w || d->dh != scene_h) continue; - if (d->sx != 0 || d->sy != 0 || (int)d->sw != vkp_image_width(d->img) || - (int)d->sh != vkp_image_height(d->img)) continue; + if (d->sx < 0 || d->sy < 0 || d->sw < 1.0f || d->sh < 1.0f || + d->sx + d->sw >= vkp_image_width(d->img) + 1.0f || + d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) continue; + if (d->dx == 0 && d->dy == 0 && d->dw == scene_w && d->dh == scene_h) return i; + if (d->dx < 0 || d->dy < 0 || d->dw <= 0 || d->dh <= 0 || d->dx + d->dw > scene_w || + d->dy + d->dh > scene_h || !black_fill_below(dl, i)) continue; return i; } return -1; } +static void note_copy_scene(const struct draw_list *dl, int scene_w, int scene_h, int pointer) { + static int said[6]; + const struct vkp_draw *t = dl->n > 0 ? &dl->d[dl->n - 1] : NULL; + const int now[6] = {dl->n, pointer, t ? t->dw : 0, t ? t->dh : 0, scene_w, scene_h}; + if (!memcmp(now, said, sizeof(said))) return; + memcpy(said, now, sizeof(said)); + if (pointer) + droiddeck_log("layer", "zero-copy: copy path while the pointer is drawn into the scene"); + else if (t) + droiddeck_log("layer", "zero-copy: copy path: no window fills the %dx%d scene on its own (%d surfaces, top one " + "%dx%d at %d,%d from %.2f,%.2f %.2fx%.2f of a %dx%d %s buffer%s)", scene_w, scene_h, dl->n, t->dw, t->dh, + t->dx, t->dy, t->sx, t->sy, t->sw, t->sh, vkp_image_width(t->img), vkp_image_height(t->img), + vkp_image_is_dmabuf(t->img) ? "GPU" : "memory", t->blend ? ", translucent" : ""); +} + static struct surface *surface_for_image(const struct vkp_image *img) { struct surface *s; wl_list_for_each(s, &g_surfaces, link) @@ -2066,17 +2207,28 @@ static struct surface *hdr_unimported_fullscreen(const struct draw_list *dl, int } static int is_hdr_surface(struct surface *s) { + const struct droiddeck_color *c = s ? droiddeck_color_of(s->resource) : NULL; + return c && (c->dataspace || c->convert); +} + +static int is_raw_hdr_surface(struct surface *s) { const struct droiddeck_color *c = s ? droiddeck_color_of(s->resource) : NULL; return c && c->dataspace; } +static int framegen_fits_layer(void) { + const int64_t rate = (int64_t)g_content_fps * (1 + vkp_framegen_extra_images()) * 1000; + return g_content_fps > 0 && + rate * 100 <= (int64_t)atomic_load(&g_output_refresh_mhz) * (g_framegen_layer ? 108 : 104); +} + static int hdr_plan(const struct draw_list *dl, int w, int h, int fx_on, int framegen, struct hdr_scene *hs) { memset(hs, 0, sizeof(*hs)); if (!droiddeck_color_hdr_open()) return 0; struct surface *un = hdr_unimported_fullscreen(dl, w, h); if (!un) { struct surface *lo = ahb_layer_only_candidate(w, h); - if (lo && is_hdr_surface(lo)) un = lo; + if (lo && is_raw_hdr_surface(lo)) un = lo; } if (un && g_zero_copy) { hs->color = droiddeck_color_of(un->resource); hs->who = un; return 3; } hs->hf.tonemap = !droiddeck_color_output(); @@ -2084,24 +2236,48 @@ static int hdr_plan(const struct draw_list *dl, int w, int h, int fx_on, int fra for (int i = 0; i < dl->n; i++) { struct surface *s = surface_for_image(dl->d[i].img); if (!is_hdr_surface(s)) continue; - hs->is_hdr[i] = 1; + const struct droiddeck_color *c = droiddeck_color_of(s->resource); + if (c->convert && hs->hf.convert && (hs->hf.convert->gain != c->gain || + memcmp(hs->hf.convert->to2020, c->to2020, sizeof(c->to2020)) != 0)) { + static int said; + if (!said) { + said = 1; + droiddeck_log("color", "two windows need different colour conversions in one frame: the upper one is " + "shown as SDR"); + } + continue; + } + hs->is_hdr[i] = c->convert ? 2 : 1; + if (c->convert) hs->hf.convert = c; hs->n_hdr++; - hs->color = droiddeck_color_of(s->resource); + hs->color = c; hs->who = s; } if (!hs->n_hdr) { free(hs->is_hdr); hs->is_hdr = NULL; return 0; } + if (hs->color->convert) { + static struct droiddeck_color composed; + composed = *hs->color; + composed.dataspace = DROIDDECK_ADATASPACE_BT2020_PQ; + composed.convert = 0; + hs->color = &composed; + } hs->hf.is_hdr = hs->is_hdr; hs->hf.color = hs->color; hs->hf.peak_nits = hs->color->max_cll > 0.0f ? hs->color->max_cll : hs->color->has_st2086 ? hs->color->max_lum : 1000.0f; - if (framegen) return 2; + if (framegen) { + if (!g_zero_copy || !framegen_fits_layer()) return 2; + hs->why = "frame generation is on"; + return 1; + } int li = g_zero_copy ? layer_candidate(dl, w, h) : -1; int over = li >= 0 ? dl->n - 1 - li : 0; - if (!hs->hf.tonemap && !fx_on && li >= 0 && hs->is_hdr[li] && + if (!hs->hf.tonemap && !hs->hf.convert && !fx_on && li >= 0 && hs->is_hdr[li] && (over == 0 || (over == 1 && sc_layer_overlay_affordable()))) return 0; hs->why = hs->hf.tonemap ? "HDR output is switched off in the drawer" : fx_on ? "screen effects are on" + : hs->hf.convert ? "its colours are converted to BT.2020 PQ" : !g_zero_copy ? "zero-copy presentation is off" : (li >= 0 && hs->is_hdr[li]) ? "a window is above the game and this display cannot compose a second layer" : "the HDR game is not one fullscreen window"; @@ -2174,8 +2350,7 @@ static void hdr_note_precedence(struct surface *hs, int fx_on, int framegen) { static void hdr_count_copied(const struct draw_list *dl, const char *reason) { for (int i = 0; i < dl->n; i++) { struct surface *s = surface_for_image(dl->d[i].img); - const struct droiddeck_color *c = s ? droiddeck_color_of(s->resource) : NULL; - if (!c || !c->dataspace) continue; + if (!is_hdr_surface(s)) continue; char name[160]; describe(s, name, sizeof(name)); droiddeck_color_frame_copied(name, reason); @@ -2317,6 +2492,8 @@ static void render_scene(void) { g_dirty_since_ns = 0; } g_dirty = 0; + if (g_rendered_tick_ns == g_tick_vsync_ns) g_tick_spare = 0; + g_scene_queues = 0; g_rendered_tick_ns = g_tick_vsync_ns; g_tick_held = 0; g_hud_fresh = 0; @@ -2378,7 +2555,13 @@ static void render_scene(void) { static int fell_back; vkp_apply_window_request(); sc_layer_hide_overlay(); - if (sc_layer_present_hdr_scene(dl.d, dl.n, &hs.hf, w, h, hs.color) == 0) { + const int generated = framegen ? sc_layer_present_generated(dl.d, dl.n, &hs.hf, w, h, 1, hs.color) : 0; + if (framegen) g_framegen_layer = generated >= 0; + if (generated > 0 && g_framegen_layer_said != 3) { + g_framegen_layer_said = 3; + droiddeck_log("framegen", "generated frames and the composed HDR picture go on the game's display layer"); + } + if (framegen ? generated >= 0 : sc_layer_present_hdr_scene(dl.d, dl.n, &hs.hf, w, h, hs.color) == 0) { rendered = vkp_base_black(w, h) == 0; if (fell_back) { fell_back = 0; droiddeck_log("color", "the composed picture is on the game's display layer again"); } } else { @@ -2404,13 +2587,16 @@ static void render_scene(void) { rendered = vkp_render(w, h, dl.d, dl.n) == 0; } else if (hdr_route == 0 || hdr_route == 3) { const int pass_on = fx_on || framegen; - int li = (g_zero_copy && !framegen && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1; + tell_overlay_planes(); + const int fg_layer = framegen && hdr_route == 0 && framegen_fits_layer(); + g_framegen_layer = fg_layer; + int li = (g_zero_copy && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1; int over = li >= 0 ? dl.n - 1 - li : 0; const int fx_blocks = (li >= 0 && fx_on && over > 0); if (fx_blocks) { li = -1; over = 0; } const int ov_blocks = (li >= 0 && over > 0 && !fx_blocks && !sc_layer_overlay_affordable()); if (ov_blocks) { li = -1; over = 0; } - const int blocked = framegen ? 1 : bfi ? 4 : (fx_blocks ? 2 : (ov_blocks ? 3 : 0)); + const int blocked = (framegen && !fg_layer) ? 1 : bfi ? 4 : (fx_blocks ? 2 : (ov_blocks ? 3 : 0)); if (g_zero_copy && !cursor_on && blocked != g_zero_copy_paused) { g_zero_copy_paused = blocked; if (blocked == 1) @@ -2419,14 +2605,21 @@ static void render_scene(void) { droiddeck_log("effects", "zero-copy paused: a window above the game needs the compositor pass for the whole scene"); else if (blocked == 4) droiddeck_log("bfi", "zero-copy paused: black frame insertion needs the compositor pass"); - else if (blocked == 3) - droiddeck_log("layer", "zero-copy paused: a window above the game would need a second display layer, " - "which this display cannot compose in hardware - whole scene on the copy path"); + else if (blocked == 3) { + const struct vkp_draw *top = &dl.d[dl.n - 1]; + struct surface *ts = surface_for_image(top->img); + droiddeck_log("layer", "zero-copy paused: a window above the game (%dx%d at %d,%d%s, %s) would need a second " + "display layer, which this display cannot compose in hardware - whole scene on the copy path", + top->dw, top->dh, top->dx, top->dy, top->blend ? ", translucent" : "", + ts ? client_name(wl_resource_get_client(ts->resource)) : "no client surface"); + } else droiddeck_log("effects", "zero-copy resumed: the game is back on its own display layer"); } struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL; + const struct vkp_draw *ld = li >= 0 ? &dl.d[li] : NULL; if (li < 0) ls = layer_only; + if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) note_copy_scene(&dl, w, h, cursor_on); if (cardboard) ls = NULL; if (cursor_on) ls = NULL; if (bfi) ls = NULL; @@ -2439,11 +2632,23 @@ static void render_scene(void) { if (li >= 0 || ls) { vkp_apply_window_request(); int r = -1; - if (!(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf)) - r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h); - if (r != 0 && li >= 0) + const int fg_pass = framegen && fx_on && li >= 0; + const int generated = (framegen && li >= 0) + ? sc_layer_present_generated(&dl.d[li], 1, NULL, w, h, fg_pass, + ls ? droiddeck_surface_color(ls) : NULL) : 0; + if (generated > 0 && g_framegen_layer_said != 1 + fg_pass) { + g_framegen_layer_said = 1 + fg_pass; + droiddeck_log("framegen", fg_pass + ? "generated frames and the game's frames go on the game's display layer straight from the screen effects pass" + : "generated frames go on the game's display layer between the game's own frames"); + } + if (fg_pass) + r = generated >= 0 ? 0 : -1; + else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf)) + r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld); + if (!fg_pass && generated >= 0 && r != 0 && li >= 0) r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h) - : sc_layer_present(dl.d[li].img, w, h, ls ? droiddeck_surface_color(ls) : NULL); + : sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL); if (r == 0) { if (ls) ls->drawn = 1; int go[8], ov = 0; @@ -2457,8 +2662,10 @@ static void render_scene(void) { hdr_copy = "the overlay layer refused the window above it"; } else { rendered = vkp_base_black(w, h) == 0; + g_scene_queues = sc_layer_queues(); } } else { + sc_layer_hide(); rendered = vkp_render(w, h, dl.d, dl.n) == 0; copy = 1; hdr_copy = "its display layer was unavailable this frame"; @@ -2518,8 +2725,12 @@ static int commit_renders_on(void) { !g_bfi_running; } +static int tick_takes_scene(void) { + return g_rendered_tick_ns != g_tick_vsync_ns || (g_tick_spare && g_scene_queues); +} + static int render_on_commit(void) { - return commit_renders_on() && !g_render_idle && g_rendered_tick_ns != g_tick_vsync_ns; + return commit_renders_on() && !g_render_idle && tick_takes_scene(); } static void schedule_render(void) { @@ -2546,7 +2757,7 @@ static int scene_waits_for_game(int64_t now) { static void on_commit_idle(void *data) { g_render_idle = NULL; - if (!g_dirty || !commit_renders_on() || g_rendered_tick_ns == g_tick_vsync_ns || scene_waits_for_game(now_ns())) return; + if (!g_dirty || !commit_renders_on() || !tick_takes_scene() || scene_waits_for_game(now_ns())) return; g_pace.commit_renders++; render_scene(); } @@ -2621,6 +2832,7 @@ static void on_vsync(int64_t frame_time_ns) { if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8; } g_last_vsync_ns = now; + g_tick_spare = g_rendered_tick_ns != g_tick_vsync_ns; g_tick_vsync_ns = frame_time_ns; int tick_change = 0; if (vkp_apply_window_request()) tick_change = 1; @@ -3843,6 +4055,10 @@ static int on_input_readable(int fd, uint32_t mask, void *data) { output_notify_mode(); wl_display_flush_clients(g_display); } + if (atomic_exchange(&g_panel_rates_pending, 0)) { + refresh_notify_rates(); + wl_display_flush_clients(g_display); + } if (vsync) on_vsync(vsync_ns); return 0; } @@ -3892,6 +4108,23 @@ void droiddeck_wayland_output_resized(void) { (void)n; } +void droiddeck_wayland_set_panel_rates(const int *rates, int count) { + if (count > PANEL_RATES_MAX) count = PANEL_RATES_MAX; + pthread_mutex_lock(&g_panel_rates_lock); + const int same = count == g_panel_rate_count && !memcmp(rates, g_panel_rates, (size_t)count * sizeof(int)); + if (!same) { + memcpy(g_panel_rates, rates, (size_t)count * sizeof(int)); + g_panel_rate_count = count; + } + pthread_mutex_unlock(&g_panel_rates_lock); + if (same || g_input_pipe[1] < 0) return; + atomic_store(&g_panel_rates_pending, 1); + struct input_msg m = { 10, 0, 0, 0, 0 }; + ssize_t n; + do { n = write(g_input_pipe[1], &m, sizeof(m)); } while (n < 0 && errno == EINTR); + (void)n; +} + void droiddeck_wayland_set_output_refresh_rate(int mhz) { if (mhz <= 0) mhz = 60000; if (atomic_exchange(&g_output_refresh_mhz, mhz) == mhz || g_input_pipe[1] < 0) return; @@ -3974,12 +4207,15 @@ static int on_stats_timer(void *data) { struct vkp_perf vp; vkp_perf_take(&vp); const unsigned drops = sc_layer_drops_take(); + unsigned aimed_next, aimed_later, aimed_even; + sc_layer_aim_take(&aimed_next, &aimed_later, &aimed_even); #define PERF_MS(sum, n) ((n) ? (double)(sum) / 1e6 / (double)(n) : 0.0) if (g_perf.scenes || vp.presents || g_perf.releases || drops) droiddeck_log("perf", "last 10 s: %u ticks, %u scenes, %u on screen (copy %u, zero-copy %u, layer copy %u) | " "render_scene %.2f/%.2f ms | base %u black kept, %u presented | acquire %.2f/%.2f ms | " "present %.2f/%.2f ms (%u) | fence wait %.2f/%.2f ms (%u, %u GPU release waits) | " - "release %.2f/%.2f ms (%u, %u held) | %u pool drops", + "release %.2f/%.2f ms (%u, %u held) | %u pool drops | layer frames timed for the next refresh %u, " + "the one after %u, held to an even step %u", g_perf.ticks, g_perf.scenes, g_stat_frames, g_perf.copy_scenes, zero_copy, layer_frames, PERF_MS(g_perf.scene_ns, g_perf.scenes), (double)g_perf.scene_max_ns / 1e6, vp.base_kept, vp.base_presents, @@ -3987,7 +4223,7 @@ static int on_stats_timer(void *data) { PERF_MS(vp.present_ns, vp.presents), (double)vp.present_max_ns / 1e6, vp.presents, PERF_MS(vp.wait_ns, vp.waits), (double)vp.wait_max_ns / 1e6, vp.waits, vp.gpu_release_waits, PERF_MS(g_perf.release_ns, g_perf.releases), (double)g_perf.release_max_ns / 1e6, - g_perf.releases, g_perf.releases_held, drops); + g_perf.releases, g_perf.releases_held, drops, aimed_next, aimed_later, aimed_even); #undef PERF_MS memset(&g_perf, 0, sizeof(g_perf)); } @@ -3997,12 +4233,12 @@ static int on_stats_timer(void *data) { droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | " "new frame waits %.2f/%.2f ms to be drawn (%u scenes, %u on arrival) | %llu game frames, %u re-attached after an " "empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, " - "%u not drawn", + "%u not drawn | game frames arrived 1/2/3/4+ refreshes apart %u/%u/%u/%u", g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6, g_pace.ticks, g_pace.ticks_late_2ms, g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6, g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct, - g_pace.presented, g_pace.replaced, g_pace.undrawn); + g_pace.presented, g_pace.replaced, g_pace.undrawn, g_pace.gaps[0], g_pace.gaps[1], g_pace.gaps[2], g_pace.gaps[3]); } if (g_bfi_stats.lit || g_bfi_stats.dark || g_bfi_stats.failed) { droiddeck_log("bfi", "last 10 s: %u pictures, %u black refreshes, %u black refreshes not presented", @@ -4028,6 +4264,12 @@ static int on_stats_timer(void *data) { "draw - expect a black picture (main device %u:%u)", ci->name, (unsigned)major(g_main_device), (unsigned)minor(g_main_device)); } + if (g_content_fps > 0 && now_ns() - g_game_frame_ns >= 2000000000LL) { + g_content_fps = 0; + g_cadence_ns = 0; + g_cadence_frames = 0; + droiddeck_on_content_rate(0); + } wl_event_source_timer_update(g_stats_timer, 10000); return 0; } @@ -4106,6 +4348,7 @@ int droiddeck_wayland_run(void) { wl_list_init(&g_surfaces); wl_list_init(&g_toplevels); wl_list_init(&g_outputs); + wl_list_init(&g_refresh_clients); wl_list_init(&g_constraints); wl_list_init(&g_relative_pointers); open_session_log(); @@ -4143,6 +4386,7 @@ int droiddeck_wayland_run(void) { wl_display_init_shm(display); wl_global_create(display, &wl_output_interface, 4, NULL, bind_output); + wl_global_create(display, &droiddeck_refresh_v1_interface, 1, NULL, bind_refresh); wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base); wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf); droiddeck_android_wlegl_init(display); @@ -4153,6 +4397,7 @@ int droiddeck_wayland_run(void) { wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager); droiddeck_ext_init(display); ahb_swapchain_init(display); + display_buffers_init(display); droiddeck_color_init(display); diff --git a/app/src/main/cpp/waylandcomp/src/compositor_internal.h b/app/src/main/cpp/waylandcomp/src/compositor_internal.h index c70f9dd193..b17329c124 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor_internal.h +++ b/app/src/main/cpp/waylandcomp/src/compositor_internal.h @@ -20,6 +20,7 @@ #define DRM_XBGR8888 FOURCC('X', 'B', '2', '4') #define MOD_LINEAR VKP_MOD_LINEAR #define MOD_INVALID VKP_MOD_INVALID +#define MOD_QCOM_COMPRESSED VKP_MOD_QCOM_COMPRESSED #define MAX_PLANES 4 struct dmabuf_params { diff --git a/app/src/main/cpp/waylandcomp/src/display_buffers.c b/app/src/main/cpp/waylandcomp/src/display_buffers.c new file mode 100644 index 0000000000..99f6993a56 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/display_buffers.c @@ -0,0 +1,343 @@ +#define _GNU_SOURCE +#include "display_buffers.h" +#include "ahb_swapchain.h" +#include "compositor_internal.h" +#include "droiddeck_color.h" +#include "droiddeck_ext.h" +#include "sc_layer.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DISPLAY_BUFFERS_SOCKET "droiddeck-display-buffers" +#define DISPLAY_BUFFERS_MAGIC 0x42444444u +#define DISPLAY_BUFFERS_VERSION 1u +#define DISPLAY_BUFFERS_ALLOC 1u +#define DISPLAY_BUFFERS_FREE 2u +#define DISPLAY_BUFFERS_MAX_SIDE 16384u +#define DISPLAY_BUFFERS_MAX_PER_CLIENT 256 +#define DISPLAY_BUFFERS_PROBE_W 1280u +#define DISPLAY_BUFFERS_PROBE_H 720u +#define ALIGN_UP(v, a) (((v) + (a) - 1) / (a) * (a)) + +extern volatile int g_zero_copy; +volatile int g_display_buffer_driver; + +struct display_buffers_request { + uint32_t magic, version, op, width, height, format, stride, offset; + uint64_t size, id, modifier; +}; + +struct display_buffers_reply { + uint32_t magic, status; + uint64_t id, size; +}; + +struct peer { + int fd; + pid_t pid; + int count; + int logged_w, logged_h; + uint32_t logged_format; + struct wl_event_source *src; +}; + +struct entry { + uint64_t id; + dev_t dev; + ino_t ino; + AHardwareBuffer *ahb; + uint32_t format, stride, width, height; + uint64_t modifier; + struct peer *peer; + struct wl_list link; +}; + +static struct wl_list g_entries; +static struct wl_event_loop *g_loop; +static uint64_t g_next_id = 1; +static int g_refused_logged; +static int g_ubwc_promised; +static int g_ubwc_probed[2]; + +static uint32_t ahb_format_of(uint32_t drm, uint64_t modifier) { + switch (drm) { + case DRM_ABGR8888: case DRM_XBGR8888: return AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM; + case DRM_ARGB8888: case DRM_XRGB8888: return modifier == MOD_QCOM_COMPRESSED ? AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM : 0; + case FOURCC('A', 'B', '3', '0'): case FOURCC('X', 'B', '3', '0'): return AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM; + default: return 0; + } +} + +static uint64_t ubwc_meta_size(uint32_t w, uint32_t h) { + return ALIGN_UP((uint64_t)ALIGN_UP((w + 15) / 16, 64) * ALIGN_UP((h + 3) / 4, 16), 4096); +} + +static uint64_t ubwc_size(uint32_t w, uint32_t h, uint32_t stride) { + return ubwc_meta_size(w, h) + ALIGN_UP((uint64_t)stride * ALIGN_UP(h, 16), 4096); +} + +static void entry_free(struct entry *e) { + wl_list_remove(&e->link); + e->peer->count--; + AHardwareBuffer_release(e->ahb); + free(e); +} + +static AHardwareBuffer *allocate_ubwc(uint32_t w, uint32_t h, uint32_t format, uint32_t stride, int *fd, uint64_t *size) { + const uint64_t tiers[2] = {SC_LAYER_AHB_USAGE_VENDOR_UBWC, 0}; + for (int i = 0; i < 2; i++) { + AHardwareBuffer_Desc d = { + .width = w, .height = h, .layers = 1, .format = format, + .usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | + AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | tiers[i]}; + AHardwareBuffer *ahb = NULL; + if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) continue; + AHardwareBuffer_Desc got; + AHardwareBuffer_describe(ahb, &got); + const uint64_t need = ubwc_size(w, h, got.stride * 4); + *fd = !stride || (uint64_t)got.stride * 4 == stride ? sc_layer_ahb_fd(ahb, need) : -1; + if (*fd >= 0 && (uint64_t)lseek(*fd, 0, SEEK_END) == need) { *size = need; return ahb; } + *fd = -1; + AHardwareBuffer_release(ahb); + } + return NULL; +} + +static uint64_t gralloc_bytes(uint32_t format, uint64_t usage, uint32_t *stride) { + AHardwareBuffer_Desc d = { + .width = DISPLAY_BUFFERS_PROBE_W, .height = DISPLAY_BUFFERS_PROBE_H, .layers = 1, .format = format, + .usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | + AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | usage}; + AHardwareBuffer *ahb = NULL; + if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) return 0; + AHardwareBuffer_describe(ahb, &d); + const int fd = sc_layer_ahb_fd(ahb, 1); + const off_t bytes = fd >= 0 ? lseek(fd, 0, SEEK_END) : 0; + if (fd >= 0) lseek(fd, 0, SEEK_SET); + AHardwareBuffer_release(ahb); + *stride = d.stride; + return bytes > 0 ? (uint64_t)bytes : 0; +} + +static int ubwc_probe(uint32_t format) { + int *state = &g_ubwc_probed[format == AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM ? 0 : 1]; + if (*state) return *state > 0; + uint32_t stride = 0, linear_stride = 0; + const uint64_t flagged = gralloc_bytes(format, SC_LAYER_AHB_USAGE_VENDOR_UBWC, &stride); + const uint64_t plain = gralloc_bytes(format, 0, &stride); + const uint64_t linear = gralloc_bytes(format, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY, &linear_stride); + const uint64_t need = ubwc_size(DISPLAY_BUFFERS_PROBE_W, DISPLAY_BUFFERS_PROBE_H, stride * 4); + *state = stride && linear != need && (flagged == need || plain == need) ? 1 : -1; + droiddeck_log("layer", "display buffers: gralloc %s buffers %s (%ux%u: the layout takes %llu bytes; gralloc gives %llu " + "asked for UBWC, %llu unasked, %llu linear)", droiddeck_ahb_format_name(format), + *state > 0 ? "use the UBWC layout the drivers render to: compressed frames can go on the display layer" + : "do not match the UBWC layout the drivers render to: compressed frames are not offered", + DISPLAY_BUFFERS_PROBE_W, DISPLAY_BUFFERS_PROBE_H, (unsigned long long)need, (unsigned long long)flagged, + (unsigned long long)plain, (unsigned long long)linear); + return *state > 0; +} + +int display_buffers_offer_ubwc(uint32_t drm) { + const uint32_t format = ahb_format_of(drm, MOD_QCOM_COMPRESSED); + if (!g_loop || !g_zero_copy || !g_ubwc || !g_display_buffer_driver || !format || !ubwc_probe(format)) return 0; + g_ubwc_promised = 1; + return 1; +} + +void display_buffers_withdraw_ubwc(void) { g_ubwc_promised = 0; } + +static AHardwareBuffer *allocate(const struct display_buffers_request *q, uint32_t format, int *fd) { + const uint32_t rows = (uint32_t)((q->size + q->stride - 1) / q->stride); + const uint32_t dims[2][2] = {{q->width, q->height}, {q->stride / 4, rows}}; + for (int i = 0; i < 2; i++) { + AHardwareBuffer_Desc d = { + .width = dims[i][0], .height = dims[i][1], .layers = 1, .format = format, + .usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | + AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | AHARDWAREBUFFER_USAGE_CPU_READ_RARELY}; + AHardwareBuffer *ahb = NULL; + if (i && dims[1][0] == dims[0][0] && dims[1][1] == dims[0][1]) break; + if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) continue; + AHardwareBuffer_Desc got; + AHardwareBuffer_describe(ahb, &got); + *fd = (uint64_t)got.stride * 4 == q->stride ? sc_layer_ahb_fd(ahb, q->size) : -1; + if (*fd >= 0) return ahb; + AHardwareBuffer_release(ahb); + } + return NULL; +} + +static int reply(struct peer *p, const struct display_buffers_reply *r, int fd) { + char control[CMSG_SPACE(sizeof(int))] = {0}; + struct iovec iov = {.iov_base = (void *)r, .iov_len = sizeof(*r)}; + struct msghdr msg = {.msg_iov = &iov, .msg_iovlen = 1}; + if (fd >= 0) { + msg.msg_control = control; + msg.msg_controllen = sizeof(control); + struct cmsghdr *c = CMSG_FIRSTHDR(&msg); + c->cmsg_level = SOL_SOCKET; + c->cmsg_type = SCM_RIGHTS; + c->cmsg_len = CMSG_LEN(sizeof(int)); + memcpy(CMSG_DATA(c), &fd, sizeof(int)); + } + ssize_t n; + do { n = sendmsg(p->fd, &msg, MSG_NOSIGNAL); } while (n < 0 && errno == EINTR); + return n == (ssize_t)sizeof(*r) ? 0 : -1; +} + +static void handle_alloc(struct peer *p, const struct display_buffers_request *q) { + struct display_buffers_reply r = {.magic = DISPLAY_BUFFERS_MAGIC, .status = 1}; + const int compressed = q->modifier == MOD_QCOM_COMPRESSED; + const uint32_t format = compressed || q->modifier == MOD_LINEAR ? ahb_format_of(q->format, q->modifier) : 0; + struct entry *e = NULL; + AHardwareBuffer *ahb = NULL; + struct stat st; + uint64_t need = 0; + int fd = -1; + const int sized = format && q->width && q->height && q->width <= DISPLAY_BUFFERS_MAX_SIDE && + q->height <= DISPLAY_BUFFERS_MAX_SIDE && q->stride % 4 == 0 && q->stride / 4 >= q->width && + q->stride / 4 <= DISPLAY_BUFFERS_MAX_SIDE; + const int sane = !sized ? 0 + : compressed ? q->offset == ubwc_meta_size(q->width, q->height) && + q->size == ubwc_size(q->width, q->height, q->stride) + : q->offset == 0 && q->size >= (uint64_t)q->stride * q->height && + q->size <= (uint64_t)q->stride * DISPLAY_BUFFERS_MAX_SIDE; + const int wanted = compressed ? g_ubwc_promised : g_zero_copy; + if (sane && wanted && ahb_swapchain_advertised() && p->count < DISPLAY_BUFFERS_MAX_PER_CLIENT) + ahb = compressed ? allocate_ubwc(q->width, q->height, format, q->stride, &fd, &need) : allocate(q, format, &fd); + if (ahb && fstat(fd, &st) == 0) e = calloc(1, sizeof(*e)); + if (e) { + e->id = r.id = g_next_id++; + e->dev = st.st_dev; e->ino = st.st_ino; + e->ahb = ahb; + e->format = format; e->stride = q->stride; + e->width = q->width; e->height = q->height; + e->modifier = q->modifier; + e->peer = p; + p->count++; + wl_list_insert(&g_entries, &e->link); + r.status = 0; + r.size = (uint64_t)lseek(fd, 0, SEEK_END); + lseek(fd, 0, SEEK_SET); + if (p->logged_w != (int)q->width || p->logged_h != (int)q->height || p->logged_format != q->format) { + AHardwareBuffer_Desc got; + AHardwareBuffer_describe(ahb, &got); + p->logged_w = (int)q->width; p->logged_h = (int)q->height; p->logged_format = q->format; + droiddeck_log("layer", "display buffers: pid %d renders %ux%u %c%c%c%c %s straight into gralloc buffers " + "(%s %ux%u, stride %u px, %llu bytes for the %llu it asked for)", (int)p->pid, q->width, q->height, + q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff, + compressed ? "UBWC" : "linear", droiddeck_ahb_format_name(format), got.width, got.height, + got.stride, (unsigned long long)r.size, (unsigned long long)q->size); + } + } else { + if (ahb) AHardwareBuffer_release(ahb); + fd = -1; + if (sized && wanted && (compressed || !g_refused_logged)) { + g_refused_logged = 1; + droiddeck_log(compressed ? "error" : "layer", "display buffers: no gralloc buffer matches pid %d's %ux%u " + "%c%c%c%c %s layout (stride %u bytes, pixels at %u, %llu bytes; gralloc's layout has pixels at " + "%llu, %llu bytes): %s", (int)p->pid, q->width, q->height, + q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff, + compressed ? "UBWC" : "linear", q->stride, q->offset, (unsigned long long)q->size, + (unsigned long long)(compressed ? ubwc_meta_size(q->width, q->height) : 0), + (unsigned long long)(compressed ? ubwc_size(q->width, q->height, q->stride) : q->size), + compressed ? "its compressed frames cannot be shown" : "its frames keep the copy path"); + } + } + if (reply(p, &r, fd) != 0 && e) entry_free(e); +} + +static void peer_gone(struct peer *p) { + struct entry *e, *tmp; + wl_list_for_each_safe(e, tmp, &g_entries, link) + if (e->peer == p) entry_free(e); + wl_event_source_remove(p->src); + close(p->fd); + free(p); +} + +static int on_peer(int fd, uint32_t mask, void *data) { + struct peer *p = data; + for (;;) { + struct display_buffers_request q; + ssize_t n = recv(fd, &q, sizeof(q), MSG_DONTWAIT); + if (n < 0 && errno == EINTR) continue; + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return 0; + if (n != (ssize_t)sizeof(q) || q.magic != DISPLAY_BUFFERS_MAGIC || q.version != DISPLAY_BUFFERS_VERSION) break; + if (q.op == DISPLAY_BUFFERS_ALLOC) { + handle_alloc(p, &q); + } else if (q.op == DISPLAY_BUFFERS_FREE) { + struct entry *e, *tmp; + wl_list_for_each_safe(e, tmp, &g_entries, link) + if (e->peer == p && e->id == q.id) entry_free(e); + } else { + break; + } + } + peer_gone(p); + return 0; +} + +static int on_listen(int fd, uint32_t mask, void *data) { + int c = accept4(fd, NULL, NULL, SOCK_CLOEXEC | SOCK_NONBLOCK); + if (c < 0) return 0; + struct peer *p = calloc(1, sizeof(*p)); + if (!p) { close(c); return 0; } + struct ucred cred = {0}; + socklen_t len = sizeof(cred); + if (getsockopt(c, SOL_SOCKET, SO_PEERCRED, &cred, &len) == 0) p->pid = cred.pid; + p->fd = c; + p->src = wl_event_loop_add_fd(g_loop, c, WL_EVENT_READABLE, on_peer, p); + if (!p->src) { close(c); free(p); } + return 0; +} + +void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b) { + struct stat st; + struct entry *e; + if (!g_loop || wl_list_empty(&g_entries) || b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) return; + wl_list_for_each(e, &g_entries, link) { + if (e->dev != st.st_dev || e->ino != st.st_ino) continue; + AHardwareBuffer_Desc d; + AHardwareBuffer_describe(e->ahb, &d); + const int compressed = e->modifier == MOD_QCOM_COMPRESSED; + const int laid_out = compressed ? b->modifier == MOD_QCOM_COMPRESSED && (uint32_t)b->width == e->width && + (uint32_t)b->height == e->height + : (b->modifier == MOD_LINEAR || b->modifier == MOD_INVALID) && + e->stride == b->stride[0]; + if (laid_out && e->format == ahb_format_of(b->format, e->modifier) && b->width > 0 && b->height > 0 && + (uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height) + ahb_swapchain_adopt(c, buffer, b, e->ahb, e->modifier); + return; + } +} + +void display_buffers_init(struct wl_display *display) { + wl_list_init(&g_entries); + const char *dir = getenv("XDG_RUNTIME_DIR"); + struct sockaddr_un addr = {.sun_family = AF_UNIX}; + if (!ahb_swapchain_advertised() || !dir) return; + if (snprintf(addr.sun_path, sizeof(addr.sun_path), "%s/" DISPLAY_BUFFERS_SOCKET, dir) >= (int)sizeof(addr.sun_path)) { + droiddeck_log("layer", "display buffers: %s is too long for a socket path, not offered", dir); + return; + } + int fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); + if (fd < 0) return; + unlink(addr.sun_path); + struct wl_event_loop *loop = wl_display_get_event_loop(display); + if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(fd, 16) != 0 || + !wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE, on_listen, NULL)) { + droiddeck_log("layer", "display buffers: socket %s failed (%s), not offered", addr.sun_path, strerror(errno)); + close(fd); + return; + } + g_loop = loop; + droiddeck_log("layer", "display buffers: offered on %s (programs whose driver asks render into gralloc buffers while " + "zero-copy is on)", addr.sun_path); +} diff --git a/app/src/main/cpp/waylandcomp/src/display_buffers.h b/app/src/main/cpp/waylandcomp/src/display_buffers.h new file mode 100644 index 0000000000..4943be521e --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/display_buffers.h @@ -0,0 +1,12 @@ +#ifndef DISPLAY_BUFFERS_H +#define DISPLAY_BUFFERS_H +#include + +struct dmabuf_buffer; + +void display_buffers_init(struct wl_display *display); +int display_buffers_offer_ubwc(uint32_t drm); +void display_buffers_withdraw_ubwc(void); +void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b); + +#endif diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_color.h b/app/src/main/cpp/waylandcomp/src/droiddeck_color.h index a578301ae5..8809b7ed63 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_color.h +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_color.h @@ -16,6 +16,9 @@ struct droiddeck_color { float max_lum, min_lum; int has_cta861; float max_cll, max_fall; + int convert; + float to2020[9]; + float gain; char text[256]; }; diff --git a/app/src/main/cpp/waylandcomp/src/hdr_compose.c b/app/src/main/cpp/waylandcomp/src/hdr_compose.c index 01d8be6f66..8cedd51b55 100644 --- a/app/src/main/cpp/waylandcomp/src/hdr_compose.c +++ b/app/src/main/cpp/waylandcomp/src/hdr_compose.c @@ -12,7 +12,7 @@ #define MIXED_FORMAT VK_FORMAT_A2B10G10R10_UNORM_PACK32 -struct pc_encode { float ndc[4]; float params[4]; float rects[HDRC_MAX_RECTS][4]; }; +struct pc_encode { float ndc[4]; float params[4]; uint32_t rects[HDRC_MAX_RECTS][2]; float conv[3][4]; }; static VkDevice g_dev; static int g_ready; @@ -266,7 +266,16 @@ int hdrc_encode(VkCommandBuffer cmd, VkImage mixed, VkImage out, VkFormat out_fm pc.params[1] = p->peak_nits > 0.0f ? p->peak_nits : 1000.0f; pc.params[2] = p->mode == HDRC_OUT_SDR ? 1.0f : 0.0f; pc.params[3] = (float)count + 16.0f * (float)mask; - for (int i = 0; i < count; i++) memcpy(pc.rects[i], p->rects[i], sizeof(pc.rects[i])); + for (int i = 0; i < count; i++) { + uint32_t v[4]; + for (int k = 0; k < 4; k++) v[k] = p->rects[i][k] <= 0.0f ? 0u : p->rects[i][k] >= 65535.0f ? 65535u : (uint32_t)p->rects[i][k]; + pc.rects[i][0] = v[0] | v[1] << 16; + pc.rects[i][1] = v[2] | v[3] << 16; + } + for (int k = 0; k < 3; k++) memcpy(pc.conv[k], &p->conv[3 * k], 3 * sizeof(float)); + pc.conv[0][3] = (float)(p->conv_mask & mask); + pc.conv[1][3] = p->conv_linear ? 1.0f : 0.0f; + pc.conv[2][3] = p->conv_gain; VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_out[slot].rp, .framebuffer = fb, .renderArea = {{0, 0}, {(uint32_t)w, (uint32_t)h}}}; diff --git a/app/src/main/cpp/waylandcomp/src/hdr_compose.h b/app/src/main/cpp/waylandcomp/src/hdr_compose.h index 5a37d42ad8..e49f575a3e 100644 --- a/app/src/main/cpp/waylandcomp/src/hdr_compose.h +++ b/app/src/main/cpp/waylandcomp/src/hdr_compose.h @@ -14,6 +14,10 @@ struct hdrc_params { int count; unsigned hdr_mask; float rects[HDRC_MAX_RECTS][4]; + unsigned conv_mask; + int conv_linear; + float conv_gain; + float conv[9]; }; void hdrc_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops); diff --git a/app/src/main/cpp/waylandcomp/src/hdr_encode.frag b/app/src/main/cpp/waylandcomp/src/hdr_encode.frag index db3ea8bcaf..1900bc4b9e 100644 --- a/app/src/main/cpp/waylandcomp/src/hdr_encode.frag +++ b/app/src/main/cpp/waylandcomp/src/hdr_encode.frag @@ -6,7 +6,8 @@ layout(binding = 0) uniform sampler2D Mixed; layout(push_constant) uniform PC { vec4 ndc; vec4 params; - vec4 rects[6]; + uvec2 rects[6]; + vec4 conv[3]; } pc; layout(location = 0) in vec2 fragTexCoord; @@ -55,28 +56,38 @@ float toneCurve(float x, float peak) { return knee + (1.0 - knee) * (1.0 - exp(-(x - knee) / rate)); } -bool isHdrPixel(vec2 p) { - float packed = pc.params.w; - float count = mod(packed, 16.0); - float mask = floor(packed / 16.0); +int rectAt(vec2 p) { + float count = mod(pc.params.w, 16.0); for (int i = 0; i < 6; i++) { if (float(i) >= count - 0.5) break; - vec4 r = pc.rects[i]; - if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w) { - float bit = mod(floor(mask / exp2(float(i))), 2.0); - return bit > 0.5; - } + uvec2 r = pc.rects[i]; + vec2 lo = vec2(float(r.x & 0xFFFFu), float(r.x >> 16)); + vec2 hi = vec2(float(r.y & 0xFFFFu), float(r.y >> 16)); + if (p.x >= lo.x && p.y >= lo.y && p.x < hi.x && p.y < hi.y) return i; } - return false; + return -1; +} + +bool bitOf(float mask, int i) { + return i >= 0 && mod(floor(mask / exp2(float(i))), 2.0) > 0.5; +} + +vec3 convertedNits(vec3 c) { + vec3 lin = pc.conv[1].w > 0.5 ? c : pqToLinear(c); + return vec3(dot(pc.conv[0].xyz, lin), dot(pc.conv[1].xyz, lin), dot(pc.conv[2].xyz, lin)) * pc.conv[2].w; } void main() { vec3 c = texelFetch(Mixed, ivec2(gl_FragCoord.xy), 0).rgb; - bool hdr = isHdrPixel(gl_FragCoord.xy); + int at = rectAt(gl_FragCoord.xy); + bool hdr = bitOf(floor(pc.params.w / 16.0), at); + bool conv = hdr && bitOf(pc.conv[0].w, at); float sdrWhite = max(pc.params.x, 1.0); vec3 outc; if (pc.params.z < 0.5) { - if (hdr) { + if (conv) { + outc = linearToPq(max(convertedNits(c), 0.0) / 10000.0); + } else if (hdr) { outc = c; } else { vec3 nits = (BT709_TO_BT2020 * srgbToLinear(c)) * sdrWhite; @@ -86,7 +97,8 @@ void main() { if (!hdr) { outc = c; } else { - vec3 rel = max(BT2020_TO_BT709 * (pqToLinear(c) * 10000.0), 0.0) / sdrWhite; + vec3 nits = conv ? convertedNits(c) : pqToLinear(c) * 10000.0; + vec3 rel = max(BT2020_TO_BT709 * nits, 0.0) / sdrWhite; float m = max(max(rel.r, rel.g), rel.b); if (m > 1e-6) rel *= toneCurve(m, max(pc.params.y, sdrWhite) / sdrWhite) / m; outc = linearToSrgb(clamp(rel, 0.0, 1.0)); diff --git a/app/src/main/cpp/waylandcomp/src/hdr_encode_frag.h b/app/src/main/cpp/waylandcomp/src/hdr_encode_frag.h index ba52146fc7..68baea4f82 100644 --- a/app/src/main/cpp/waylandcomp/src/hdr_encode_frag.h +++ b/app/src/main/cpp/waylandcomp/src/hdr_encode_frag.h @@ -1,8 +1,8 @@ #pragma once const uint32_t hdr_encode_code[] = { - 0x07230203,0x00010000,0x0008000b,0x0000018e,0x00000000,0x00020011,0x00000001,0x0006000b, + 0x07230203,0x00010000,0x0008000b,0x000001ff,0x00000000,0x00020011,0x00000001,0x0006000b, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, - 0x0008000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x0000010d,0x00000186,0x0000018d, + 0x0008000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000151,0x000001f7,0x000001fe, 0x00030010,0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004, 0x6e69616d,0x00000000,0x00070005,0x0000000b,0x62677273,0x694c6f54,0x7261656e,0x33667628, 0x0000003b,0x00030005,0x0000000a,0x00000063,0x00070005,0x0000000e,0x656e696c,0x6f547261, @@ -10,272 +10,354 @@ const uint32_t hdr_encode_code[] = { 0x6f547170,0x656e694c,0x76287261,0x003b3366,0x00030005,0x00000010,0x00000065,0x00060005, 0x00000014,0x656e696c,0x6f547261,0x76287150,0x003b3366,0x00030005,0x00000013,0x00000079, 0x00070005,0x0000001a,0x656e6f74,0x76727543,0x31662865,0x3b31663b,0x00000000,0x00030005, - 0x00000018,0x00000078,0x00040005,0x00000019,0x6b616570,0x00000000,0x00060005,0x00000021, - 0x64487369,0x78695072,0x76286c65,0x003b3266,0x00030005,0x00000020,0x00000070,0x00030005, - 0x00000023,0x00006f6c,0x00030005,0x00000028,0x00006968,0x00030005,0x0000003c,0x00006f6c, - 0x00030005,0x0000003f,0x00006968,0x00030005,0x00000050,0x00000070,0x00030005,0x0000006f, - 0x00000070,0x00040005,0x0000008c,0x6e617073,0x00000000,0x00040005,0x00000091,0x65746172, - 0x00000000,0x00040005,0x000000a2,0x6b636170,0x00006465,0x00030005,0x000000a7,0x00004350, - 0x00040006,0x000000a7,0x00000000,0x0063646e,0x00050006,0x000000a7,0x00000001,0x61726170, - 0x0000736d,0x00050006,0x000000a7,0x00000002,0x74636572,0x00000073,0x00030005,0x000000a9, - 0x00006370,0x00040005,0x000000b0,0x6e756f63,0x00000074,0x00040005,0x000000b4,0x6b73616d, - 0x00000000,0x00030005,0x000000b9,0x00000069,0x00030005,0x000000cd,0x00000072,0x00030005, - 0x000000f5,0x00746962,0x00030005,0x00000106,0x00000063,0x00040005,0x0000010a,0x6578694d, - 0x00000064,0x00060005,0x0000010d,0x465f6c67,0x43676172,0x64726f6f,0x00000000,0x00030005, - 0x00000116,0x00726468,0x00040005,0x00000117,0x61726170,0x0000006d,0x00050005,0x0000011b, - 0x57726473,0x65746968,0x00000000,0x00040005,0x00000127,0x6374756f,0x00000000,0x00040005, - 0x0000012a,0x7374696e,0x00000000,0x00040005,0x00000139,0x61726170,0x0000006d,0x00040005, - 0x00000143,0x61726170,0x0000006d,0x00030005,0x0000014c,0x006c6572,0x00040005,0x0000015a, - 0x61726170,0x0000006d,0x00030005,0x00000164,0x0000006d,0x00040005,0x00000177,0x61726170, - 0x0000006d,0x00040005,0x00000179,0x61726170,0x0000006d,0x00040005,0x00000183,0x61726170, - 0x0000006d,0x00050005,0x00000186,0x4374756f,0x726f6c6f,0x00000000,0x00060005,0x0000018d, - 0x67617266,0x43786554,0x64726f6f,0x00000000,0x00040047,0x000000a6,0x00000006,0x00000010, - 0x00030047,0x000000a7,0x00000002,0x00050048,0x000000a7,0x00000000,0x00000023,0x00000000, - 0x00050048,0x000000a7,0x00000001,0x00000023,0x00000010,0x00050048,0x000000a7,0x00000002, - 0x00000023,0x00000020,0x00040047,0x0000010a,0x00000021,0x00000000,0x00040047,0x0000010a, - 0x00000022,0x00000000,0x00040047,0x0000010d,0x0000000b,0x0000000f,0x00040047,0x00000186, - 0x0000001e,0x00000000,0x00040047,0x0000018d,0x0000001e,0x00000000,0x00020013,0x00000002, - 0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007, - 0x00000006,0x00000003,0x00040020,0x00000008,0x00000007,0x00000007,0x00040021,0x00000009, - 0x00000007,0x00000008,0x00040020,0x00000016,0x00000007,0x00000006,0x00050021,0x00000017, - 0x00000006,0x00000016,0x00000016,0x00040017,0x0000001c,0x00000006,0x00000002,0x00040020, - 0x0000001d,0x00000007,0x0000001c,0x00020014,0x0000001e,0x00040021,0x0000001f,0x0000001e, - 0x0000001d,0x0004002b,0x00000006,0x00000025,0x414eb852,0x0004002b,0x00000006,0x0000002a, - 0x3d6147ae,0x0004002b,0x00000006,0x0000002d,0x3f870a3d,0x0004002b,0x00000006,0x00000030, - 0x4019999a,0x0006002c,0x00000007,0x00000031,0x00000030,0x00000030,0x00000030,0x0004002b, - 0x00000006,0x00000035,0x3d25aee6,0x0006002c,0x00000007,0x00000036,0x00000035,0x00000035, - 0x00000035,0x0004002b,0x00000006,0x00000041,0x3ed55555,0x0006002c,0x00000007,0x00000042, - 0x00000041,0x00000041,0x00000041,0x0004002b,0x00000006,0x00000049,0x3b4d2e1c,0x0006002c, - 0x00000007,0x0000004a,0x00000049,0x00000049,0x00000049,0x0004002b,0x00000006,0x00000052, - 0x00000000,0x0004002b,0x00000006,0x00000053,0x3f800000,0x0004002b,0x00000006,0x00000057, - 0x3c4fcdac,0x0006002c,0x00000007,0x00000058,0x00000057,0x00000057,0x00000057,0x0004002b, - 0x00000006,0x0000005b,0x3f560000,0x0004002b,0x00000006,0x00000060,0x4196d000,0x0004002b, - 0x00000006,0x00000061,0x41958000,0x0004002b,0x00000006,0x00000066,0x358637bd,0x0004002b, - 0x00000006,0x0000006a,0x40c8e06b,0x0006002c,0x00000007,0x0000006b,0x0000006a,0x0000006a, - 0x0000006a,0x0004002b,0x00000006,0x00000074,0x3e232000,0x0006002c,0x00000007,0x00000075, - 0x00000074,0x00000074,0x00000074,0x0004002b,0x00000006,0x00000080,0x429db000,0x0006002c, - 0x00000007,0x00000081,0x00000080,0x00000080,0x00000080,0x0004002b,0x00000006,0x00000086, - 0x3f4ccccd,0x0004002b,0x00000006,0x0000008f,0x3d4ccccd,0x0004002b,0x00000006,0x00000093, - 0x407a5e35,0x0004002b,0x00000006,0x00000095,0x3e4ccccd,0x00040017,0x000000a3,0x00000006, - 0x00000004,0x00040015,0x000000a4,0x00000020,0x00000000,0x0004002b,0x000000a4,0x000000a5, - 0x00000006,0x0004001c,0x000000a6,0x000000a3,0x000000a5,0x0005001e,0x000000a7,0x000000a3, - 0x000000a3,0x000000a6,0x00040020,0x000000a8,0x00000009,0x000000a7,0x0004003b,0x000000a8, - 0x000000a9,0x00000009,0x00040015,0x000000aa,0x00000020,0x00000001,0x0004002b,0x000000aa, - 0x000000ab,0x00000001,0x0004002b,0x000000a4,0x000000ac,0x00000003,0x00040020,0x000000ad, - 0x00000009,0x00000006,0x0004002b,0x00000006,0x000000b2,0x41800000,0x00040020,0x000000b8, - 0x00000007,0x000000aa,0x0004002b,0x000000aa,0x000000ba,0x00000000,0x0004002b,0x000000aa, - 0x000000c1,0x00000006,0x0004002b,0x00000006,0x000000c6,0x3f000000,0x00040020,0x000000cc, - 0x00000007,0x000000a3,0x0004002b,0x000000aa,0x000000ce,0x00000002,0x00040020,0x000000d0, - 0x00000009,0x000000a3,0x0004002b,0x000000a4,0x000000d3,0x00000000,0x0004002b,0x000000a4, - 0x000000db,0x00000001,0x0004002b,0x000000a4,0x000000e6,0x00000002,0x0004002b,0x00000006, - 0x000000fc,0x40000000,0x0003002a,0x0000001e,0x00000103,0x00090019,0x00000107,0x00000006, - 0x00000001,0x00000000,0x00000000,0x00000000,0x00000001,0x00000000,0x0003001b,0x00000108, - 0x00000107,0x00040020,0x00000109,0x00000000,0x00000108,0x0004003b,0x00000109,0x0000010a, - 0x00000000,0x00040020,0x0000010c,0x00000001,0x000000a3,0x0004003b,0x0000010c,0x0000010d, - 0x00000001,0x00040017,0x00000110,0x000000aa,0x00000002,0x00040020,0x00000115,0x00000007, - 0x0000001e,0x00040018,0x0000012b,0x00000007,0x00000003,0x0004002b,0x00000006,0x0000012c, - 0x3f209d49,0x0004002b,0x00000006,0x0000012d,0x3d8d844d,0x0004002b,0x00000006,0x0000012e, - 0x3c86594b,0x0006002c,0x00000007,0x0000012f,0x0000012c,0x0000012d,0x0000012e,0x0004002b, - 0x00000006,0x00000130,0x3ea89a02,0x0004002b,0x00000006,0x00000131,0x3f6b645a,0x0004002b, - 0x00000006,0x00000132,0x3db43958,0x0006002c,0x00000007,0x00000133,0x00000130,0x00000131, - 0x00000132,0x0004002b,0x00000006,0x00000134,0x3d315b57,0x0004002b,0x00000006,0x00000135, - 0x3c3ac711,0x0004002b,0x00000006,0x00000136,0x3f65460b,0x0006002c,0x00000007,0x00000137, - 0x00000134,0x00000135,0x00000136,0x0006002c,0x0000012b,0x00000138,0x0000012f,0x00000133, - 0x00000137,0x0004002b,0x00000006,0x00000140,0x461c4000,0x0004002b,0x00000006,0x0000014d, - 0x3fd48b44,0x0004002b,0x00000006,0x0000014e,0xbdff2e49,0x0004002b,0x00000006,0x0000014f, - 0xbc95182b,0x0006002c,0x00000007,0x00000150,0x0000014d,0x0000014e,0x0000014f,0x0004002b, - 0x00000006,0x00000151,0xbf166cf4,0x0004002b,0x00000006,0x00000152,0x3f9102de,0x0004002b, - 0x00000006,0x00000153,0xbdce075f,0x0006002c,0x00000007,0x00000154,0x00000151,0x00000152, - 0x00000153,0x0004002b,0x00000006,0x00000155,0xbd95182b,0x0004002b,0x00000006,0x00000156, - 0xbc07fcb9,0x0004002b,0x00000006,0x00000157,0x3f8f3190,0x0006002c,0x00000007,0x00000158, - 0x00000155,0x00000156,0x00000157,0x0006002c,0x0000012b,0x00000159,0x00000150,0x00000154, - 0x00000158,0x00040020,0x00000185,0x00000003,0x000000a3,0x0004003b,0x00000185,0x00000186, - 0x00000003,0x00040020,0x0000018c,0x00000001,0x0000001c,0x0004003b,0x0000018c,0x0000018d, + 0x00000018,0x00000078,0x00040005,0x00000019,0x6b616570,0x00000000,0x00050005,0x00000021, + 0x74636572,0x76287441,0x003b3266,0x00030005,0x00000020,0x00000070,0x00060005,0x00000028, + 0x4f746962,0x31662866,0x3b31693b,0x00000000,0x00040005,0x00000026,0x6b73616d,0x00000000, + 0x00030005,0x00000027,0x00000069,0x00070005,0x0000002b,0x766e6f63,0x65747265,0x74694e64, + 0x66762873,0x00003b33,0x00030005,0x0000002a,0x00000063,0x00030005,0x0000002d,0x00006f6c, + 0x00030005,0x00000032,0x00006968,0x00030005,0x00000046,0x00006f6c,0x00030005,0x00000049, + 0x00006968,0x00030005,0x0000005a,0x00000070,0x00030005,0x00000079,0x00000070,0x00040005, + 0x00000096,0x6e617073,0x00000000,0x00040005,0x0000009b,0x65746172,0x00000000,0x00040005, + 0x000000ac,0x6e756f63,0x00000074,0x00030005,0x000000b4,0x00004350,0x00040006,0x000000b4, + 0x00000000,0x0063646e,0x00050006,0x000000b4,0x00000001,0x61726170,0x0000736d,0x00050006, + 0x000000b4,0x00000002,0x74636572,0x00000073,0x00050006,0x000000b4,0x00000003,0x766e6f63, + 0x00000000,0x00030005,0x000000b6,0x00006370,0x00030005,0x000000bd,0x00000069,0x00030005, + 0x000000d1,0x00000072,0x00030005,0x000000d7,0x00006f6c,0x00030005,0x000000e5,0x00006968, + 0x00030005,0x00000126,0x006e696c,0x00040005,0x00000130,0x61726170,0x0000006d,0x00030005, + 0x0000014a,0x00000063,0x00040005,0x0000014e,0x6578694d,0x00000064,0x00060005,0x00000151, + 0x465f6c67,0x43676172,0x64726f6f,0x00000000,0x00030005,0x00000159,0x00007461,0x00040005, + 0x0000015a,0x61726170,0x0000006d,0x00030005,0x0000015f,0x00726468,0x00040005,0x00000164, + 0x61726170,0x0000006d,0x00040005,0x00000165,0x61726170,0x0000006d,0x00040005,0x00000168, + 0x766e6f63,0x00000000,0x00040005,0x0000016c,0x61726170,0x0000006d,0x00040005,0x0000016f, + 0x61726170,0x0000006d,0x00050005,0x00000173,0x57726473,0x65746968,0x00000000,0x00040005, + 0x00000180,0x6374756f,0x00000000,0x00040005,0x00000181,0x61726170,0x0000006d,0x00040005, + 0x00000189,0x61726170,0x0000006d,0x00040005,0x00000191,0x7374696e,0x00000000,0x00040005, + 0x000001a0,0x61726170,0x0000006d,0x00040005,0x000001a9,0x61726170,0x0000006d,0x00040005, + 0x000001b2,0x7374696e,0x00000000,0x00040005,0x000001b7,0x61726170,0x0000006d,0x00040005, + 0x000001bb,0x61726170,0x0000006d,0x00030005,0x000001c0,0x006c6572,0x00030005,0x000001d5, + 0x0000006d,0x00040005,0x000001e8,0x61726170,0x0000006d,0x00040005,0x000001ea,0x61726170, + 0x0000006d,0x00040005,0x000001f4,0x61726170,0x0000006d,0x00050005,0x000001f7,0x4374756f, + 0x726f6c6f,0x00000000,0x00060005,0x000001fe,0x67617266,0x43786554,0x64726f6f,0x00000000, + 0x00040047,0x000000b1,0x00000006,0x00000008,0x00040047,0x000000b3,0x00000006,0x00000010, + 0x00030047,0x000000b4,0x00000002,0x00050048,0x000000b4,0x00000000,0x00000023,0x00000000, + 0x00050048,0x000000b4,0x00000001,0x00000023,0x00000010,0x00050048,0x000000b4,0x00000002, + 0x00000023,0x00000020,0x00050048,0x000000b4,0x00000003,0x00000023,0x00000050,0x00040047, + 0x0000014e,0x00000021,0x00000000,0x00040047,0x0000014e,0x00000022,0x00000000,0x00040047, + 0x00000151,0x0000000b,0x0000000f,0x00040047,0x000001f7,0x0000001e,0x00000000,0x00040047, + 0x000001fe,0x0000001e,0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002, + 0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000003,0x00040020, + 0x00000008,0x00000007,0x00000007,0x00040021,0x00000009,0x00000007,0x00000008,0x00040020, + 0x00000016,0x00000007,0x00000006,0x00050021,0x00000017,0x00000006,0x00000016,0x00000016, + 0x00040017,0x0000001c,0x00000006,0x00000002,0x00040020,0x0000001d,0x00000007,0x0000001c, + 0x00040015,0x0000001e,0x00000020,0x00000001,0x00040021,0x0000001f,0x0000001e,0x0000001d, + 0x00040020,0x00000023,0x00000007,0x0000001e,0x00020014,0x00000024,0x00050021,0x00000025, + 0x00000024,0x00000016,0x00000023,0x0004002b,0x00000006,0x0000002f,0x414eb852,0x0004002b, + 0x00000006,0x00000034,0x3d6147ae,0x0004002b,0x00000006,0x00000037,0x3f870a3d,0x0004002b, + 0x00000006,0x0000003a,0x4019999a,0x0006002c,0x00000007,0x0000003b,0x0000003a,0x0000003a, + 0x0000003a,0x0004002b,0x00000006,0x0000003f,0x3d25aee6,0x0006002c,0x00000007,0x00000040, + 0x0000003f,0x0000003f,0x0000003f,0x0004002b,0x00000006,0x0000004b,0x3ed55555,0x0006002c, + 0x00000007,0x0000004c,0x0000004b,0x0000004b,0x0000004b,0x0004002b,0x00000006,0x00000053, + 0x3b4d2e1c,0x0006002c,0x00000007,0x00000054,0x00000053,0x00000053,0x00000053,0x0004002b, + 0x00000006,0x0000005c,0x00000000,0x0004002b,0x00000006,0x0000005d,0x3f800000,0x0004002b, + 0x00000006,0x00000061,0x3c4fcdac,0x0006002c,0x00000007,0x00000062,0x00000061,0x00000061, + 0x00000061,0x0004002b,0x00000006,0x00000065,0x3f560000,0x0004002b,0x00000006,0x0000006a, + 0x4196d000,0x0004002b,0x00000006,0x0000006b,0x41958000,0x0004002b,0x00000006,0x00000070, + 0x358637bd,0x0004002b,0x00000006,0x00000074,0x40c8e06b,0x0006002c,0x00000007,0x00000075, + 0x00000074,0x00000074,0x00000074,0x0004002b,0x00000006,0x0000007e,0x3e232000,0x0006002c, + 0x00000007,0x0000007f,0x0000007e,0x0000007e,0x0000007e,0x0004002b,0x00000006,0x0000008a, + 0x429db000,0x0006002c,0x00000007,0x0000008b,0x0000008a,0x0000008a,0x0000008a,0x0004002b, + 0x00000006,0x00000090,0x3f4ccccd,0x0004002b,0x00000006,0x00000099,0x3d4ccccd,0x0004002b, + 0x00000006,0x0000009d,0x407a5e35,0x0004002b,0x00000006,0x0000009f,0x3e4ccccd,0x00040017, + 0x000000ad,0x00000006,0x00000004,0x00040015,0x000000ae,0x00000020,0x00000000,0x00040017, + 0x000000af,0x000000ae,0x00000002,0x0004002b,0x000000ae,0x000000b0,0x00000006,0x0004001c, + 0x000000b1,0x000000af,0x000000b0,0x0004002b,0x000000ae,0x000000b2,0x00000003,0x0004001c, + 0x000000b3,0x000000ad,0x000000b2,0x0006001e,0x000000b4,0x000000ad,0x000000ad,0x000000b1, + 0x000000b3,0x00040020,0x000000b5,0x00000009,0x000000b4,0x0004003b,0x000000b5,0x000000b6, + 0x00000009,0x0004002b,0x0000001e,0x000000b7,0x00000001,0x00040020,0x000000b8,0x00000009, + 0x00000006,0x0004002b,0x00000006,0x000000bb,0x41800000,0x0004002b,0x0000001e,0x000000be, + 0x00000000,0x0004002b,0x0000001e,0x000000c5,0x00000006,0x0004002b,0x00000006,0x000000ca, + 0x3f000000,0x00040020,0x000000d0,0x00000007,0x000000af,0x0004002b,0x0000001e,0x000000d2, + 0x00000002,0x00040020,0x000000d4,0x00000009,0x000000af,0x0004002b,0x000000ae,0x000000d8, + 0x00000000,0x00040020,0x000000d9,0x00000007,0x000000ae,0x0004002b,0x000000ae,0x000000dc, + 0x0000ffff,0x0004002b,0x0000001e,0x000000e1,0x00000010,0x0004002b,0x000000ae,0x000000e6, + 0x00000001,0x0004002b,0x0000001e,0x00000113,0xffffffff,0x0004002b,0x00000006,0x00000120, + 0x40000000,0x0004002b,0x0000001e,0x00000127,0x00000003,0x00040020,0x00000134,0x00000009, + 0x000000ad,0x00090019,0x0000014b,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000, + 0x00000001,0x00000000,0x0003001b,0x0000014c,0x0000014b,0x00040020,0x0000014d,0x00000000, + 0x0000014c,0x0004003b,0x0000014d,0x0000014e,0x00000000,0x00040020,0x00000150,0x00000001, + 0x000000ad,0x0004003b,0x00000150,0x00000151,0x00000001,0x00040017,0x00000154,0x0000001e, + 0x00000002,0x00040020,0x0000015e,0x00000007,0x00000024,0x0004002b,0x000000ae,0x00000177, + 0x00000002,0x0004002b,0x00000006,0x00000186,0x461c4000,0x00040018,0x00000192,0x00000007, + 0x00000003,0x0004002b,0x00000006,0x00000193,0x3f209d49,0x0004002b,0x00000006,0x00000194, + 0x3d8d844d,0x0004002b,0x00000006,0x00000195,0x3c86594b,0x0006002c,0x00000007,0x00000196, + 0x00000193,0x00000194,0x00000195,0x0004002b,0x00000006,0x00000197,0x3ea89a02,0x0004002b, + 0x00000006,0x00000198,0x3f6b645a,0x0004002b,0x00000006,0x00000199,0x3db43958,0x0006002c, + 0x00000007,0x0000019a,0x00000197,0x00000198,0x00000199,0x0004002b,0x00000006,0x0000019b, + 0x3d315b57,0x0004002b,0x00000006,0x0000019c,0x3c3ac711,0x0004002b,0x00000006,0x0000019d, + 0x3f65460b,0x0006002c,0x00000007,0x0000019e,0x0000019b,0x0000019c,0x0000019d,0x0006002c, + 0x00000192,0x0000019f,0x00000196,0x0000019a,0x0000019e,0x0004002b,0x00000006,0x000001c1, + 0x3fd48b44,0x0004002b,0x00000006,0x000001c2,0xbdff2e49,0x0004002b,0x00000006,0x000001c3, + 0xbc95182b,0x0006002c,0x00000007,0x000001c4,0x000001c1,0x000001c2,0x000001c3,0x0004002b, + 0x00000006,0x000001c5,0xbf166cf4,0x0004002b,0x00000006,0x000001c6,0x3f9102de,0x0004002b, + 0x00000006,0x000001c7,0xbdce075f,0x0006002c,0x00000007,0x000001c8,0x000001c5,0x000001c6, + 0x000001c7,0x0004002b,0x00000006,0x000001c9,0xbd95182b,0x0004002b,0x00000006,0x000001ca, + 0xbc07fcb9,0x0004002b,0x00000006,0x000001cb,0x3f8f3190,0x0006002c,0x00000007,0x000001cc, + 0x000001c9,0x000001ca,0x000001cb,0x0006002c,0x00000192,0x000001cd,0x000001c4,0x000001c8, + 0x000001cc,0x00040020,0x000001f6,0x00000003,0x000000ad,0x0004003b,0x000001f6,0x000001f7, + 0x00000003,0x00040020,0x000001fd,0x00000001,0x0000001c,0x0004003b,0x000001fd,0x000001fe, 0x00000001,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005, - 0x0004003b,0x00000008,0x00000106,0x00000007,0x0004003b,0x00000115,0x00000116,0x00000007, - 0x0004003b,0x0000001d,0x00000117,0x00000007,0x0004003b,0x00000016,0x0000011b,0x00000007, - 0x0004003b,0x00000008,0x00000127,0x00000007,0x0004003b,0x00000008,0x0000012a,0x00000007, - 0x0004003b,0x00000008,0x00000139,0x00000007,0x0004003b,0x00000008,0x00000143,0x00000007, - 0x0004003b,0x00000008,0x0000014c,0x00000007,0x0004003b,0x00000008,0x0000015a,0x00000007, - 0x0004003b,0x00000016,0x00000164,0x00000007,0x0004003b,0x00000016,0x00000177,0x00000007, - 0x0004003b,0x00000016,0x00000179,0x00000007,0x0004003b,0x00000008,0x00000183,0x00000007, - 0x0004003d,0x00000108,0x0000010b,0x0000010a,0x0004003d,0x000000a3,0x0000010e,0x0000010d, - 0x0007004f,0x0000001c,0x0000010f,0x0000010e,0x0000010e,0x00000000,0x00000001,0x0004006e, - 0x00000110,0x00000111,0x0000010f,0x00040064,0x00000107,0x00000112,0x0000010b,0x0007005f, - 0x000000a3,0x00000113,0x00000112,0x00000111,0x00000002,0x000000ba,0x0008004f,0x00000007, - 0x00000114,0x00000113,0x00000113,0x00000000,0x00000001,0x00000002,0x0003003e,0x00000106, - 0x00000114,0x0004003d,0x000000a3,0x00000118,0x0000010d,0x0007004f,0x0000001c,0x00000119, - 0x00000118,0x00000118,0x00000000,0x00000001,0x0003003e,0x00000117,0x00000119,0x00050039, - 0x0000001e,0x0000011a,0x00000021,0x00000117,0x0003003e,0x00000116,0x0000011a,0x00060041, - 0x000000ad,0x0000011c,0x000000a9,0x000000ab,0x000000d3,0x0004003d,0x00000006,0x0000011d, - 0x0000011c,0x0007000c,0x00000006,0x0000011e,0x00000001,0x00000028,0x0000011d,0x00000053, - 0x0003003e,0x0000011b,0x0000011e,0x00060041,0x000000ad,0x0000011f,0x000000a9,0x000000ab, - 0x000000e6,0x0004003d,0x00000006,0x00000120,0x0000011f,0x000500b8,0x0000001e,0x00000121, - 0x00000120,0x000000c6,0x000300f7,0x00000123,0x00000000,0x000400fa,0x00000121,0x00000122, - 0x00000145,0x000200f8,0x00000122,0x0004003d,0x0000001e,0x00000124,0x00000116,0x000300f7, - 0x00000126,0x00000000,0x000400fa,0x00000124,0x00000125,0x00000129,0x000200f8,0x00000125, - 0x0004003d,0x00000007,0x00000128,0x00000106,0x0003003e,0x00000127,0x00000128,0x000200f9, - 0x00000126,0x000200f8,0x00000129,0x0004003d,0x00000007,0x0000013a,0x00000106,0x0003003e, - 0x00000139,0x0000013a,0x00050039,0x00000007,0x0000013b,0x0000000b,0x00000139,0x00050091, - 0x00000007,0x0000013c,0x00000138,0x0000013b,0x0004003d,0x00000006,0x0000013d,0x0000011b, - 0x0005008e,0x00000007,0x0000013e,0x0000013c,0x0000013d,0x0003003e,0x0000012a,0x0000013e, - 0x0004003d,0x00000007,0x0000013f,0x0000012a,0x00060050,0x00000007,0x00000141,0x00000140, - 0x00000140,0x00000140,0x00050088,0x00000007,0x00000142,0x0000013f,0x00000141,0x0003003e, - 0x00000143,0x00000142,0x00050039,0x00000007,0x00000144,0x00000014,0x00000143,0x0003003e, - 0x00000127,0x00000144,0x000200f9,0x00000126,0x000200f8,0x00000126,0x000200f9,0x00000123, - 0x000200f8,0x00000145,0x0004003d,0x0000001e,0x00000146,0x00000116,0x000400a8,0x0000001e, - 0x00000147,0x00000146,0x000300f7,0x00000149,0x00000000,0x000400fa,0x00000147,0x00000148, - 0x0000014b,0x000200f8,0x00000148,0x0004003d,0x00000007,0x0000014a,0x00000106,0x0003003e, - 0x00000127,0x0000014a,0x000200f9,0x00000149,0x000200f8,0x0000014b,0x0004003d,0x00000007, - 0x0000015b,0x00000106,0x0003003e,0x0000015a,0x0000015b,0x00050039,0x00000007,0x0000015c, - 0x00000011,0x0000015a,0x0005008e,0x00000007,0x0000015d,0x0000015c,0x00000140,0x00050091, - 0x00000007,0x0000015e,0x00000159,0x0000015d,0x00060050,0x00000007,0x0000015f,0x00000052, - 0x00000052,0x00000052,0x0007000c,0x00000007,0x00000160,0x00000001,0x00000028,0x0000015e, - 0x0000015f,0x0004003d,0x00000006,0x00000161,0x0000011b,0x00060050,0x00000007,0x00000162, - 0x00000161,0x00000161,0x00000161,0x00050088,0x00000007,0x00000163,0x00000160,0x00000162, - 0x0003003e,0x0000014c,0x00000163,0x00050041,0x00000016,0x00000165,0x0000014c,0x000000d3, - 0x0004003d,0x00000006,0x00000166,0x00000165,0x00050041,0x00000016,0x00000167,0x0000014c, - 0x000000db,0x0004003d,0x00000006,0x00000168,0x00000167,0x0007000c,0x00000006,0x00000169, - 0x00000001,0x00000028,0x00000166,0x00000168,0x00050041,0x00000016,0x0000016a,0x0000014c, - 0x000000e6,0x0004003d,0x00000006,0x0000016b,0x0000016a,0x0007000c,0x00000006,0x0000016c, - 0x00000001,0x00000028,0x00000169,0x0000016b,0x0003003e,0x00000164,0x0000016c,0x0004003d, - 0x00000006,0x0000016d,0x00000164,0x000500ba,0x0000001e,0x0000016e,0x0000016d,0x00000066, - 0x000300f7,0x00000170,0x00000000,0x000400fa,0x0000016e,0x0000016f,0x00000170,0x000200f8, - 0x0000016f,0x00060041,0x000000ad,0x00000171,0x000000a9,0x000000ab,0x000000db,0x0004003d, - 0x00000006,0x00000172,0x00000171,0x0004003d,0x00000006,0x00000173,0x0000011b,0x0007000c, - 0x00000006,0x00000174,0x00000001,0x00000028,0x00000172,0x00000173,0x0004003d,0x00000006, - 0x00000175,0x0000011b,0x00050088,0x00000006,0x00000176,0x00000174,0x00000175,0x0004003d, - 0x00000006,0x00000178,0x00000164,0x0003003e,0x00000177,0x00000178,0x0003003e,0x00000179, - 0x00000176,0x00060039,0x00000006,0x0000017a,0x0000001a,0x00000177,0x00000179,0x0004003d, - 0x00000006,0x0000017b,0x00000164,0x00050088,0x00000006,0x0000017c,0x0000017a,0x0000017b, - 0x0004003d,0x00000007,0x0000017d,0x0000014c,0x0005008e,0x00000007,0x0000017e,0x0000017d, - 0x0000017c,0x0003003e,0x0000014c,0x0000017e,0x000200f9,0x00000170,0x000200f8,0x00000170, - 0x0004003d,0x00000007,0x0000017f,0x0000014c,0x00060050,0x00000007,0x00000180,0x00000052, - 0x00000052,0x00000052,0x00060050,0x00000007,0x00000181,0x00000053,0x00000053,0x00000053, - 0x0008000c,0x00000007,0x00000182,0x00000001,0x0000002b,0x0000017f,0x00000180,0x00000181, - 0x0003003e,0x00000183,0x00000182,0x00050039,0x00000007,0x00000184,0x0000000e,0x00000183, - 0x0003003e,0x00000127,0x00000184,0x000200f9,0x00000149,0x000200f8,0x00000149,0x000200f9, - 0x00000123,0x000200f8,0x00000123,0x0004003d,0x00000007,0x00000187,0x00000127,0x00050051, - 0x00000006,0x00000188,0x00000187,0x00000000,0x00050051,0x00000006,0x00000189,0x00000187, - 0x00000001,0x00050051,0x00000006,0x0000018a,0x00000187,0x00000002,0x00070050,0x000000a3, - 0x0000018b,0x00000188,0x00000189,0x0000018a,0x00000053,0x0003003e,0x00000186,0x0000018b, + 0x0004003b,0x00000008,0x0000014a,0x00000007,0x0004003b,0x00000023,0x00000159,0x00000007, + 0x0004003b,0x0000001d,0x0000015a,0x00000007,0x0004003b,0x0000015e,0x0000015f,0x00000007, + 0x0004003b,0x00000016,0x00000164,0x00000007,0x0004003b,0x00000023,0x00000165,0x00000007, + 0x0004003b,0x0000015e,0x00000168,0x00000007,0x0004003b,0x00000016,0x0000016c,0x00000007, + 0x0004003b,0x00000023,0x0000016f,0x00000007,0x0004003b,0x00000016,0x00000173,0x00000007, + 0x0004003b,0x00000008,0x00000180,0x00000007,0x0004003b,0x00000008,0x00000181,0x00000007, + 0x0004003b,0x00000008,0x00000189,0x00000007,0x0004003b,0x00000008,0x00000191,0x00000007, + 0x0004003b,0x00000008,0x000001a0,0x00000007,0x0004003b,0x00000008,0x000001a9,0x00000007, + 0x0004003b,0x00000008,0x000001b2,0x00000007,0x0004003b,0x00000008,0x000001b4,0x00000007, + 0x0004003b,0x00000008,0x000001b7,0x00000007,0x0004003b,0x00000008,0x000001bb,0x00000007, + 0x0004003b,0x00000008,0x000001c0,0x00000007,0x0004003b,0x00000016,0x000001d5,0x00000007, + 0x0004003b,0x00000016,0x000001e8,0x00000007,0x0004003b,0x00000016,0x000001ea,0x00000007, + 0x0004003b,0x00000008,0x000001f4,0x00000007,0x0004003d,0x0000014c,0x0000014f,0x0000014e, + 0x0004003d,0x000000ad,0x00000152,0x00000151,0x0007004f,0x0000001c,0x00000153,0x00000152, + 0x00000152,0x00000000,0x00000001,0x0004006e,0x00000154,0x00000155,0x00000153,0x00040064, + 0x0000014b,0x00000156,0x0000014f,0x0007005f,0x000000ad,0x00000157,0x00000156,0x00000155, + 0x00000002,0x000000be,0x0008004f,0x00000007,0x00000158,0x00000157,0x00000157,0x00000000, + 0x00000001,0x00000002,0x0003003e,0x0000014a,0x00000158,0x0004003d,0x000000ad,0x0000015b, + 0x00000151,0x0007004f,0x0000001c,0x0000015c,0x0000015b,0x0000015b,0x00000000,0x00000001, + 0x0003003e,0x0000015a,0x0000015c,0x00050039,0x0000001e,0x0000015d,0x00000021,0x0000015a, + 0x0003003e,0x00000159,0x0000015d,0x00060041,0x000000b8,0x00000160,0x000000b6,0x000000b7, + 0x000000b2,0x0004003d,0x00000006,0x00000161,0x00000160,0x00050088,0x00000006,0x00000162, + 0x00000161,0x000000bb,0x0006000c,0x00000006,0x00000163,0x00000001,0x00000008,0x00000162, + 0x0003003e,0x00000164,0x00000163,0x0004003d,0x0000001e,0x00000166,0x00000159,0x0003003e, + 0x00000165,0x00000166,0x00060039,0x00000024,0x00000167,0x00000028,0x00000164,0x00000165, + 0x0003003e,0x0000015f,0x00000167,0x0004003d,0x00000024,0x00000169,0x0000015f,0x000300f7, + 0x0000016b,0x00000000,0x000400fa,0x00000169,0x0000016a,0x0000016b,0x000200f8,0x0000016a, + 0x00070041,0x000000b8,0x0000016d,0x000000b6,0x00000127,0x000000be,0x000000b2,0x0004003d, + 0x00000006,0x0000016e,0x0000016d,0x0003003e,0x0000016c,0x0000016e,0x0004003d,0x0000001e, + 0x00000170,0x00000159,0x0003003e,0x0000016f,0x00000170,0x00060039,0x00000024,0x00000171, + 0x00000028,0x0000016c,0x0000016f,0x000200f9,0x0000016b,0x000200f8,0x0000016b,0x000700f5, + 0x00000024,0x00000172,0x00000169,0x00000005,0x00000171,0x0000016a,0x0003003e,0x00000168, + 0x00000172,0x00060041,0x000000b8,0x00000174,0x000000b6,0x000000b7,0x000000d8,0x0004003d, + 0x00000006,0x00000175,0x00000174,0x0007000c,0x00000006,0x00000176,0x00000001,0x00000028, + 0x00000175,0x0000005d,0x0003003e,0x00000173,0x00000176,0x00060041,0x000000b8,0x00000178, + 0x000000b6,0x000000b7,0x00000177,0x0004003d,0x00000006,0x00000179,0x00000178,0x000500b8, + 0x00000024,0x0000017a,0x00000179,0x000000ca,0x000300f7,0x0000017c,0x00000000,0x000400fa, + 0x0000017a,0x0000017b,0x000001ab,0x000200f8,0x0000017b,0x0004003d,0x00000024,0x0000017d, + 0x00000168,0x000300f7,0x0000017f,0x00000000,0x000400fa,0x0000017d,0x0000017e,0x0000018b, + 0x000200f8,0x0000017e,0x0004003d,0x00000007,0x00000182,0x0000014a,0x0003003e,0x00000181, + 0x00000182,0x00050039,0x00000007,0x00000183,0x0000002b,0x00000181,0x00060050,0x00000007, + 0x00000184,0x0000005c,0x0000005c,0x0000005c,0x0007000c,0x00000007,0x00000185,0x00000001, + 0x00000028,0x00000183,0x00000184,0x00060050,0x00000007,0x00000187,0x00000186,0x00000186, + 0x00000186,0x00050088,0x00000007,0x00000188,0x00000185,0x00000187,0x0003003e,0x00000189, + 0x00000188,0x00050039,0x00000007,0x0000018a,0x00000014,0x00000189,0x0003003e,0x00000180, + 0x0000018a,0x000200f9,0x0000017f,0x000200f8,0x0000018b,0x0004003d,0x00000024,0x0000018c, + 0x0000015f,0x000300f7,0x0000018e,0x00000000,0x000400fa,0x0000018c,0x0000018d,0x00000190, + 0x000200f8,0x0000018d,0x0004003d,0x00000007,0x0000018f,0x0000014a,0x0003003e,0x00000180, + 0x0000018f,0x000200f9,0x0000018e,0x000200f8,0x00000190,0x0004003d,0x00000007,0x000001a1, + 0x0000014a,0x0003003e,0x000001a0,0x000001a1,0x00050039,0x00000007,0x000001a2,0x0000000b, + 0x000001a0,0x00050091,0x00000007,0x000001a3,0x0000019f,0x000001a2,0x0004003d,0x00000006, + 0x000001a4,0x00000173,0x0005008e,0x00000007,0x000001a5,0x000001a3,0x000001a4,0x0003003e, + 0x00000191,0x000001a5,0x0004003d,0x00000007,0x000001a6,0x00000191,0x00060050,0x00000007, + 0x000001a7,0x00000186,0x00000186,0x00000186,0x00050088,0x00000007,0x000001a8,0x000001a6, + 0x000001a7,0x0003003e,0x000001a9,0x000001a8,0x00050039,0x00000007,0x000001aa,0x00000014, + 0x000001a9,0x0003003e,0x00000180,0x000001aa,0x000200f9,0x0000018e,0x000200f8,0x0000018e, + 0x000200f9,0x0000017f,0x000200f8,0x0000017f,0x000200f9,0x0000017c,0x000200f8,0x000001ab, + 0x0004003d,0x00000024,0x000001ac,0x0000015f,0x000400a8,0x00000024,0x000001ad,0x000001ac, + 0x000300f7,0x000001af,0x00000000,0x000400fa,0x000001ad,0x000001ae,0x000001b1,0x000200f8, + 0x000001ae,0x0004003d,0x00000007,0x000001b0,0x0000014a,0x0003003e,0x00000180,0x000001b0, + 0x000200f9,0x000001af,0x000200f8,0x000001b1,0x0004003d,0x00000024,0x000001b3,0x00000168, + 0x000300f7,0x000001b6,0x00000000,0x000400fa,0x000001b3,0x000001b5,0x000001ba,0x000200f8, + 0x000001b5,0x0004003d,0x00000007,0x000001b8,0x0000014a,0x0003003e,0x000001b7,0x000001b8, + 0x00050039,0x00000007,0x000001b9,0x0000002b,0x000001b7,0x0003003e,0x000001b4,0x000001b9, + 0x000200f9,0x000001b6,0x000200f8,0x000001ba,0x0004003d,0x00000007,0x000001bc,0x0000014a, + 0x0003003e,0x000001bb,0x000001bc,0x00050039,0x00000007,0x000001bd,0x00000011,0x000001bb, + 0x0005008e,0x00000007,0x000001be,0x000001bd,0x00000186,0x0003003e,0x000001b4,0x000001be, + 0x000200f9,0x000001b6,0x000200f8,0x000001b6,0x0004003d,0x00000007,0x000001bf,0x000001b4, + 0x0003003e,0x000001b2,0x000001bf,0x0004003d,0x00000007,0x000001ce,0x000001b2,0x00050091, + 0x00000007,0x000001cf,0x000001cd,0x000001ce,0x00060050,0x00000007,0x000001d0,0x0000005c, + 0x0000005c,0x0000005c,0x0007000c,0x00000007,0x000001d1,0x00000001,0x00000028,0x000001cf, + 0x000001d0,0x0004003d,0x00000006,0x000001d2,0x00000173,0x00060050,0x00000007,0x000001d3, + 0x000001d2,0x000001d2,0x000001d2,0x00050088,0x00000007,0x000001d4,0x000001d1,0x000001d3, + 0x0003003e,0x000001c0,0x000001d4,0x00050041,0x00000016,0x000001d6,0x000001c0,0x000000d8, + 0x0004003d,0x00000006,0x000001d7,0x000001d6,0x00050041,0x00000016,0x000001d8,0x000001c0, + 0x000000e6,0x0004003d,0x00000006,0x000001d9,0x000001d8,0x0007000c,0x00000006,0x000001da, + 0x00000001,0x00000028,0x000001d7,0x000001d9,0x00050041,0x00000016,0x000001db,0x000001c0, + 0x00000177,0x0004003d,0x00000006,0x000001dc,0x000001db,0x0007000c,0x00000006,0x000001dd, + 0x00000001,0x00000028,0x000001da,0x000001dc,0x0003003e,0x000001d5,0x000001dd,0x0004003d, + 0x00000006,0x000001de,0x000001d5,0x000500ba,0x00000024,0x000001df,0x000001de,0x00000070, + 0x000300f7,0x000001e1,0x00000000,0x000400fa,0x000001df,0x000001e0,0x000001e1,0x000200f8, + 0x000001e0,0x00060041,0x000000b8,0x000001e2,0x000000b6,0x000000b7,0x000000e6,0x0004003d, + 0x00000006,0x000001e3,0x000001e2,0x0004003d,0x00000006,0x000001e4,0x00000173,0x0007000c, + 0x00000006,0x000001e5,0x00000001,0x00000028,0x000001e3,0x000001e4,0x0004003d,0x00000006, + 0x000001e6,0x00000173,0x00050088,0x00000006,0x000001e7,0x000001e5,0x000001e6,0x0004003d, + 0x00000006,0x000001e9,0x000001d5,0x0003003e,0x000001e8,0x000001e9,0x0003003e,0x000001ea, + 0x000001e7,0x00060039,0x00000006,0x000001eb,0x0000001a,0x000001e8,0x000001ea,0x0004003d, + 0x00000006,0x000001ec,0x000001d5,0x00050088,0x00000006,0x000001ed,0x000001eb,0x000001ec, + 0x0004003d,0x00000007,0x000001ee,0x000001c0,0x0005008e,0x00000007,0x000001ef,0x000001ee, + 0x000001ed,0x0003003e,0x000001c0,0x000001ef,0x000200f9,0x000001e1,0x000200f8,0x000001e1, + 0x0004003d,0x00000007,0x000001f0,0x000001c0,0x00060050,0x00000007,0x000001f1,0x0000005c, + 0x0000005c,0x0000005c,0x00060050,0x00000007,0x000001f2,0x0000005d,0x0000005d,0x0000005d, + 0x0008000c,0x00000007,0x000001f3,0x00000001,0x0000002b,0x000001f0,0x000001f1,0x000001f2, + 0x0003003e,0x000001f4,0x000001f3,0x00050039,0x00000007,0x000001f5,0x0000000e,0x000001f4, + 0x0003003e,0x00000180,0x000001f5,0x000200f9,0x000001af,0x000200f8,0x000001af,0x000200f9, + 0x0000017c,0x000200f8,0x0000017c,0x0004003d,0x00000007,0x000001f8,0x00000180,0x00050051, + 0x00000006,0x000001f9,0x000001f8,0x00000000,0x00050051,0x00000006,0x000001fa,0x000001f8, + 0x00000001,0x00050051,0x00000006,0x000001fb,0x000001f8,0x00000002,0x00070050,0x000000ad, + 0x000001fc,0x000001f9,0x000001fa,0x000001fb,0x0000005d,0x0003003e,0x000001f7,0x000001fc, 0x000100fd,0x00010038,0x00050036,0x00000007,0x0000000b,0x00000000,0x00000009,0x00030037, - 0x00000008,0x0000000a,0x000200f8,0x0000000c,0x0004003b,0x00000008,0x00000023,0x00000007, - 0x0004003b,0x00000008,0x00000028,0x00000007,0x0004003d,0x00000007,0x00000024,0x0000000a, - 0x00060050,0x00000007,0x00000026,0x00000025,0x00000025,0x00000025,0x00050088,0x00000007, - 0x00000027,0x00000024,0x00000026,0x0003003e,0x00000023,0x00000027,0x0004003d,0x00000007, - 0x00000029,0x0000000a,0x00060050,0x00000007,0x0000002b,0x0000002a,0x0000002a,0x0000002a, - 0x00050081,0x00000007,0x0000002c,0x00000029,0x0000002b,0x00060050,0x00000007,0x0000002e, - 0x0000002d,0x0000002d,0x0000002d,0x00050088,0x00000007,0x0000002f,0x0000002c,0x0000002e, - 0x0007000c,0x00000007,0x00000032,0x00000001,0x0000001a,0x0000002f,0x00000031,0x0003003e, - 0x00000028,0x00000032,0x0004003d,0x00000007,0x00000033,0x00000023,0x0004003d,0x00000007, - 0x00000034,0x00000028,0x0004003d,0x00000007,0x00000037,0x0000000a,0x0007000c,0x00000007, - 0x00000038,0x00000001,0x00000030,0x00000036,0x00000037,0x0008000c,0x00000007,0x00000039, - 0x00000001,0x0000002e,0x00000033,0x00000034,0x00000038,0x000200fe,0x00000039,0x00010038, + 0x00000008,0x0000000a,0x000200f8,0x0000000c,0x0004003b,0x00000008,0x0000002d,0x00000007, + 0x0004003b,0x00000008,0x00000032,0x00000007,0x0004003d,0x00000007,0x0000002e,0x0000000a, + 0x00060050,0x00000007,0x00000030,0x0000002f,0x0000002f,0x0000002f,0x00050088,0x00000007, + 0x00000031,0x0000002e,0x00000030,0x0003003e,0x0000002d,0x00000031,0x0004003d,0x00000007, + 0x00000033,0x0000000a,0x00060050,0x00000007,0x00000035,0x00000034,0x00000034,0x00000034, + 0x00050081,0x00000007,0x00000036,0x00000033,0x00000035,0x00060050,0x00000007,0x00000038, + 0x00000037,0x00000037,0x00000037,0x00050088,0x00000007,0x00000039,0x00000036,0x00000038, + 0x0007000c,0x00000007,0x0000003c,0x00000001,0x0000001a,0x00000039,0x0000003b,0x0003003e, + 0x00000032,0x0000003c,0x0004003d,0x00000007,0x0000003d,0x0000002d,0x0004003d,0x00000007, + 0x0000003e,0x00000032,0x0004003d,0x00000007,0x00000041,0x0000000a,0x0007000c,0x00000007, + 0x00000042,0x00000001,0x00000030,0x00000040,0x00000041,0x0008000c,0x00000007,0x00000043, + 0x00000001,0x0000002e,0x0000003d,0x0000003e,0x00000042,0x000200fe,0x00000043,0x00010038, 0x00050036,0x00000007,0x0000000e,0x00000000,0x00000009,0x00030037,0x00000008,0x0000000d, - 0x000200f8,0x0000000f,0x0004003b,0x00000008,0x0000003c,0x00000007,0x0004003b,0x00000008, - 0x0000003f,0x00000007,0x0004003d,0x00000007,0x0000003d,0x0000000d,0x0005008e,0x00000007, - 0x0000003e,0x0000003d,0x00000025,0x0003003e,0x0000003c,0x0000003e,0x0004003d,0x00000007, - 0x00000040,0x0000000d,0x0007000c,0x00000007,0x00000043,0x00000001,0x0000001a,0x00000040, - 0x00000042,0x0005008e,0x00000007,0x00000044,0x00000043,0x0000002d,0x00060050,0x00000007, - 0x00000045,0x0000002a,0x0000002a,0x0000002a,0x00050083,0x00000007,0x00000046,0x00000044, - 0x00000045,0x0003003e,0x0000003f,0x00000046,0x0004003d,0x00000007,0x00000047,0x0000003c, - 0x0004003d,0x00000007,0x00000048,0x0000003f,0x0004003d,0x00000007,0x0000004b,0x0000000d, - 0x0007000c,0x00000007,0x0000004c,0x00000001,0x00000030,0x0000004a,0x0000004b,0x0008000c, - 0x00000007,0x0000004d,0x00000001,0x0000002e,0x00000047,0x00000048,0x0000004c,0x000200fe, - 0x0000004d,0x00010038,0x00050036,0x00000007,0x00000011,0x00000000,0x00000009,0x00030037, - 0x00000008,0x00000010,0x000200f8,0x00000012,0x0004003b,0x00000008,0x00000050,0x00000007, - 0x0004003d,0x00000007,0x00000051,0x00000010,0x00060050,0x00000007,0x00000054,0x00000052, - 0x00000052,0x00000052,0x00060050,0x00000007,0x00000055,0x00000053,0x00000053,0x00000053, - 0x0008000c,0x00000007,0x00000056,0x00000001,0x0000002b,0x00000051,0x00000054,0x00000055, - 0x0007000c,0x00000007,0x00000059,0x00000001,0x0000001a,0x00000056,0x00000058,0x0003003e, - 0x00000050,0x00000059,0x0004003d,0x00000007,0x0000005a,0x00000050,0x00060050,0x00000007, - 0x0000005c,0x0000005b,0x0000005b,0x0000005b,0x00050083,0x00000007,0x0000005d,0x0000005a, - 0x0000005c,0x00060050,0x00000007,0x0000005e,0x00000052,0x00000052,0x00000052,0x0007000c, - 0x00000007,0x0000005f,0x00000001,0x00000028,0x0000005d,0x0000005e,0x0004003d,0x00000007, - 0x00000062,0x00000050,0x0005008e,0x00000007,0x00000063,0x00000062,0x00000061,0x00060050, - 0x00000007,0x00000064,0x00000060,0x00000060,0x00000060,0x00050083,0x00000007,0x00000065, - 0x00000064,0x00000063,0x00060050,0x00000007,0x00000067,0x00000066,0x00000066,0x00000066, - 0x0007000c,0x00000007,0x00000068,0x00000001,0x00000028,0x00000065,0x00000067,0x00050088, - 0x00000007,0x00000069,0x0000005f,0x00000068,0x0007000c,0x00000007,0x0000006c,0x00000001, - 0x0000001a,0x00000069,0x0000006b,0x000200fe,0x0000006c,0x00010038,0x00050036,0x00000007, + 0x000200f8,0x0000000f,0x0004003b,0x00000008,0x00000046,0x00000007,0x0004003b,0x00000008, + 0x00000049,0x00000007,0x0004003d,0x00000007,0x00000047,0x0000000d,0x0005008e,0x00000007, + 0x00000048,0x00000047,0x0000002f,0x0003003e,0x00000046,0x00000048,0x0004003d,0x00000007, + 0x0000004a,0x0000000d,0x0007000c,0x00000007,0x0000004d,0x00000001,0x0000001a,0x0000004a, + 0x0000004c,0x0005008e,0x00000007,0x0000004e,0x0000004d,0x00000037,0x00060050,0x00000007, + 0x0000004f,0x00000034,0x00000034,0x00000034,0x00050083,0x00000007,0x00000050,0x0000004e, + 0x0000004f,0x0003003e,0x00000049,0x00000050,0x0004003d,0x00000007,0x00000051,0x00000046, + 0x0004003d,0x00000007,0x00000052,0x00000049,0x0004003d,0x00000007,0x00000055,0x0000000d, + 0x0007000c,0x00000007,0x00000056,0x00000001,0x00000030,0x00000054,0x00000055,0x0008000c, + 0x00000007,0x00000057,0x00000001,0x0000002e,0x00000051,0x00000052,0x00000056,0x000200fe, + 0x00000057,0x00010038,0x00050036,0x00000007,0x00000011,0x00000000,0x00000009,0x00030037, + 0x00000008,0x00000010,0x000200f8,0x00000012,0x0004003b,0x00000008,0x0000005a,0x00000007, + 0x0004003d,0x00000007,0x0000005b,0x00000010,0x00060050,0x00000007,0x0000005e,0x0000005c, + 0x0000005c,0x0000005c,0x00060050,0x00000007,0x0000005f,0x0000005d,0x0000005d,0x0000005d, + 0x0008000c,0x00000007,0x00000060,0x00000001,0x0000002b,0x0000005b,0x0000005e,0x0000005f, + 0x0007000c,0x00000007,0x00000063,0x00000001,0x0000001a,0x00000060,0x00000062,0x0003003e, + 0x0000005a,0x00000063,0x0004003d,0x00000007,0x00000064,0x0000005a,0x00060050,0x00000007, + 0x00000066,0x00000065,0x00000065,0x00000065,0x00050083,0x00000007,0x00000067,0x00000064, + 0x00000066,0x00060050,0x00000007,0x00000068,0x0000005c,0x0000005c,0x0000005c,0x0007000c, + 0x00000007,0x00000069,0x00000001,0x00000028,0x00000067,0x00000068,0x0004003d,0x00000007, + 0x0000006c,0x0000005a,0x0005008e,0x00000007,0x0000006d,0x0000006c,0x0000006b,0x00060050, + 0x00000007,0x0000006e,0x0000006a,0x0000006a,0x0000006a,0x00050083,0x00000007,0x0000006f, + 0x0000006e,0x0000006d,0x00060050,0x00000007,0x00000071,0x00000070,0x00000070,0x00000070, + 0x0007000c,0x00000007,0x00000072,0x00000001,0x00000028,0x0000006f,0x00000071,0x00050088, + 0x00000007,0x00000073,0x00000069,0x00000072,0x0007000c,0x00000007,0x00000076,0x00000001, + 0x0000001a,0x00000073,0x00000075,0x000200fe,0x00000076,0x00010038,0x00050036,0x00000007, 0x00000014,0x00000000,0x00000009,0x00030037,0x00000008,0x00000013,0x000200f8,0x00000015, - 0x0004003b,0x00000008,0x0000006f,0x00000007,0x0004003d,0x00000007,0x00000070,0x00000013, - 0x00060050,0x00000007,0x00000071,0x00000052,0x00000052,0x00000052,0x00060050,0x00000007, - 0x00000072,0x00000053,0x00000053,0x00000053,0x0008000c,0x00000007,0x00000073,0x00000001, - 0x0000002b,0x00000070,0x00000071,0x00000072,0x0007000c,0x00000007,0x00000076,0x00000001, - 0x0000001a,0x00000073,0x00000075,0x0003003e,0x0000006f,0x00000076,0x0004003d,0x00000007, - 0x00000077,0x0000006f,0x0005008e,0x00000007,0x00000078,0x00000077,0x00000060,0x00060050, - 0x00000007,0x00000079,0x0000005b,0x0000005b,0x0000005b,0x00050081,0x00000007,0x0000007a, - 0x00000079,0x00000078,0x0004003d,0x00000007,0x0000007b,0x0000006f,0x0005008e,0x00000007, - 0x0000007c,0x0000007b,0x00000061,0x00060050,0x00000007,0x0000007d,0x00000053,0x00000053, - 0x00000053,0x00050081,0x00000007,0x0000007e,0x0000007d,0x0000007c,0x00050088,0x00000007, - 0x0000007f,0x0000007a,0x0000007e,0x0007000c,0x00000007,0x00000082,0x00000001,0x0000001a, - 0x0000007f,0x00000081,0x000200fe,0x00000082,0x00010038,0x00050036,0x00000006,0x0000001a, + 0x0004003b,0x00000008,0x00000079,0x00000007,0x0004003d,0x00000007,0x0000007a,0x00000013, + 0x00060050,0x00000007,0x0000007b,0x0000005c,0x0000005c,0x0000005c,0x00060050,0x00000007, + 0x0000007c,0x0000005d,0x0000005d,0x0000005d,0x0008000c,0x00000007,0x0000007d,0x00000001, + 0x0000002b,0x0000007a,0x0000007b,0x0000007c,0x0007000c,0x00000007,0x00000080,0x00000001, + 0x0000001a,0x0000007d,0x0000007f,0x0003003e,0x00000079,0x00000080,0x0004003d,0x00000007, + 0x00000081,0x00000079,0x0005008e,0x00000007,0x00000082,0x00000081,0x0000006a,0x00060050, + 0x00000007,0x00000083,0x00000065,0x00000065,0x00000065,0x00050081,0x00000007,0x00000084, + 0x00000083,0x00000082,0x0004003d,0x00000007,0x00000085,0x00000079,0x0005008e,0x00000007, + 0x00000086,0x00000085,0x0000006b,0x00060050,0x00000007,0x00000087,0x0000005d,0x0000005d, + 0x0000005d,0x00050081,0x00000007,0x00000088,0x00000087,0x00000086,0x00050088,0x00000007, + 0x00000089,0x00000084,0x00000088,0x0007000c,0x00000007,0x0000008c,0x00000001,0x0000001a, + 0x00000089,0x0000008b,0x000200fe,0x0000008c,0x00010038,0x00050036,0x00000006,0x0000001a, 0x00000000,0x00000017,0x00030037,0x00000016,0x00000018,0x00030037,0x00000016,0x00000019, - 0x000200f8,0x0000001b,0x0004003b,0x00000016,0x0000008c,0x00000007,0x0004003b,0x00000016, - 0x00000091,0x00000007,0x0004003d,0x00000006,0x00000085,0x00000018,0x000500bc,0x0000001e, - 0x00000087,0x00000085,0x00000086,0x000300f7,0x00000089,0x00000000,0x000400fa,0x00000087, - 0x00000088,0x00000089,0x000200f8,0x00000088,0x0004003d,0x00000006,0x0000008a,0x00000018, - 0x000200fe,0x0000008a,0x000200f8,0x00000089,0x0004003d,0x00000006,0x0000008d,0x00000019, - 0x00050083,0x00000006,0x0000008e,0x0000008d,0x00000086,0x0007000c,0x00000006,0x00000090, - 0x00000001,0x00000028,0x0000008e,0x0000008f,0x0003003e,0x0000008c,0x00000090,0x0004003d, - 0x00000006,0x00000092,0x0000008c,0x00050088,0x00000006,0x00000094,0x00000092,0x00000093, - 0x0007000c,0x00000006,0x00000096,0x00000001,0x00000028,0x00000094,0x00000095,0x0003003e, - 0x00000091,0x00000096,0x0004003d,0x00000006,0x00000097,0x00000018,0x00050083,0x00000006, - 0x00000098,0x00000097,0x00000086,0x0004007f,0x00000006,0x00000099,0x00000098,0x0004003d, - 0x00000006,0x0000009a,0x00000091,0x00050088,0x00000006,0x0000009b,0x00000099,0x0000009a, - 0x0006000c,0x00000006,0x0000009c,0x00000001,0x0000001b,0x0000009b,0x00050083,0x00000006, - 0x0000009d,0x00000053,0x0000009c,0x00050085,0x00000006,0x0000009e,0x00000095,0x0000009d, - 0x00050081,0x00000006,0x0000009f,0x00000086,0x0000009e,0x000200fe,0x0000009f,0x00010038, + 0x000200f8,0x0000001b,0x0004003b,0x00000016,0x00000096,0x00000007,0x0004003b,0x00000016, + 0x0000009b,0x00000007,0x0004003d,0x00000006,0x0000008f,0x00000018,0x000500bc,0x00000024, + 0x00000091,0x0000008f,0x00000090,0x000300f7,0x00000093,0x00000000,0x000400fa,0x00000091, + 0x00000092,0x00000093,0x000200f8,0x00000092,0x0004003d,0x00000006,0x00000094,0x00000018, + 0x000200fe,0x00000094,0x000200f8,0x00000093,0x0004003d,0x00000006,0x00000097,0x00000019, + 0x00050083,0x00000006,0x00000098,0x00000097,0x00000090,0x0007000c,0x00000006,0x0000009a, + 0x00000001,0x00000028,0x00000098,0x00000099,0x0003003e,0x00000096,0x0000009a,0x0004003d, + 0x00000006,0x0000009c,0x00000096,0x00050088,0x00000006,0x0000009e,0x0000009c,0x0000009d, + 0x0007000c,0x00000006,0x000000a0,0x00000001,0x00000028,0x0000009e,0x0000009f,0x0003003e, + 0x0000009b,0x000000a0,0x0004003d,0x00000006,0x000000a1,0x00000018,0x00050083,0x00000006, + 0x000000a2,0x000000a1,0x00000090,0x0004007f,0x00000006,0x000000a3,0x000000a2,0x0004003d, + 0x00000006,0x000000a4,0x0000009b,0x00050088,0x00000006,0x000000a5,0x000000a3,0x000000a4, + 0x0006000c,0x00000006,0x000000a6,0x00000001,0x0000001b,0x000000a5,0x00050083,0x00000006, + 0x000000a7,0x0000005d,0x000000a6,0x00050085,0x00000006,0x000000a8,0x0000009f,0x000000a7, + 0x00050081,0x00000006,0x000000a9,0x00000090,0x000000a8,0x000200fe,0x000000a9,0x00010038, 0x00050036,0x0000001e,0x00000021,0x00000000,0x0000001f,0x00030037,0x0000001d,0x00000020, - 0x000200f8,0x00000022,0x0004003b,0x00000016,0x000000a2,0x00000007,0x0004003b,0x00000016, - 0x000000b0,0x00000007,0x0004003b,0x00000016,0x000000b4,0x00000007,0x0004003b,0x000000b8, - 0x000000b9,0x00000007,0x0004003b,0x000000cc,0x000000cd,0x00000007,0x0004003b,0x00000016, - 0x000000f5,0x00000007,0x00060041,0x000000ad,0x000000ae,0x000000a9,0x000000ab,0x000000ac, - 0x0004003d,0x00000006,0x000000af,0x000000ae,0x0003003e,0x000000a2,0x000000af,0x0004003d, - 0x00000006,0x000000b1,0x000000a2,0x0005008d,0x00000006,0x000000b3,0x000000b1,0x000000b2, - 0x0003003e,0x000000b0,0x000000b3,0x0004003d,0x00000006,0x000000b5,0x000000a2,0x00050088, - 0x00000006,0x000000b6,0x000000b5,0x000000b2,0x0006000c,0x00000006,0x000000b7,0x00000001, - 0x00000008,0x000000b6,0x0003003e,0x000000b4,0x000000b7,0x0003003e,0x000000b9,0x000000ba, - 0x000200f9,0x000000bb,0x000200f8,0x000000bb,0x000400f6,0x000000bd,0x000000be,0x00000000, - 0x000200f9,0x000000bf,0x000200f8,0x000000bf,0x0004003d,0x000000aa,0x000000c0,0x000000b9, - 0x000500b1,0x0000001e,0x000000c2,0x000000c0,0x000000c1,0x000400fa,0x000000c2,0x000000bc, - 0x000000bd,0x000200f8,0x000000bc,0x0004003d,0x000000aa,0x000000c3,0x000000b9,0x0004006f, - 0x00000006,0x000000c4,0x000000c3,0x0004003d,0x00000006,0x000000c5,0x000000b0,0x00050083, - 0x00000006,0x000000c7,0x000000c5,0x000000c6,0x000500be,0x0000001e,0x000000c8,0x000000c4, - 0x000000c7,0x000300f7,0x000000ca,0x00000000,0x000400fa,0x000000c8,0x000000c9,0x000000ca, - 0x000200f8,0x000000c9,0x000200f9,0x000000bd,0x000200f8,0x000000ca,0x0004003d,0x000000aa, - 0x000000cf,0x000000b9,0x00060041,0x000000d0,0x000000d1,0x000000a9,0x000000ce,0x000000cf, - 0x0004003d,0x000000a3,0x000000d2,0x000000d1,0x0003003e,0x000000cd,0x000000d2,0x00050041, - 0x00000016,0x000000d4,0x00000020,0x000000d3,0x0004003d,0x00000006,0x000000d5,0x000000d4, - 0x00050041,0x00000016,0x000000d6,0x000000cd,0x000000d3,0x0004003d,0x00000006,0x000000d7, - 0x000000d6,0x000500be,0x0000001e,0x000000d8,0x000000d5,0x000000d7,0x000300f7,0x000000da, - 0x00000000,0x000400fa,0x000000d8,0x000000d9,0x000000da,0x000200f8,0x000000d9,0x00050041, - 0x00000016,0x000000dc,0x00000020,0x000000db,0x0004003d,0x00000006,0x000000dd,0x000000dc, - 0x00050041,0x00000016,0x000000de,0x000000cd,0x000000db,0x0004003d,0x00000006,0x000000df, - 0x000000de,0x000500be,0x0000001e,0x000000e0,0x000000dd,0x000000df,0x000200f9,0x000000da, - 0x000200f8,0x000000da,0x000700f5,0x0000001e,0x000000e1,0x000000d8,0x000000ca,0x000000e0, - 0x000000d9,0x000300f7,0x000000e3,0x00000000,0x000400fa,0x000000e1,0x000000e2,0x000000e3, - 0x000200f8,0x000000e2,0x00050041,0x00000016,0x000000e4,0x00000020,0x000000d3,0x0004003d, - 0x00000006,0x000000e5,0x000000e4,0x00050041,0x00000016,0x000000e7,0x000000cd,0x000000e6, - 0x0004003d,0x00000006,0x000000e8,0x000000e7,0x000500b8,0x0000001e,0x000000e9,0x000000e5, - 0x000000e8,0x000200f9,0x000000e3,0x000200f8,0x000000e3,0x000700f5,0x0000001e,0x000000ea, - 0x000000e1,0x000000da,0x000000e9,0x000000e2,0x000300f7,0x000000ec,0x00000000,0x000400fa, - 0x000000ea,0x000000eb,0x000000ec,0x000200f8,0x000000eb,0x00050041,0x00000016,0x000000ed, - 0x00000020,0x000000db,0x0004003d,0x00000006,0x000000ee,0x000000ed,0x00050041,0x00000016, - 0x000000ef,0x000000cd,0x000000ac,0x0004003d,0x00000006,0x000000f0,0x000000ef,0x000500b8, - 0x0000001e,0x000000f1,0x000000ee,0x000000f0,0x000200f9,0x000000ec,0x000200f8,0x000000ec, - 0x000700f5,0x0000001e,0x000000f2,0x000000ea,0x000000e3,0x000000f1,0x000000eb,0x000300f7, - 0x000000f4,0x00000000,0x000400fa,0x000000f2,0x000000f3,0x000000f4,0x000200f8,0x000000f3, - 0x0004003d,0x00000006,0x000000f6,0x000000b4,0x0004003d,0x000000aa,0x000000f7,0x000000b9, - 0x0004006f,0x00000006,0x000000f8,0x000000f7,0x0006000c,0x00000006,0x000000f9,0x00000001, - 0x0000001d,0x000000f8,0x00050088,0x00000006,0x000000fa,0x000000f6,0x000000f9,0x0006000c, - 0x00000006,0x000000fb,0x00000001,0x00000008,0x000000fa,0x0005008d,0x00000006,0x000000fd, - 0x000000fb,0x000000fc,0x0003003e,0x000000f5,0x000000fd,0x0004003d,0x00000006,0x000000fe, - 0x000000f5,0x000500ba,0x0000001e,0x000000ff,0x000000fe,0x000000c6,0x000200fe,0x000000ff, - 0x000200f8,0x000000f4,0x000200f9,0x000000be,0x000200f8,0x000000be,0x0004003d,0x000000aa, - 0x00000101,0x000000b9,0x00050080,0x000000aa,0x00000102,0x00000101,0x000000ab,0x0003003e, - 0x000000b9,0x00000102,0x000200f9,0x000000bb,0x000200f8,0x000000bd,0x000200fe,0x00000103, - 0x00010038 + 0x000200f8,0x00000022,0x0004003b,0x00000016,0x000000ac,0x00000007,0x0004003b,0x00000023, + 0x000000bd,0x00000007,0x0004003b,0x000000d0,0x000000d1,0x00000007,0x0004003b,0x0000001d, + 0x000000d7,0x00000007,0x0004003b,0x0000001d,0x000000e5,0x00000007,0x00060041,0x000000b8, + 0x000000b9,0x000000b6,0x000000b7,0x000000b2,0x0004003d,0x00000006,0x000000ba,0x000000b9, + 0x0005008d,0x00000006,0x000000bc,0x000000ba,0x000000bb,0x0003003e,0x000000ac,0x000000bc, + 0x0003003e,0x000000bd,0x000000be,0x000200f9,0x000000bf,0x000200f8,0x000000bf,0x000400f6, + 0x000000c1,0x000000c2,0x00000000,0x000200f9,0x000000c3,0x000200f8,0x000000c3,0x0004003d, + 0x0000001e,0x000000c4,0x000000bd,0x000500b1,0x00000024,0x000000c6,0x000000c4,0x000000c5, + 0x000400fa,0x000000c6,0x000000c0,0x000000c1,0x000200f8,0x000000c0,0x0004003d,0x0000001e, + 0x000000c7,0x000000bd,0x0004006f,0x00000006,0x000000c8,0x000000c7,0x0004003d,0x00000006, + 0x000000c9,0x000000ac,0x00050083,0x00000006,0x000000cb,0x000000c9,0x000000ca,0x000500be, + 0x00000024,0x000000cc,0x000000c8,0x000000cb,0x000300f7,0x000000ce,0x00000000,0x000400fa, + 0x000000cc,0x000000cd,0x000000ce,0x000200f8,0x000000cd,0x000200f9,0x000000c1,0x000200f8, + 0x000000ce,0x0004003d,0x0000001e,0x000000d3,0x000000bd,0x00060041,0x000000d4,0x000000d5, + 0x000000b6,0x000000d2,0x000000d3,0x0004003d,0x000000af,0x000000d6,0x000000d5,0x0003003e, + 0x000000d1,0x000000d6,0x00050041,0x000000d9,0x000000da,0x000000d1,0x000000d8,0x0004003d, + 0x000000ae,0x000000db,0x000000da,0x000500c7,0x000000ae,0x000000dd,0x000000db,0x000000dc, + 0x00040070,0x00000006,0x000000de,0x000000dd,0x00050041,0x000000d9,0x000000df,0x000000d1, + 0x000000d8,0x0004003d,0x000000ae,0x000000e0,0x000000df,0x000500c2,0x000000ae,0x000000e2, + 0x000000e0,0x000000e1,0x00040070,0x00000006,0x000000e3,0x000000e2,0x00050050,0x0000001c, + 0x000000e4,0x000000de,0x000000e3,0x0003003e,0x000000d7,0x000000e4,0x00050041,0x000000d9, + 0x000000e7,0x000000d1,0x000000e6,0x0004003d,0x000000ae,0x000000e8,0x000000e7,0x000500c7, + 0x000000ae,0x000000e9,0x000000e8,0x000000dc,0x00040070,0x00000006,0x000000ea,0x000000e9, + 0x00050041,0x000000d9,0x000000eb,0x000000d1,0x000000e6,0x0004003d,0x000000ae,0x000000ec, + 0x000000eb,0x000500c2,0x000000ae,0x000000ed,0x000000ec,0x000000e1,0x00040070,0x00000006, + 0x000000ee,0x000000ed,0x00050050,0x0000001c,0x000000ef,0x000000ea,0x000000ee,0x0003003e, + 0x000000e5,0x000000ef,0x00050041,0x00000016,0x000000f0,0x00000020,0x000000d8,0x0004003d, + 0x00000006,0x000000f1,0x000000f0,0x00050041,0x00000016,0x000000f2,0x000000d7,0x000000d8, + 0x0004003d,0x00000006,0x000000f3,0x000000f2,0x000500be,0x00000024,0x000000f4,0x000000f1, + 0x000000f3,0x000300f7,0x000000f6,0x00000000,0x000400fa,0x000000f4,0x000000f5,0x000000f6, + 0x000200f8,0x000000f5,0x00050041,0x00000016,0x000000f7,0x00000020,0x000000e6,0x0004003d, + 0x00000006,0x000000f8,0x000000f7,0x00050041,0x00000016,0x000000f9,0x000000d7,0x000000e6, + 0x0004003d,0x00000006,0x000000fa,0x000000f9,0x000500be,0x00000024,0x000000fb,0x000000f8, + 0x000000fa,0x000200f9,0x000000f6,0x000200f8,0x000000f6,0x000700f5,0x00000024,0x000000fc, + 0x000000f4,0x000000ce,0x000000fb,0x000000f5,0x000300f7,0x000000fe,0x00000000,0x000400fa, + 0x000000fc,0x000000fd,0x000000fe,0x000200f8,0x000000fd,0x00050041,0x00000016,0x000000ff, + 0x00000020,0x000000d8,0x0004003d,0x00000006,0x00000100,0x000000ff,0x00050041,0x00000016, + 0x00000101,0x000000e5,0x000000d8,0x0004003d,0x00000006,0x00000102,0x00000101,0x000500b8, + 0x00000024,0x00000103,0x00000100,0x00000102,0x000200f9,0x000000fe,0x000200f8,0x000000fe, + 0x000700f5,0x00000024,0x00000104,0x000000fc,0x000000f6,0x00000103,0x000000fd,0x000300f7, + 0x00000106,0x00000000,0x000400fa,0x00000104,0x00000105,0x00000106,0x000200f8,0x00000105, + 0x00050041,0x00000016,0x00000107,0x00000020,0x000000e6,0x0004003d,0x00000006,0x00000108, + 0x00000107,0x00050041,0x00000016,0x00000109,0x000000e5,0x000000e6,0x0004003d,0x00000006, + 0x0000010a,0x00000109,0x000500b8,0x00000024,0x0000010b,0x00000108,0x0000010a,0x000200f9, + 0x00000106,0x000200f8,0x00000106,0x000700f5,0x00000024,0x0000010c,0x00000104,0x000000fe, + 0x0000010b,0x00000105,0x000300f7,0x0000010e,0x00000000,0x000400fa,0x0000010c,0x0000010d, + 0x0000010e,0x000200f8,0x0000010d,0x0004003d,0x0000001e,0x0000010f,0x000000bd,0x000200fe, + 0x0000010f,0x000200f8,0x0000010e,0x000200f9,0x000000c2,0x000200f8,0x000000c2,0x0004003d, + 0x0000001e,0x00000111,0x000000bd,0x00050080,0x0000001e,0x00000112,0x00000111,0x000000b7, + 0x0003003e,0x000000bd,0x00000112,0x000200f9,0x000000bf,0x000200f8,0x000000c1,0x000200fe, + 0x00000113,0x00010038,0x00050036,0x00000024,0x00000028,0x00000000,0x00000025,0x00030037, + 0x00000016,0x00000026,0x00030037,0x00000023,0x00000027,0x000200f8,0x00000029,0x0004003d, + 0x0000001e,0x00000116,0x00000027,0x000500af,0x00000024,0x00000117,0x00000116,0x000000be, + 0x000300f7,0x00000119,0x00000000,0x000400fa,0x00000117,0x00000118,0x00000119,0x000200f8, + 0x00000118,0x0004003d,0x00000006,0x0000011a,0x00000026,0x0004003d,0x0000001e,0x0000011b, + 0x00000027,0x0004006f,0x00000006,0x0000011c,0x0000011b,0x0006000c,0x00000006,0x0000011d, + 0x00000001,0x0000001d,0x0000011c,0x00050088,0x00000006,0x0000011e,0x0000011a,0x0000011d, + 0x0006000c,0x00000006,0x0000011f,0x00000001,0x00000008,0x0000011e,0x0005008d,0x00000006, + 0x00000121,0x0000011f,0x00000120,0x000500ba,0x00000024,0x00000122,0x00000121,0x000000ca, + 0x000200f9,0x00000119,0x000200f8,0x00000119,0x000700f5,0x00000024,0x00000123,0x00000117, + 0x00000029,0x00000122,0x00000118,0x000200fe,0x00000123,0x00010038,0x00050036,0x00000007, + 0x0000002b,0x00000000,0x00000009,0x00030037,0x00000008,0x0000002a,0x000200f8,0x0000002c, + 0x0004003b,0x00000008,0x00000126,0x00000007,0x0004003b,0x00000008,0x0000012b,0x00000007, + 0x0004003b,0x00000008,0x00000130,0x00000007,0x00070041,0x000000b8,0x00000128,0x000000b6, + 0x00000127,0x000000b7,0x000000b2,0x0004003d,0x00000006,0x00000129,0x00000128,0x000500ba, + 0x00000024,0x0000012a,0x00000129,0x000000ca,0x000300f7,0x0000012d,0x00000000,0x000400fa, + 0x0000012a,0x0000012c,0x0000012f,0x000200f8,0x0000012c,0x0004003d,0x00000007,0x0000012e, + 0x0000002a,0x0003003e,0x0000012b,0x0000012e,0x000200f9,0x0000012d,0x000200f8,0x0000012f, + 0x0004003d,0x00000007,0x00000131,0x0000002a,0x0003003e,0x00000130,0x00000131,0x00050039, + 0x00000007,0x00000132,0x00000011,0x00000130,0x0003003e,0x0000012b,0x00000132,0x000200f9, + 0x0000012d,0x000200f8,0x0000012d,0x0004003d,0x00000007,0x00000133,0x0000012b,0x0003003e, + 0x00000126,0x00000133,0x00060041,0x00000134,0x00000135,0x000000b6,0x00000127,0x000000be, + 0x0004003d,0x000000ad,0x00000136,0x00000135,0x0008004f,0x00000007,0x00000137,0x00000136, + 0x00000136,0x00000000,0x00000001,0x00000002,0x0004003d,0x00000007,0x00000138,0x00000126, + 0x00050094,0x00000006,0x00000139,0x00000137,0x00000138,0x00060041,0x00000134,0x0000013a, + 0x000000b6,0x00000127,0x000000b7,0x0004003d,0x000000ad,0x0000013b,0x0000013a,0x0008004f, + 0x00000007,0x0000013c,0x0000013b,0x0000013b,0x00000000,0x00000001,0x00000002,0x0004003d, + 0x00000007,0x0000013d,0x00000126,0x00050094,0x00000006,0x0000013e,0x0000013c,0x0000013d, + 0x00060041,0x00000134,0x0000013f,0x000000b6,0x00000127,0x000000d2,0x0004003d,0x000000ad, + 0x00000140,0x0000013f,0x0008004f,0x00000007,0x00000141,0x00000140,0x00000140,0x00000000, + 0x00000001,0x00000002,0x0004003d,0x00000007,0x00000142,0x00000126,0x00050094,0x00000006, + 0x00000143,0x00000141,0x00000142,0x00060050,0x00000007,0x00000144,0x00000139,0x0000013e, + 0x00000143,0x00070041,0x000000b8,0x00000145,0x000000b6,0x00000127,0x000000d2,0x000000b2, + 0x0004003d,0x00000006,0x00000146,0x00000145,0x0005008e,0x00000007,0x00000147,0x00000144, + 0x00000146,0x000200fe,0x00000147,0x00010038 }; diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c index c760d91c22..74cd5d6b45 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -3,6 +3,7 @@ #include "ahb_swapchain.h" #include "droiddeck_color.h" #include "vk_present.h" +#include "framegen_bridge.h" #include #include #include @@ -64,6 +65,8 @@ static struct { void (*setHdrMetadata_cta861_3)(ASurfaceTransaction *, ASurfaceControl *, const struct droiddeck_hdr_cta861_3 *); const void *(*getNativeHandle)(const AHardwareBuffer *); void (*setDesiredHdrHeadroom)(ASurfaceTransaction *, ASurfaceControl *, float); + void (*setEnableBackPressure)(ASurfaceTransaction *, ASurfaceControl *, bool); + void (*setDesiredPresentTime)(ASurfaceTransaction *, int64_t); int state; } api; @@ -105,6 +108,8 @@ static int load_api(void) { SYM(setHdrMetadata_smpte2086, "ASurfaceTransaction_setHdrMetadata_smpte2086"); SYM(setHdrMetadata_cta861_3, "ASurfaceTransaction_setHdrMetadata_cta861_3"); SYM(setDesiredHdrHeadroom, "ASurfaceTransaction_setDesiredHdrHeadroom"); + SYM(setEnableBackPressure, "ASurfaceTransaction_setEnableBackPressure"); + SYM(setDesiredPresentTime, "ASurfaceTransaction_setDesiredPresentTime"); #undef SYM if (!api.createFromWindow || !api.release || !api.txCreate || !api.txDelete || !api.txApply || !api.setBuffer || !api.setZOrder || !api.setVisibility || !api.setGeometry || @@ -134,7 +139,7 @@ void sc_layer_set_frame_rate(float fps) { } -#define POOL_MAX 5 +#define POOL_MAX 8 struct slot { AHardwareBuffer *ahb; @@ -158,6 +163,7 @@ struct layer { ARect geo_src, geo_dst; int geo_valid; int alloc_tier; + unsigned import_failed_fmts; uint64_t pool_modifier; int first_logged; int64_t drop_logged_ns; @@ -183,6 +189,12 @@ static int g_layers_ready; static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; static int g_pending_cb; static unsigned g_stat_layer_frames; +static pthread_mutex_t g_timeline_lock = PTHREAD_MUTEX_INITIALIZER; +static int64_t g_timeline_present_ns, g_timeline_deadline_ns, g_timeline_period_ns; +static int g_timeline_late; +static int64_t g_cadence_seen_ns, g_cadence_gap_ns, g_cadence_target_ns; +static int g_group_frames = 1, g_group_index; +static unsigned g_stat_aimed_next, g_stat_aimed_later, g_stat_aimed_even; static int g_two_logged; static AHardwareBuffer *g_blank; static ASurfaceControl *g_base_sc; @@ -219,6 +231,58 @@ static int64_t now_ns(void) { return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec; } +void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns) { + pthread_mutex_lock(&g_timeline_lock); + g_timeline_present_ns = present_ns; + g_timeline_deadline_ns = deadline_ns; + g_timeline_period_ns = period_ns; + pthread_mutex_unlock(&g_timeline_lock); +} + +static int64_t cadence_target(int64_t now, int64_t earliest, int64_t period) { + const int64_t gap = now - g_cadence_seen_ns; + g_cadence_seen_ns = now; + if (gap <= 0 || gap > 8 * period) { + g_cadence_gap_ns = 0; + g_cadence_target_ns = earliest; + return earliest; + } + g_cadence_gap_ns = g_cadence_gap_ns ? (g_cadence_gap_ns * 15 + gap) / 16 : gap; + const int64_t steps = (g_cadence_gap_ns + period / 2) / period; + const int64_t even = g_cadence_target_ns + steps * period; + int64_t target = earliest; + if (steps >= 1 && llabs(g_cadence_gap_ns - steps * period) < period / 8 && + even > earliest + period / 2 && even < earliest + steps * period + period / 2) { + target = even; + g_stat_aimed_even++; + } + g_cadence_target_ns = target; + return target; +} + +static void apply_present_time(ASurfaceTransaction *tx, int game) { + if (!api.setDesiredPresentTime) return; + pthread_mutex_lock(&g_timeline_lock); + const int64_t present = g_timeline_present_ns, deadline = g_timeline_deadline_ns, period = g_timeline_period_ns; + pthread_mutex_unlock(&g_timeline_lock); + const int64_t now = now_ns(); + if (period <= 0 || now - deadline > 4 * period) return; + int64_t ahead = now > deadline ? (now - deadline + period - 1) / period : -((deadline - now) / period); + const int64_t slack = deadline + ahead * period - now; + g_timeline_late = slack < (g_timeline_late ? period * 5 / 8 : period / 8); + if (g_timeline_late) { ahead++; g_stat_aimed_later++; } else g_stat_aimed_next++; + int64_t target = present + ahead * period; + if (game && g_group_index > 0) { + int64_t steps = (g_group_index * g_cadence_gap_ns / g_group_frames + period / 2) / period; + if (steps < g_group_index) steps = g_group_index; + if (target < g_cadence_target_ns + steps * period) target = g_cadence_target_ns + steps * period; + } else if (game) { + target = cadence_target(now, target, period); + } + if (game && g_group_frames > 1 && ++g_group_index >= g_group_frames) { g_group_index = 0; g_group_frames = 1; } + api.setDesiredPresentTime(tx, target - period / 2); +} + static void on_complete(void *context, ASurfaceTransactionStats *stats) { struct complete_ctx *ctx = context; pthread_mutex_lock(&g_lock); @@ -401,10 +465,22 @@ static void describe_handle(const struct droiddeck_native_handle *h, char *out, o += (size_t)snprintf(out + o, n - o, " %#x", (unsigned)h->data[h->numFds + i]); } +static int handle_fd(const struct droiddeck_native_handle *h, off_t need, int *which) { + for (int i = 0; h && i < h->numFds; i++) { + off_t sz = lseek(h->data[i], 0, SEEK_END); + if (sz >= 0) lseek(h->data[i], 0, SEEK_SET); + if (sz >= need) { if (which) *which = i; return h->data[i]; } + } + return -1; +} + +int sc_layer_ahb_fd(AHardwareBuffer *ahb, uint64_t need) { + return load_api() == 0 ? handle_fd(api.getNativeHandle(ahb), (off_t)need, NULL) : -1; +} + static int g_alloc_failed; enum { TIER_UBWC, TIER_PLAIN, TIER_LINEAR }; -#define DROIDDECK_AHB_USAGE_VENDOR_UBWC (1ULL << 28) static const char *tier_name(int tier) { return tier == TIER_UBWC ? "asked for UBWC" : tier == TIER_PLAIN ? "no UBWC request" : "linear by request (CPU bit)"; @@ -412,14 +488,15 @@ static const char *tier_name(int tier) { static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fmt) { g_alloc_failed = 0; - while (l->alloc_tier <= TIER_LINEAR) { + const unsigned fmt_bit = fmt == AHB_RGB10A2 ? 2u : 1u; + while (l->alloc_tier <= TIER_LINEAR && !(l->import_failed_fmts & fmt_bit)) { const int tier = l->alloc_tier; AHardwareBuffer_Desc d = { .width = (uint32_t)w, .height = (uint32_t)h, .layers = 1, .format = fmt, .usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY | - (tier == TIER_UBWC ? DROIDDECK_AHB_USAGE_VENDOR_UBWC : 0) | + (tier == TIER_UBWC ? SC_LAYER_AHB_USAGE_VENDOR_UBWC : 0) | (tier == TIER_LINEAR ? AHARDWAREBUFFER_USAGE_CPU_READ_RARELY : 0)}; AHardwareBuffer *ahb = NULL; if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) { @@ -443,6 +520,10 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm img = vkp_image_import_dmabuf(nh->data[0], fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888, mod, w, h, got.stride * 4, 0, 1); path = "dma-buf (QTI handle)"; + if (!img && mod == MOD_LINEAR && vkp_can_import_ahb()) { + img = vkp_image_import_ahb(ahb, info, sizeof(info)); + if (img) { mod = SC_MOD_GRALLOC; path = "AHardwareBuffer"; } + } } else { if (tier == TIER_UBWC) { char hd[256]; @@ -459,13 +540,8 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm path = "AHardwareBuffer"; img = vkp_image_import_ahb(ahb, info, sizeof(info)); if (!img && tier == TIER_LINEAR) { - const off_t need = (off_t)got.stride * 4 * h; - int fd = -1, which = -1; - for (int i = 0; nh && i < nh->numFds; i++) { - off_t sz = lseek(nh->data[i], 0, SEEK_END); - if (sz >= 0) lseek(nh->data[i], 0, SEEK_SET); - if (sz >= need) { fd = nh->data[i]; which = i; break; } - } + int which = -1; + int fd = handle_fd(nh, (off_t)got.stride * 4 * h, &which); if (fd < 0 && nh && nh->numFds > 0) { fd = nh->data[0]; which = 0; } mod = MOD_LINEAR; path = "linear dma-buf"; @@ -486,6 +562,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd); AHardwareBuffer_release(ahb); if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; } + l->import_failed_fmts |= fmt_bit; g_alloc_failed = 1; return -1; } @@ -506,16 +583,27 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm return -1; } -static int fence_signalled(int fd) { +static int fence_wait(int fd, int timeout_ms) { struct pollfd p = {.fd = fd, .events = POLLIN}; int r; - do { r = poll(&p, 1, 0); } while (r < 0 && errno == EINTR); - return r > 0; + do { r = poll(&p, 1, timeout_ms); } while (r < 0 && errno == EINTR); + return r; +} + +static int fence_signalled(int fd) { + return fence_wait(fd, 0) > 0; +} + +static void slot_keep_fence(struct slot *s, int fd) { + pthread_mutex_lock(&g_lock); + if (s->release_fd < 0) s->release_fd = fd; else close(fd); + pthread_mutex_unlock(&g_lock); } static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait_fd) { int idx = -1, pending = -1, fd = -1; *wait_fd = -1; + g_alloc_failed = 0; pthread_mutex_lock(&g_lock); for (int i = 0; i < l->pool_n; i++) { if (i == l->cur_slot || l->slots[i].busy) continue; @@ -535,15 +623,7 @@ static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait memset(s, 0, sizeof(*s)); s->release_fd = -1; } if (fd >= 0 && !vkp_can_wait_sync_fd()) { - struct pollfd p = {.fd = fd, .events = POLLIN}; - int r; - do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); - if (r == 0) { - pthread_mutex_lock(&g_lock); - if (s->release_fd < 0) s->release_fd = fd; else close(fd); - pthread_mutex_unlock(&g_lock); - return -1; - } + if (fence_wait(fd, 100) == 0) { slot_keep_fence(s, fd); return -1; } close(fd); fd = -1; } @@ -558,6 +638,8 @@ static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait int sc_layer_available(void) { return load_api() == 0; } +int sc_layer_queues(void) { return load_api() == 0 && api.setEnableBackPressure != NULL; } + void sc_layer_probe_dmabuf_fd(int fd) { static int done; if (done || fd < 0) return; @@ -595,9 +677,10 @@ static int ensure_sc(struct layer *l) { return 0; } -static int layer_geometry(int w, int h, int scene_w, int scene_h, int r[8]) { +static int layer_geometry(int w, int h, int scene_w, int scene_h, const struct vkp_draw *draw, int r[8]) { if (vkp_update_map(scene_w, scene_h) != 0) return -1; - return vkp_map_rect(w, h, scene_w, scene_h, r) ? 1 : 0; + if (draw) return vkp_map_draw(draw, r) ? 1 : 0; + return vkp_map_rect(w, h, (const int[4]){0, 0, scene_w, scene_h}, r) ? 1 : 0; } static ARect g_game_src, g_game_dst; @@ -757,6 +840,7 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d ASurfaceControl *old = swap_sc_begin(l); if (old) api.setZOrder(tx, l->sc, l->z); api.setBuffer(tx, l->sc, s->ahb, -1); + if (api.setEnableBackPressure) api.setEnableBackPressure(tx, l->sc, true); api.setBufferTransparency(tx, l->sc, translucent ? ASC_TRANSPARENCY_TRANSLUCENT : ASC_TRANSPARENCY_OPAQUE); apply_geometry(tx, l, r); @@ -769,6 +853,7 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d pthread_mutex_lock(&g_lock); s->busy = 1; pthread_mutex_unlock(&g_lock); + apply_present_time(tx, l == &g_layers[SC_LAYER_GAME]); api.txApply(tx); api.txDelete(tx); l->cur_slot = idx; @@ -799,11 +884,12 @@ unsigned sc_layer_drops_take(void) { } int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, void *token, int scene_w, int scene_h, + const struct vkp_draw *draw, const struct droiddeck_color *color, uint32_t ahb_format) { struct layer *l = layer_of(SC_LAYER_GAME); int r[8]; if (!ahb || !token || ensure_sc(l) != 0) goto unavailable; - int g = layer_geometry(w, h, scene_w, scene_h, r); + int g = layer_geometry(w, h, scene_w, scene_h, draw, r); if (g < 0) goto unavailable; if (g == 0) { if (acquire_fd >= 0) close(acquire_fd); sc_layer_hide(); return 1; } if (token == l->cur_token && l->shown && !l->recreate_pending) { @@ -821,6 +907,7 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi ASurfaceControl *old = swap_sc_begin(l); if (old) api.setZOrder(tx, l->sc, l->z); api.setBuffer(tx, l->sc, ahb, acquire_fd); + if (api.setEnableBackPressure) api.setEnableBackPressure(tx, l->sc, true); api.setBufferTransparency(tx, l->sc, ASC_TRANSPARENCY_OPAQUE); apply_geometry(tx, l, r); apply_frame_rate(tx, l); @@ -834,6 +921,7 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi l->ds_applied = -1; l->md_applied = 0; l->hr_applied = -1.0f; return -1; } + apply_present_time(tx, 1); api.txApply(tx); api.txDelete(tx); l->cur_slot = -1; @@ -848,18 +936,19 @@ unavailable: return -1; } -int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct droiddeck_color *color) { +int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw, + const struct droiddeck_color *color) { struct layer *l = layer_of(SC_LAYER_GAME); if (!src || ensure_sc(l) != 0) return -1; int sw = vkp_image_width(src), sh = vkp_image_height(src); int r[8]; - int g = layer_geometry(sw, sh, scene_w, scene_h, r); + int g = layer_geometry(sw, sh, scene_w, scene_h, draw, r); if (g < 0) return -1; if (g == 0) { sc_layer_hide(); return 0; } int wait_fd; int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd); - if (idx < 0) { log_drop(l); return 0; } + if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; } if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1; if (present_slot(l, idx, r, color, 0) != 0) return -1; if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8); @@ -879,10 +968,10 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int if (!draws || n <= 0 || ensure_sc(l) != 0) return -1; if (vkp_update_map(scene_w, scene_h) != 0) return -1; if (vkp_pass_begin(scene_w, scene_h, draws, n, &rw, &rh) != 0) return -1; - if (!vkp_map_rect(rw, rh, scene_w, scene_h, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } + if (!vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } int wait_fd; int idx = take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd); - if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; } + if (idx < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1; if (present_slot(l, idx, r, NULL, 0) != 0) return -1; if (!l->first_logged) { @@ -895,8 +984,97 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int return 0; } +static void slots_idle(struct layer *l, const int *idx, int from, int to) { + pthread_mutex_lock(&g_lock); + for (int i = from; i < to; i++) l->slots[idx[i]].busy = 0; + pthread_mutex_unlock(&g_lock); +} + static uint32_t g_hdr_pool_fmt = AHB_RGB10A2; +static int take_hdr_slot(struct layer *l, int w, int h, int *wait_fd) { + int idx = take_free_slot(l, w, h, g_hdr_pool_fmt, wait_fd); + if (idx < 0 && g_alloc_failed && g_hdr_pool_fmt == AHB_RGB10A2) { + g_hdr_pool_fmt = AHB_RGBA8; + droiddeck_log("color", "%s: this device will not make a 10-bit layer buffer (RGBA1010102): the HDR picture goes " + "on 8-bit buffers instead (still tagged BT2020_PQ; less precision)", l->name); + idx = take_free_slot(l, w, h, g_hdr_pool_fmt, wait_fd); + } + return idx; +} + +int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf, + int scene_w, int scene_h, int composed, const struct droiddeck_color *color) { + struct layer *l = layer_of(SC_LAYER_GAME); + int rw = 0, rh = 0, r[8], idx[VKP_FG_MAX_GENERATIONS + 1], m = 0, first_fd = -1, have_fd = 0; + struct vkp_image *dst[VKP_FG_MAX_GENERATIONS], *real = NULL; + g_group_index = 0; + g_group_frames = 1; + if (!draws || n_draws <= 0 || ensure_sc(l) != 0) return -1; + if (vkp_update_map(scene_w, scene_h) != 0) return -1; + const int deep = hf && !hf->tonemap; + if (hf) composed = 1; + if (hf && hf->tonemap) color = NULL; + int n = vkp_pass_begin_generate(scene_w, scene_h, draws, n_draws, hf, &rw, &rh); + if (n < 0) return -1; + const int mapped = vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r); + if (!mapped) n = 0; + if (composed) { + if (!mapped) { vkp_pass_abort(); sc_layer_hide(); return 0; } + idx[VKP_FG_MAX_GENERATIONS] = deep ? take_hdr_slot(l, rw, rh, &first_fd) + : take_free_slot(l, rw, rh, AHB_RGBA8, &first_fd); + if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } + pthread_mutex_lock(&g_lock); + l->slots[idx[VKP_FG_MAX_GENERATIONS]].busy = 1; + pthread_mutex_unlock(&g_lock); + real = l->slots[idx[VKP_FG_MAX_GENERATIONS]].img; + have_fd = 1; + } + for (; m < n; m++) { + int fd; + idx[m] = take_free_slot(l, rw, rh, deep ? g_hdr_pool_fmt : AHB_RGBA8, &fd); + if (idx[m] < 0) { log_drop(l); break; } + if (have_fd && fd >= 0) { + if (fence_wait(fd, 100) == 0) { slot_keep_fence(&l->slots[idx[m]], fd); log_drop(l); break; } + close(fd); + } + pthread_mutex_lock(&g_lock); + l->slots[idx[m]].busy = 1; + pthread_mutex_unlock(&g_lock); + dst[m] = l->slots[idx[m]].img; + if (!have_fd) { first_fd = fd; have_fd = 1; } + } + if (vkp_pass_copy_generated(dst, m, real, first_fd) != 0) { + slots_idle(l, idx, 0, m); + if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); + return -1; + } + g_group_frames = m + 1; + for (int k = 0; k < m; k++) { + if (present_slot(l, idx[k], r, color, 0) == 0) continue; + slots_idle(l, idx, k, m); + if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); + g_group_index = 0; + g_group_frames = 1; + return -1; + } + vkp_framegen_presented(m); + if (real) { + if (present_slot(l, idx[VKP_FG_MAX_GENERATIONS], r, color, 0) != 0) { + slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); + g_group_index = 0; + g_group_frames = 1; + return -1; + } + l->first_logged = 1; + vkp_signal_first_frame(); + } + if (hf && hf->color && hf->color->dataspace) + droiddeck_color_frame_shown(hf->color, deep ? DROIDDECK_HDR_COMPOSED : DROIDDECK_HDR_TONEMAPPED, + deep ? g_hdr_pool_fmt : AHB_RGBA8); + return m; +} + int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int scene_w, int scene_h, const struct droiddeck_color *color) { struct layer *l = layer_of(SC_LAYER_GAME); @@ -904,19 +1082,11 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct if (!draws || n <= 0 || !hf || ensure_sc(l) != 0) return -1; if (vkp_update_map(scene_w, scene_h) != 0) return -1; if (vkp_pass_begin_hdr(scene_w, scene_h, draws, n, hf, &rw, &rh) != 0) return -1; - if (!vkp_map_rect(rw, rh, scene_w, scene_h, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } + if (!vkp_map_rect(rw, rh, (const int[4]){0, 0, scene_w, scene_h}, r)) { vkp_pass_abort(); sc_layer_hide(); return 0; } const int tm = hf->tonemap; - const uint32_t fmt = tm ? AHB_RGBA8 : g_hdr_pool_fmt; - g_alloc_failed = 0; int wait_fd; - int idx = take_free_slot(l, rw, rh, fmt, &wait_fd); - if (idx < 0 && g_alloc_failed && fmt == AHB_RGB10A2) { - g_hdr_pool_fmt = AHB_RGBA8; - droiddeck_log("color", "%s: this device will not make a 10-bit layer buffer (RGBA1010102): the HDR picture goes " - "on 8-bit buffers instead (still tagged BT2020_PQ; less precision)", l->name); - idx = take_free_slot(l, rw, rh, g_hdr_pool_fmt, &wait_fd); - } - if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; } + int idx = tm ? take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd) : take_hdr_slot(l, rw, rh, &wait_fd); + if (idx < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1; if (present_slot(l, idx, r, tm ? NULL : color, 0) != 0) return -1; if (color && color->dataspace) @@ -967,8 +1137,9 @@ int sc_layer_overlay_affordable(void) { if (want) droiddeck_log("layer", "overlay layer declined: this display rotates every layer %d° and the game " "layer is scaled %dx%d -> %dx%d, and on that combination a second layer drops the " - "whole frame to GPU composition for the rest of the session (measured). The window " - "above the game goes on the copy path instead - same picture, one blit.", + "whole frame to GPU composition for the rest of the session (measured). A nested " + "compositor is asked to compose its own overlays into the game picture; any other " + "window above the game goes on the copy path instead.", deg, sr[0], sr[1], ds[0], ds[1]); else if (!first) droiddeck_log("layer", "overlay layer allowed again: the game layer is no longer both rotated and " @@ -986,7 +1157,7 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl if (sw <= 0 || sh <= 0) return -1; int wait_fd; int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd); - if (idx < 0) { log_drop(l); return 0; } + if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; } if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1; if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1; if (!l->first_logged) { @@ -1033,6 +1204,13 @@ void sc_layer_window_gone(void) { drain_and_free_pools(); } +void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even) { + *next = g_stat_aimed_next; + *later = g_stat_aimed_later; + *even = g_stat_aimed_even; + g_stat_aimed_next = g_stat_aimed_later = g_stat_aimed_even = 0; +} + unsigned sc_layer_frames_take(void) { unsigned n = g_stat_layer_frames; g_stat_layer_frames = 0; diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.h b/app/src/main/cpp/waylandcomp/src/sc_layer.h index 58fe5f6d61..24a24fc25e 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.h +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.h @@ -7,10 +7,13 @@ struct vkp_image; struct vkp_draw; struct droiddeck_color; +struct vkp_hdr_frame; enum sc_layer_id { SC_LAYER_GAME = 0, SC_LAYER_OVERLAY = 1, SC_LAYER_COUNT = 2 }; int sc_layer_available(void); +#define SC_LAYER_AHB_USAGE_VENDOR_UBWC (1ULL << 28) +int sc_layer_ahb_fd(AHardwareBuffer *ahb, uint64_t need); void sc_layer_probe_dmabuf_fd(int fd); @@ -18,21 +21,25 @@ int sc_layer_can_tag_hdr(void); void sc_layer_hdr_symbols(char *out, size_t size); -int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct droiddeck_color *color); +int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw, + const struct droiddeck_color *color); int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int scene_h); +int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf, + int scene_w, int scene_h, int composed, const struct droiddeck_color *color); -struct vkp_hdr_frame; int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int scene_w, int scene_h, const struct droiddeck_color *color); int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, void *token, - int scene_w, int scene_h, const struct droiddeck_color *color, uint32_t ahb_format); + int scene_w, int scene_h, const struct vkp_draw *draw, const struct droiddeck_color *color, uint32_t ahb_format); void sc_layer_set_frame_rate(float fps); int sc_layer_overlay_affordable(void); +int sc_layer_queues(void); + int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent); void sc_layer_hide(void); @@ -42,6 +49,8 @@ void sc_layer_hide_overlay(void); void sc_layer_window_gone(void); +void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns); +void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even); unsigned sc_layer_frames_take(void); unsigned sc_layer_drops_take(void); diff --git a/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h b/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h new file mode 100644 index 0000000000..a820026930 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/vk_linear_dmabuf.h @@ -0,0 +1,61 @@ +#ifndef VK_LINEAR_DMABUF_H +#define VK_LINEAR_DMABUF_H + +#include +#include + +static inline int vkp_linear_dmabuf_through_buffer(int drm_modifiers, uint64_t modifier, int blit_dst) { + return !drm_modifiers && modifier == 0 && !blit_dst; +} + +static inline int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) { + return dmabuf && !staged; +} + +static inline VkPipelineStageFlags vkp_linear_dmabuf_readback_stage(int in_general) { + return in_general ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; +} + +static inline VkAccessFlags vkp_linear_dmabuf_readback_access(int in_general) { + return in_general ? VK_ACCESS_TRANSFER_WRITE_BIT : 0; +} + +static inline uint32_t vkp_linear_dmabuf_texel_bytes(VkFormat fmt) { + return fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? 8u : 4u; +} + +static inline int vkp_padded_linear_target_needs_layout(int drm_modifiers, uint64_t modifier, VkFormat fmt, + int w, uint32_t stride, uint32_t offset) { + return !drm_modifiers && modifier == 0 && + (offset != 0 || (uint64_t)stride != (uint64_t)w * vkp_linear_dmabuf_texel_bytes(fmt)); +} + +static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, uint32_t stride, uint32_t offset, + VkBufferImageCopy *copy) { + const uint32_t texel = vkp_linear_dmabuf_texel_bytes(fmt); + if (!copy || w <= 0 || h <= 0 || stride % texel || offset % texel || stride / texel < (uint32_t)w) return 0; + *copy = (VkBufferImageCopy){ + .bufferOffset = offset, + .bufferRowLength = stride / texel, + .bufferImageHeight = (uint32_t)h, + .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .imageExtent = {(uint32_t)w, (uint32_t)h, 1}, + }; + return (VkDeviceSize)offset + (VkDeviceSize)stride * (VkDeviceSize)(h - 1) + (VkDeviceSize)w * texel; +} + +static inline VkBufferMemoryBarrier vkp_linear_dmabuf_ownership(VkBuffer buffer, uint32_t queue_family, + VkAccessFlags access, int acquire) { + return (VkBufferMemoryBarrier){ + .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + .srcAccessMask = acquire ? 0 : access, + .dstAccessMask = acquire ? access : 0, + .srcQueueFamilyIndex = acquire ? VK_QUEUE_FAMILY_FOREIGN_EXT : queue_family, + .dstQueueFamilyIndex = acquire ? queue_family : VK_QUEUE_FAMILY_FOREIGN_EXT, + .buffer = buffer, + .offset = 0, + .size = VK_WHOLE_SIZE, + }; +} + +#endif diff --git a/app/src/main/cpp/waylandcomp/src/vk_loader.h b/app/src/main/cpp/waylandcomp/src/vk_loader.h index 2742a1b82a..c0782140f0 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_loader.h +++ b/app/src/main/cpp/waylandcomp/src/vk_loader.h @@ -22,7 +22,9 @@ X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \ X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \ X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \ - X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \ + X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) X(CmdCopyImageToBuffer) \ + X(CreateBuffer) X(DestroyBuffer) X(GetBufferMemoryRequirements) X(BindBufferMemory) \ + X(CmdCopyBufferToImage) \ \ X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \ X(CreateGraphicsPipelines) X(DestroyPipeline) X(CreateRenderPass) X(DestroyRenderPass) \ diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 53ddadaeb0..61b2765c5b 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -2,6 +2,7 @@ #include "vk_present.h" #include "vk_loader.h" #include "vk_external_image_sync.h" +#include "vk_linear_dmabuf.h" #include "sc_layer.h" #include "effects_chain.h" #include "cardboard.h" @@ -42,10 +43,15 @@ struct vkp_image { VkFormat fmt; int sampled; AHardwareBuffer *android_buffer; + int staged; + VkBuffer linear_buf; + VkDeviceMemory linear_mem; + VkBufferImageCopy linear_copy; }; static ANativeWindow *g_window; static int g_ahb_import; +static int g_drm_modifiers; static char *g_driver_path, *g_library_name, *g_native_lib_dir; static int g_allow_driver_fallback; static int g_dev_state; @@ -628,6 +634,7 @@ static int dev_init(void) { if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i]; else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]); } + g_drm_modifiers = has_ext(exts, ne, "VK_EXT_image_drm_format_modifier"); int want_hdr_md = 0; if (droiddeck_color_requested()) { want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME); @@ -1088,6 +1095,10 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0); } +static int foreign_image(const struct vkp_image *img) { + return vkp_linear_dmabuf_foreign_image(img->dmabuf, img->staged); +} + /* Return client sources to FOREIGN after their final read. The consuming paths * wait for our fence before Wayland can release an ordinary dma-buf or an * android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from @@ -1095,7 +1106,7 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) { struct vkp_external_client_barrier_pair pair; if (!img || !vkp_external_client_barrier_pair( - img->image, g_qfam, img->dmabuf, img->blit_dst, &pair)) + img->image, g_qfam, foreign_image(img), img->blit_dst, &pair)) return; g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release); @@ -1109,6 +1120,37 @@ static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_ } } +static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img) { + if (!img || !img->linear_buf) return; + const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 1); + VkImageMemoryBarrier write = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = img->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, + 0, NULL, 1, &acquire, 1, &write); + g_vk.CmdCopyBufferToImage(cmd, img->linear_buf, img->image, VK_IMAGE_LAYOUT_GENERAL, 1, &img->linear_copy); + VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 0); + VkImageMemoryBarrier read = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = img->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, + 0, NULL, 1, &release, 1, &read); +} + +static void stage_linear_dmabufs(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) { + for (int i = 0; i < count; i++) { + int seen = 0; + for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; } + if (!seen) stage_linear_dmabuf(cmd, draws[i].img); + } +} + int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst); } @@ -1181,18 +1223,122 @@ fail: return NULL; } +static int optimal_sampled(VkFormat fmt) { + if (!g_vk.GetPhysicalDeviceFormatProperties2) return 0; + VkFormatProperties2 fp = {.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2}; + g_vk.GetPhysicalDeviceFormatProperties2(g_pd, fmt, &fp); + const VkFormatFeatureFlags need = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | + VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; + return (fp.formatProperties.optimalTilingFeatures & need) == need; +} + +static void destroy_image_objects(struct vkp_image *img) { + if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL); + if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL); + if (img->linear_buf) g_vk.DestroyBuffer(g_dev, img->linear_buf, NULL); + if (img->linear_mem) g_vk.FreeMemory(g_dev, img->linear_mem, NULL); + img->image = VK_NULL_HANDLE; img->mem = VK_NULL_HANDLE; + img->linear_buf = VK_NULL_HANDLE; img->linear_mem = VK_NULL_HANDLE; + img->staged = 0; img->in_general = 0; +} + +static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferImageCopy *copy, VkDeviceSize need) { + int dupfd = dup(fd); + if (dupfd < 0) return -1; + VkDeviceSize size = need; + off_t end = lseek(dupfd, 0, SEEK_END); + if (end > 0 && (VkDeviceSize)end >= need) size = (VkDeviceSize)end; + lseek(dupfd, 0, SEEK_SET); + if (end > 0 && (VkDeviceSize)end < need) { + LOGE("dmabuf: the linear %dx%d buffer holds %lld bytes, its row pitch needs %llu", img->w, img->h, + (long long)end, (unsigned long long)need); + close(dupfd); + return -1; + } + VkExternalMemoryBufferCreateInfo ext = { + .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO, + .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT}; + VkBufferCreateInfo bci = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = &ext, .size = size, + .usage = img->blit_dst ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE}; + VkResult r = g_vk.CreateBuffer(g_dev, &bci, NULL, &img->linear_buf); + if (r != VK_SUCCESS) goto fail; + uint32_t allowed = 0xffffffff; + if (g_vk.GetMemoryFdPropertiesKHR) { + VkMemoryFdPropertiesKHR fp = {.sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR}; + if (g_vk.GetMemoryFdPropertiesKHR(g_dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, + dupfd, &fp) == VK_SUCCESS) + allowed = fp.memoryTypeBits; + } + VkMemoryRequirements breq; + g_vk.GetBufferMemoryRequirements(g_dev, img->linear_buf, &breq); + int bidx = memory_type(breq.memoryTypeBits & allowed, 0); + r = VK_ERROR_FORMAT_NOT_SUPPORTED; + if (bidx < 0) goto fail; + VkImportMemoryFdInfoKHR imp = {.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, + .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, .fd = dupfd}; + VkMemoryDedicatedAllocateInfo ded = {.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, + .pNext = &imp, .buffer = img->linear_buf}; + VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &ded, + .allocationSize = breq.size, .memoryTypeIndex = (uint32_t)bidx}; + r = g_vk.AllocateMemory(g_dev, &mai, NULL, &img->linear_mem); + if (r != VK_SUCCESS) goto fail; + dupfd = -1; + r = g_vk.BindBufferMemory(g_dev, img->linear_buf, img->linear_mem, 0); + if (r != VK_SUCCESS) goto fail; + + VkImageCreateInfo ici = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = img->fmt, + .extent = {(uint32_t)img->w, (uint32_t)img->h, 1}, .mipLevels = 1, .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | + (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0), + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED}; + r = g_vk.CreateImage(g_dev, &ici, NULL, &img->image); + if (r != VK_SUCCESS) goto fail; + VkMemoryRequirements ireq; + g_vk.GetImageMemoryRequirements(g_dev, img->image, &ireq); + int iidx = memory_type(ireq.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + if (iidx < 0) iidx = memory_type(ireq.memoryTypeBits, 0); + r = VK_ERROR_FORMAT_NOT_SUPPORTED; + if (iidx < 0) goto fail; + VkMemoryAllocateInfo iai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = ireq.size, .memoryTypeIndex = (uint32_t)iidx}; + r = g_vk.AllocateMemory(g_dev, &iai, NULL, &img->mem); + if (r != VK_SUCCESS) goto fail; + r = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0); + if (r != VK_SUCCESS) goto fail; + img->linear_copy = *copy; + img->staged = 1; + img->in_general = 1; + return 0; +fail: + LOGE("dmabuf: %s the linear %dx%d buffer at its row pitch failed (%s)", + img->blit_dst ? "writing" : "reading", img->w, img->h, vk_result_name(r)); + if (dupfd >= 0) close(dupfd); + destroy_image_objects(img); + return -1; +} + struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h, uint32_t stride, uint32_t offset, int as_blit_dst) { if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL; if (dev_init() != 0) return NULL; + const VkFormat format = drm_to_vk(drm_format); + const int padded_target = as_blit_dst && + vkp_padded_linear_target_needs_layout(g_drm_modifiers, modifier, format, w, stride, offset); + if (padded_target && !g_vk.CmdCopyImageToBuffer) return NULL; + struct vkp_image *img = calloc(1, sizeof(*img)); if (!img) return NULL; img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0; - img->fmt = drm_to_vk(drm_format); + img->fmt = format; + const int through_buffer = padded_target || vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst); const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; - img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 && - modifier_importable(img->fmt, modifier, sampled_usage); + const int modifier_sampled = !as_blit_dst && g_drm_modifiers && g_vk.GetPhysicalDeviceImageFormatProperties2 && + modifier_importable(img->fmt, modifier, sampled_usage); + img->sampled = !as_blit_dst && (through_buffer ? optimal_sampled(img->fmt) : modifier_sampled); /* Each new format/modifier/size a client hands over, once, for the graphics report: a colour * or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */ { @@ -1203,10 +1349,11 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t if (seen[i].fmt == drm_format && seen[i].mod == modifier && seen[i].w == w && seen[i].h == h) known = 1; if (!known && nseen < 32) { seen[nseen].fmt = drm_format; seen[nseen].mod = modifier; seen[nseen].w = w; seen[nseen].h = h; nseen++; - droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s", + droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s%s", drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff, (drm_format >> 24) & 0xff, vkp_modifier_name(modifier), w, h, stride, offset, (int)img->fmt, - img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : ""); + img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : "", + through_buffer ? ", trying a copy at its row pitch (no VK_EXT_image_drm_format_modifier)" : ""); } } @@ -1214,6 +1361,17 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t * vkCreateImage, which left the whole window unshown (David Cimo). One packed, 64-byte aligned * row is what a linear buffer that small holds. */ if (stride == 0 && modifier == 0) stride = ((uint32_t)w * 4 + 63) & ~63u; + if (through_buffer) { + VkBufferImageCopy linear_copy; + const VkDeviceSize linear_size = vkp_linear_dmabuf_copy(img->fmt, w, h, stride, offset, &linear_copy); + if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) { + if (padded_target) droiddeck_log("gpu", "linear layer target %dx%d writes at pitch %u via DMA-BUF", + w, h, stride); + return img; + } + if (padded_target) { free(img); return NULL; } + img->sampled = modifier_sampled; + } VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride}; VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = { .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT, @@ -1336,7 +1494,7 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) { } int vkp_can_import_ahb(void) { - return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && g_ahb_import && + return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && !g_library_name && g_ahb_import && g_vk.GetAndroidHardwareBufferPropertiesANDROID; } @@ -1501,8 +1659,7 @@ void vkp_image_destroy(struct vkp_image *img) { if (g_dev) { blendp_forget_image(img->image); if (img->map) g_vk.UnmapMemory(g_dev, img->mem); - if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL); - if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL); + destroy_image_objects(img); } if (img->android_buffer) AHardwareBuffer_release(img->android_buffer); free(img); @@ -1600,7 +1757,7 @@ static void effects_source_note(int scene_w, int scene_h, const struct vkp_draw static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target, VkFormat target_fmt, int target_w, int target_h, VkFilter filter) { const struct vkp_image *im = d->img; - const int external_client = vkp_image_is_dmabuf(im); + const int external_client = vkp_is_external_client_image(foreign_image(im), im->blit_dst); if (d->blend && im->sampled && blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !external_client, target, target_fmt, target_w, target_h, @@ -1734,6 +1891,11 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n, struct hdrc_params p = {.mode = mode, .sdr_white_nits = droiddeck_color_sdr_white(), .peak_nits = hf->peak_nits > 0.0f ? hf->peak_nits : 1000.0f}; + if (hf->convert) { + p.conv_linear = hf->convert->convert == 2; + p.conv_gain = hf->convert->gain; + memcpy(p.conv, hf->convert->to2020, sizeof(p.conv)); + } int lowest_hdr = -1; for (int i = 0; i < n; i++) { VkImageBlit blit; @@ -1750,6 +1912,7 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n, p.rects[p.count][0] = (float)blit.dstOffsets[0].x; p.rects[p.count][1] = (float)blit.dstOffsets[0].y; p.rects[p.count][2] = (float)blit.dstOffsets[1].x; p.rects[p.count][3] = (float)blit.dstOffsets[1].y; if (hf->is_hdr[i]) p.hdr_mask |= 1u << p.count; + if (hf->is_hdr[i] == 2 && hf->convert) p.conv_mask |= 1u << p.count; p.count++; } if (i >= lowest_hdr && !truncated_said) { @@ -2084,6 +2247,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(cmd, &bi); blendp_begin_frame(); + stage_linear_dmabufs(cmd, draws, n); VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; VkImageMemoryBarrier *bars = calloc((size_t)n + 1, sizeof(*bars)); @@ -2101,7 +2265,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i if (seen || !im) continue; struct vkp_external_client_barrier_pair pair; if (vkp_external_client_barrier_pair( - im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) { + im->image, g_qfam, foreign_image(im), im->blit_dst, &pair)) { bars[nb++] = pair.acquire; } else if (!im->blit_dst && !im->in_general) { bars[nb++] = (VkImageMemoryBarrier){ @@ -2353,9 +2517,9 @@ int vkp_update_map(int scene_w, int scene_h) { return g_map.valid ? 0 : -1; } -int vkp_map_rect(int img_w, int img_h, int scene_w, int scene_h, int out[8]) { +int vkp_map_rect(int img_w, int img_h, const int dst[4], int out[8]) { struct vkp_image tmp = {.w = img_w, .h = img_h}; - struct vkp_draw d = {&tmp, 0, 0, (float)img_w, (float)img_h, 0, 0, scene_w, scene_h}; + struct vkp_draw d = {&tmp, 0, 0, (float)img_w, (float)img_h, dst[0], dst[1], dst[2], dst[3]}; return vkp_map_draw(&d, out); } @@ -2369,6 +2533,48 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) { return 1; } +static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_layout, struct vkp_image *dst, + const VkImageBlit *blit, VkFilter filter) { + const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + const VkImageMemoryBarrier acquire = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .srcQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : VK_QUEUE_FAMILY_FOREIGN_EXT, + .dstQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : g_qfam, + .image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 0, NULL, 1, &acquire); + g_vk.CmdBlitImage(cmd, src, src_layout, dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter); + if (dst->staged) { + const VkImageMemoryBarrier read = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = dst->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 0, NULL, 1, &read); + const VkBufferMemoryBarrier write = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 1); + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 1, &write, 0, NULL); + VkBufferImageCopy copy = dst->linear_copy; + copy.imageExtent.width = (uint32_t)blit->dstOffsets[1].x; + copy.imageExtent.height = (uint32_t)blit->dstOffsets[1].y; + g_vk.CmdCopyImageToBuffer(cmd, dst->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst->linear_buf, 1, ©); + const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 0); + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, 0, NULL, 1, &release, 0, NULL); + return; + } + const VkImageMemoryBarrier release = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range, + .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, 0, NULL, 0, NULL, 1, &release); +} + int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) { if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) { if (wait_fd >= 0) close(wait_fd); @@ -2383,44 +2589,32 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) { VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(g_cmd, &bi); + stage_linear_dmabuf(g_cmd, src); struct vkp_external_client_barrier_pair src_pair; const int src_external = vkp_external_client_barrier_pair( - src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair); - VkImageMemoryBarrier acq[2] = { - src_external ? src_pair.acquire : (VkImageMemoryBarrier){ + src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair); + VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}, - {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam, - .image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}}; + .image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}; if (!src_external) { - acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED; - acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL; - acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED; + acq.newLayout = VK_IMAGE_LAYOUT_GENERAL; + acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; src->in_general = 1; } g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 2, acq); + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq); int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h; VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .srcOffsets = {{0, 0, 0}, {bw, bh, 1}}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .dstOffsets = {{0, 0, 0}, {bw, bh, 1}}}; - g_vk.CmdBlitImage(g_cmd, src->image, - src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, - dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST); + blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, + dst, &blit, VK_FILTER_NEAREST); release_external_client_image(g_cmd, src); - VkImageMemoryBarrier rel = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range, - .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; - g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, NULL, 0, NULL, 1, &rel); g_vk.EndCommandBuffer(g_cmd); VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; @@ -2489,22 +2683,26 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) { VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(cmd, &bi); + stage_linear_dmabuf(cmd, src); struct vkp_external_client_barrier_pair src_pair; const int src_external = vkp_external_client_barrier_pair( - src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair); + src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair); VkImageMemoryBarrier acq[2] = { src_external ? src_pair.acquire : (VkImageMemoryBarrier){ - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED, .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}, + .image = src->image, .subresourceRange = range, + .srcAccessMask = vkp_linear_dmabuf_readback_access(src->in_general), + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}, {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}}; - g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, 0, NULL, 0, NULL, 2, acq); + g_vk.CmdPipelineBarrier(cmd, vkp_linear_dmabuf_readback_stage(src->in_general), + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 2, acq); VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .srcOffsets = {{0, 0, 0}, {src->w, src->h, 1}}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, @@ -2551,24 +2749,33 @@ static struct { int active; VkImage result; int rw, rh; + int ngen; + VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n, - const struct vkp_hdr_frame *hf, int *rw, int *rh); + const struct vkp_hdr_frame *hf, int generate, int *rw, int *rh); int vkp_pass_begin(int scene_w, int scene_h, const struct vkp_draw *draws, int n, int *rw, int *rh) { - return pass_begin_impl(scene_w, scene_h, draws, n, NULL, rw, rh); + return pass_begin_impl(scene_w, scene_h, draws, n, NULL, 0, rw, rh); +} + +int vkp_pass_begin_generate(int scene_w, int scene_h, const struct vkp_draw *draws, int n, + const struct vkp_hdr_frame *hf, int *rw, int *rh) { + if (pass_begin_impl(scene_w, scene_h, draws, n, hf, 1, rw, rh) != 0) return -1; + return g_pass.ngen; } int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int *rw, int *rh) { if (!hf) return -1; - return pass_begin_impl(scene_w, scene_h, draws, n, hf, rw, rh); + return pass_begin_impl(scene_w, scene_h, draws, n, hf, 0, rw, rh); } static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n, - const struct vkp_hdr_frame *hf, int *rw, int *rh) { + const struct vkp_hdr_frame *hf, int generate, int *rw, int *rh) { if (g_pass.active) vkp_pass_abort(); + g_pass.ngen = 0; if (vkp_update_map(scene_w, scene_h) != 0) return -1; int input_w = scene_w, input_h = scene_h; int pass_n = n, overlay_start = n; @@ -2588,13 +2795,31 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw effects_source_note(scene_w, scene_h, draws, n, input_w, input_h, (int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f)); } - if (hf) { + const int deep = hf && generate && !hf->tonemap && vkp_framegen_format_ok(FG_HDR_FMT) && + ensure_img(&g_fgscene, scene_w, scene_h, FG_HDR_FMT, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, + "HDR frame generation (scene)") == 0; + const int narrow = hf && generate && !deep; + if (hf && !deep && !narrow) { if (ensure_img(&g_hdrscene, scene_w, scene_h, HDR_FMT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, "HDR composition (picture)") != 0) return -1; - } else if (ensure_scene_image(input_w, input_h) != 0) return -1; + } else if (!deep && ensure_scene_image(input_w, input_h) != 0) return -1; + const VkFormat scene_fmt = deep ? FG_HDR_FMT : narrow || !hf ? SCENE_FMT : HDR_FMT; + if (hf && generate) { + static int said = -1; + if (said != deep + 2 * hf->tonemap) { + said = deep + 2 * hf->tonemap; + droiddeck_log("color", hf->tonemap + ? "frame generation runs on the tone-mapped picture in 8 bits, onto the game's display layer" + : deep ? "frame generation runs on the HDR picture in FP16 (RGBA16F), onto the game's display layer" + : "frame generation runs on the HDR picture in 8 bits (the engine cannot take FP16 here), onto " + "the game's display layer: banding possible in smooth gradients"); + } + } VkCommandBuffer cmd = g_cmds[0]; g_vk.ResetCommandBuffer(cmd, 0); @@ -2602,12 +2827,13 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; g_vk.BeginCommandBuffer(cmd, &bi); blendp_begin_frame(); + stage_linear_dmabufs(cmd, draws, n); VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; VkImageMemoryBarrier *bars = calloc((size_t)n + 1, sizeof(*bars)); if (!bars) { g_vk.EndCommandBuffer(cmd); return -1; } int nb = 0; - VkImage scene_img = hf ? g_hdrscene.img : g_scene.img; + VkImage scene_img = deep ? g_fgscene.img : narrow || !hf ? g_scene.img : g_hdrscene.img; bars[nb++] = (VkImageMemoryBarrier){ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, @@ -2620,7 +2846,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw if (seen || !im) continue; struct vkp_external_client_barrier_pair pair; if (vkp_external_client_barrier_pair( - im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) { + im->image, g_qfam, foreign_image(im), im->blit_dst, &pair)) { bars[nb++] = pair.acquire; } else if (!im->blit_dst && !im->in_general) { bars[nb++] = (VkImageMemoryBarrier){ @@ -2638,12 +2864,12 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw free(bars); if (hf) { - if (compose_hdr(cmd, draws, n, hf, scene_w, scene_h, g_hdrscene.img, HDR_FMT, + if (compose_hdr(cmd, draws, n, hf, scene_w, scene_h, scene_img, scene_fmt, hf->tonemap ? HDRC_OUT_SDR : HDRC_OUT_PQ) != 0) { g_vk.EndCommandBuffer(cmd); return -1; } - if (vkp_effects_active()) vkp_effects_set_formats(HDR_FMT, HDR_FMT); + if (vkp_effects_active()) vkp_effects_set_formats(scene_fmt, scene_fmt); } else { VkClearColorValue black = {.float32 = {0.0f, 0.0f, 0.0f, 1.0f}}; g_vk.CmdClearColorImage(cmd, g_scene.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, &range); @@ -2662,53 +2888,57 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw } int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f); + if (generate && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; } g_pass.rw = input_w; g_pass.rh = input_h; g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &g_pass.rw, &g_pass.rh); effects_overlay_draws(cmd, g_pass.result, g_pass.rw, g_pass.rh, scene_w, scene_h, draws ? draws + overlay_start : NULL, n - overlay_start); release_external_client_draws(cmd, draws, n); + if (generate) { + VkImageMemoryBarrier b = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = g_pass.result, .subresourceRange = range, + .srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT}; + g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, 0, NULL, 0, NULL, 1, &b); + int ngen = vkp_framegen_run(cmd, g_pass.result, VK_NULL_HANDLE, g_pass.rw, g_pass.rh, scene_fmt, g_pass.gens); + if (ngen < 0) ngen = 0; + g_pass.ngen = ngen > VKP_FG_MAX_GENERATIONS ? VKP_FG_MAX_GENERATIONS : ngen; + } g_pass.active = 1; if (rw) *rw = g_pass.rw; if (rh) *rh = g_pass.rh; return 0; } -int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { +static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp_image *const *dsts, int n, + int wait_fd) { if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; } g_pass.active = 0; if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; } VkCommandBuffer cmd = g_cmds[0]; - if (!dst || !dst->blit_dst) { + for (int i = 0; i < n; i++) { + if (dsts[i] && dsts[i]->blit_dst) continue; if (wait_fd >= 0) close(wait_fd); g_vk.EndCommandBuffer(cmd); return -1; } const int gpu_wait = take_wait_fd(wait_fd); if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; } - VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - - VkImageMemoryBarrier acq = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, - .dstQueueFamilyIndex = g_qfam, .image = dst->image, .subresourceRange = range, - .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; - g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, 0, NULL, 0, NULL, 1, &acq); - VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}}, - .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}}; - g_vk.CmdBlitImage(cmd, g_pass.result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst->image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, + for (int i = 0; i < n; i++) { + struct vkp_image *dst = dsts[i]; + VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}}; + blit_to_layer(cmd, srcs[i], src_layout, dst, &blit, (g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); - VkImageMemoryBarrier rel = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range, - .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}; - g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, NULL, 0, NULL, 1, &rel); + } g_vk.EndCommandBuffer(cmd); VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; @@ -2728,6 +2958,19 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { return 0; } +int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) { + return pass_finish(&g_pass.result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, &dst, 1, wait_fd); +} + +int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_image *real, int wait_fd) { + VkImage srcs[VKP_FG_MAX_GENERATIONS + 1]; + struct vkp_image *all[VKP_FG_MAX_GENERATIONS + 1]; + if (n > g_pass.ngen) n = g_pass.ngen; + for (int i = 0; i < n; i++) { srcs[i] = g_pass.gens[i]; all[i] = dsts[i]; } + if (real) { srcs[n] = g_pass.result; all[n] = real; } + return pass_finish(srcs, VK_IMAGE_LAYOUT_GENERAL, all, n + (real ? 1 : 0), wait_fd); +} + void vkp_pass_abort(void) { if (!g_pass.active) return; g_pass.active = 0; diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.h b/app/src/main/cpp/waylandcomp/src/vk_present.h index b8cd889219..69af7dca23 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.h +++ b/app/src/main/cpp/waylandcomp/src/vk_present.h @@ -96,6 +96,7 @@ struct vkp_hdr_frame { float peak_nits; int tonemap; const struct droiddeck_color *color; + const struct droiddeck_color *convert; }; int vkp_render_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf, int *how); @@ -106,7 +107,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd); int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px); int vkp_update_map(int scene_w, int scene_h); int vkp_map_draw(const struct vkp_draw *d, int out[8]); -int vkp_map_rect(int img_w, int img_h, int scene_w, int scene_h, int out[8]); +int vkp_map_rect(int img_w, int img_h, const int dst[4], int out[8]); int vkp_surface_rotation_degrees(void); ANativeWindow *vkp_window(void); @@ -114,6 +115,9 @@ void vkp_signal_first_frame(void); int vkp_pass_begin(int scene_w, int scene_h, const struct vkp_draw *draws, int n, int *rw, int *rh); int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd); +int vkp_pass_begin_generate(int scene_w, int scene_h, const struct vkp_draw *draws, int n, + const struct vkp_hdr_frame *hf, int *rw, int *rh); +int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_image *real, int wait_fd); void vkp_pass_abort(void); void droiddeck_log(const char *tag, const char *fmt, ...) __attribute__((format(printf, 2, 3))); diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 7879d51521..308332f9b1 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -34,11 +34,13 @@ extern int droiddeck_cursor_input_pos(int *x, int *y); extern void droiddeck_wayland_send_scene_input(int type, int a, int b); extern void droiddeck_wayland_set_cursor_composite(int on); extern void droiddeck_wayland_vsync(int64_t frame_time_ns); +extern void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns); extern void droiddeck_stream_set(int on); extern void droiddeck_stream_frame(AHardwareBuffer *ahb); extern unsigned droiddeck_stream_frames(void); extern void droiddeck_wayland_output_resized(void); extern void droiddeck_wayland_set_output_refresh_rate(int mhz); +extern void droiddeck_wayland_set_panel_rates(const int *rates, int count); extern volatile int g_fps_limit; extern volatile int g_release_unpaced; extern volatile int g_render_on_commit; @@ -48,6 +50,8 @@ extern volatile int g_hide_shell; extern volatile int g_zero_copy; extern volatile unsigned g_zero_copy_last; extern volatile int g_ubwc; +extern volatile int g_display_buffer_driver; +void droiddeck_dmabuf_formats_stale(void); extern volatile int g_no_render_node; extern volatile int g_output_w, g_output_h; @@ -59,10 +63,14 @@ static jclass g_compositor_cls; static jmethodID g_on_first_frame; static jmethodID g_on_game_surface; static jmethodID g_on_game_frame; +static jmethodID g_on_compositor_frame; static jmethodID g_on_game_program; static jmethodID g_on_pointer_lock; static jmethodID g_on_clipboard; static jmethodID g_on_text_input; +static jmethodID g_on_overlay_planes; +static jmethodID g_on_refresh_target; +static jmethodID g_on_content_rate; JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { (void)reserved; @@ -77,6 +85,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { g_on_game_surface = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameSurface", "(Ljava/lang/String;Ljava/lang/String;)V"); g_on_game_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameFrame", "()V"); + g_on_compositor_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onCompositorFrame", "()V"); g_on_game_program = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameProgram", "(ILjava/lang/String;)V"); if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; } @@ -84,6 +93,9 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { g_on_clipboard = (*env)->GetStaticMethodID(env, g_compositor_cls, "onClipboardText", "([B)V"); g_on_text_input = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInput", "(ZLjava/lang/String;IIII)V"); + g_on_overlay_planes = (*env)->GetStaticMethodID(env, g_compositor_cls, "onOverlayPlanes", "(I)V"); + g_on_refresh_target = (*env)->GetStaticMethodID(env, g_compositor_cls, "onRefreshTarget", "(II)V"); + g_on_content_rate = (*env)->GetStaticMethodID(env, g_compositor_cls, "onContentRate", "(I)V"); } } return JNI_VERSION_1_6; @@ -144,6 +156,34 @@ void droiddeck_on_game_frame(void) { if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); } +void droiddeck_on_compositor_frame(void) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_compositor_frame || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_compositor_frame); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + +void droiddeck_on_refresh_target(int refresh, int frame_rate) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_refresh_target, (jint)refresh, (jint)frame_rate); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + +void droiddeck_on_content_rate(int fps) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_content_rate || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_content_rate, (jint)fps); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + +void droiddeck_on_overlay_planes(int planes) { + JNIEnv *env; + if (!g_compositor_cls || !g_on_overlay_planes || !(env = thread_env())) return; + (*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_overlay_planes, (jint)planes); + if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env); +} + void droiddeck_on_pointer_lock(int locked, int x, int y) { JNIEnv *env; if (!g_compositor_cls || !g_on_pointer_lock || !(env = thread_env())) return; @@ -365,6 +405,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeVsync(JNIEnv *env, j droiddeck_wayland_vsync((int64_t)frameTimeNanos); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFrameTimeline(JNIEnv *env, jclass clazz, jlong presentNanos, + jlong deadlineNanos, jlong periodNanos) { + sc_layer_frame_timeline((int64_t)presentNanos, (int64_t)deadlineNanos, (int64_t)periodNanos); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetClockControl(JNIEnv *env, jclass clazz, jstring path) { const char *value = path ? (*env)->GetStringUTFChars(env, path, NULL) : NULL; @@ -380,11 +426,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHideShell(JNIEnv JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv *env, jclass clazz, jboolean on) { int live = droiddeck_get_display() != NULL; - if (!live) g_zero_copy = on ? 1 : 0; + if (!live) { g_zero_copy = on ? 1 : 0; droiddeck_dmabuf_formats_stale(); } droiddeck_host_zero_copy(on ? 1 : 0, live); __android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : ""); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) { + g_display_buffer_driver = on ? 1 : 0; + droiddeck_dmabuf_formats_stale(); + __android_log_print(ANDROID_LOG_INFO, TAG, "session driver %s for display buffers", on ? "asks" : "does not ask"); +} + JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeZeroCopyLastFrameAgeMs(JNIEnv *env, jclass clazz) { return (jint)ahb_swapchain_last_frame_age_ms(); @@ -418,6 +471,16 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetOutputRefreshRate droiddeck_wayland_set_output_refresh_rate(hz > 1.0f ? (int)(hz * 1000.0f + 0.5f) : 0); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetPanelRates(JNIEnv *env, jclass clazz, jintArray rates) { + (void)clazz; + jint values[16]; + jsize count = rates ? (*env)->GetArrayLength(env, rates) : 0; + if (count > 16) count = 16; + if (count > 0) (*env)->GetIntArrayRegion(env, rates, 0, count, values); + droiddeck_wayland_set_panel_rates((const int *)values, (int)count); +} + extern void vkp_reset_first_frame(void); JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeResetFirstFrame(JNIEnv *env, jclass clazz) { diff --git a/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c b/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c index 1ba254c4cd..a45d2691cf 100644 --- a/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c +++ b/app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c @@ -84,15 +84,18 @@ static struct { static _Atomic int g_gate = -1; static char g_gate_why[320]; static _Atomic int g_output_on = 1; +static _Atomic int g_output_wanted = 1; +static pthread_mutex_t g_output_mu = PTHREAD_MUTEX_INITIALIZER; void droiddeck_color_set_request(int mode, const char *source, int dxvk_hdr, int zero_copy_forced) { pthread_mutex_lock(&g_mu); - g_req.mode = mode < 0 ? 0 : mode > 2 ? 2 : mode; + g_req.mode = mode < 0 ? 0 : mode > 3 ? 3 : mode; snprintf(g_req.source, sizeof(g_req.source), "%s", source ? source : "environment"); g_req.dxvk_hdr = dxvk_hdr ? 1 : 0; g_req.zero_copy_forced = zero_copy_forced ? 1 : 0; pthread_mutex_unlock(&g_mu); atomic_store(&g_output_on, 1); + atomic_store(&g_output_wanted, 1); } void droiddeck_color_set_display(int id, const char *name, const char *formats, int hdr10, float max_lum, @@ -610,11 +613,23 @@ int droiddeck_color_tonemapped_on_screen(void) { void droiddeck_color_set_output(int on) { on = on ? 1 : 0; - if (atomic_load(&g_gate) != 1) { - droiddeck_log(TAG, "HDR output switch (%s) ignored: HDR is not open in this session", on ? "on" : "off"); + pthread_mutex_lock(&g_mu); + const int tonemap_only = g_req.mode == 3; + pthread_mutex_unlock(&g_mu); + pthread_mutex_lock(&g_output_mu); + atomic_store(&g_output_wanted, on); + const int gate = atomic_load(&g_gate); + const int changed = gate == 1 && !(on && tonemap_only) && atomic_exchange(&g_output_on, on) != on; + pthread_mutex_unlock(&g_output_mu); + if (gate != 1) { + if (gate == 0) droiddeck_log(TAG, "HDR output switch (%s) ignored: HDR is not open in this session", on ? "on" : "off"); return; } - if (atomic_exchange(&g_output_on, on) == on) return; + if (on && tonemap_only) { + droiddeck_log(TAG, "HDR output switch (on) ignored: this display cannot show HDR10, HDR frames stay tone-mapped"); + return; + } + if (!changed) return; char who[160]; int age = droiddeck_color_last_frame_age_ms(), tm = droiddeck_color_tonemapped_on_screen(); pthread_mutex_lock(&g_mu); @@ -658,6 +673,8 @@ static void desc_unref(struct cm_desc *d) { if (d && --d->refs <= 0) free(d); } struct cm_params { uint32_t tf, primaries; + int has_prim; int32_t prim[8]; + int has_lum; uint32_t lum_ref; int has_mprim; int32_t mprim[8]; int has_mlum; uint32_t mlum_min, mlum_max; int has_cll; uint32_t cll; @@ -730,9 +747,83 @@ static void make_output_description(struct wl_client *c, struct wl_resource *par droiddeck_client_name(c), what, col->text); } +static const float BT709_XY[8] = {0.64f, 0.33f, 0.30f, 0.60f, 0.15f, 0.06f, 0.3127f, 0.3290f}; +static const float BT2020_XY[8] = {0.708f, 0.292f, 0.170f, 0.797f, 0.131f, 0.046f, 0.3127f, 0.3290f}; + +static void mat_mul(const double a[9], const double b[9], double out[9]) { + double m[9]; + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + m[3 * i + j] = a[3 * i] * b[j] + a[3 * i + 1] * b[3 + j] + a[3 * i + 2] * b[6 + j]; + memcpy(out, m, sizeof(m)); +} + +static int mat_invert(const double m[9], double out[9]) { + const double det = m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + + m[2] * (m[3] * m[7] - m[4] * m[6]); + if (det > -1e-12 && det < 1e-12) return -1; + const double k = 1.0 / det; + double r[9] = {(m[4] * m[8] - m[5] * m[7]) * k, (m[2] * m[7] - m[1] * m[8]) * k, (m[1] * m[5] - m[2] * m[4]) * k, + (m[5] * m[6] - m[3] * m[8]) * k, (m[0] * m[8] - m[2] * m[6]) * k, (m[2] * m[3] - m[0] * m[5]) * k, + (m[3] * m[7] - m[4] * m[6]) * k, (m[1] * m[6] - m[0] * m[7]) * k, (m[0] * m[4] - m[1] * m[3]) * k}; + memcpy(out, r, sizeof(r)); + return 0; +} + +static int rgb_to_xyz(const float xy[8], double out[9], double white[3]) { + for (int i = 0; i < 4; i++) + if (xy[2 * i + 1] < 1e-4f) return -1; + double p[9], inv[9]; + for (int i = 0; i < 3; i++) { + const double x = xy[2 * i], y = xy[2 * i + 1]; + p[i] = x / y; p[3 + i] = 1.0; p[6 + i] = (1.0 - x - y) / y; + } + white[0] = xy[6] / xy[7]; white[1] = 1.0; white[2] = (1.0 - xy[6] - xy[7]) / xy[7]; + if (mat_invert(p, inv) != 0) return -1; + for (int i = 0; i < 3; i++) { + const double scale = inv[3 * i] * white[0] + inv[3 * i + 1] * white[1] + inv[3 * i + 2] * white[2]; + out[i] = p[i] * scale; out[3 + i] = p[3 + i] * scale; out[6 + i] = p[6 + i] * scale; + } + return 0; +} + +static int matrix_to_bt2020(const float xy[8], float out[9]) { + static const double bradford[9] = {0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296}; + double src[9], dst[9], dst_inv[9], sw[3], dw[3], cone_inv[9], adapt[9], m[9]; + if (rgb_to_xyz(xy, src, sw) != 0 || rgb_to_xyz(BT2020_XY, dst, dw) != 0) return -1; + if (mat_invert(dst, dst_inv) != 0 || mat_invert(bradford, cone_inv) != 0) return -1; + double scale[9] = {0}; + for (int i = 0; i < 3; i++) { + const double from = bradford[3 * i] * sw[0] + bradford[3 * i + 1] * sw[1] + bradford[3 * i + 2] * sw[2]; + const double to = bradford[3 * i] * dw[0] + bradford[3 * i + 1] * dw[1] + bradford[3 * i + 2] * dw[2]; + if (from > -1e-9 && from < 1e-9) return -1; + scale[4 * i] = to / from; + } + mat_mul(scale, bradford, adapt); + mat_mul(cone_inv, adapt, adapt); + mat_mul(adapt, src, m); + mat_mul(dst_inv, m, m); + for (int i = 0; i < 9; i++) out[i] = (float)m[i]; + return 0; +} + +static struct wl_resource *publish_description(struct wl_client *client, struct wl_resource *parent, uint32_t id, + struct cm_desc *d) { + struct wl_resource *out = wl_resource_create(client, &wp_image_description_v1_interface, + wl_resource_get_version(parent), id); + if (!out) { free(d); wl_client_post_no_memory(client); return NULL; } + d->refs = 1; + wl_resource_set_implementation(out, &image_description_impl, d, image_description_resource_destroy); + wp_image_description_v1_send_ready(out, d->c.identity); + pthread_mutex_lock(&g_mu); + g_hdr.descs++; + pthread_mutex_unlock(&g_mu); + return out; +} + static void params_create(struct wl_client *client, struct wl_resource *r, uint32_t id) { struct cm_params *p = wl_resource_get_user_data(r); - if (!p->tf || !p->primaries) { + if (!p->tf || (!p->primaries && !p->has_prim)) { wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INCOMPLETE_SET, "transfer function and primaries must both be set"); return; @@ -744,10 +835,29 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3 if (!g_next_identity) g_next_identity = 1; c->primaries = p->primaries; c->tf = p->tf; - if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && p->tf == WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ) + const float ref = p->has_lum ? (float)p->lum_ref : 203.0f; + float xy[8]; + for (int i = 0; i < 8; i++) + xy[i] = p->has_prim ? p->prim[i] / 1e6f + : p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_SRGB ? BT709_XY[i] : BT2020_XY[i]; + if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && ref == 203.0f) { c->dataspace = DROIDDECK_ADATASPACE_BT2020_PQ; - else if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && p->tf == WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_HLG) - c->dataspace = DROIDDECK_ADATASPACE_BT2020_HLG; + } else if (matrix_to_bt2020(xy, c->to2020) == 0) { + c->convert = 1; + c->gain = 10000.0f * 203.0f / ref; + } else { + struct wl_resource *bad = wl_resource_create(client, &wp_image_description_v1_interface, + wl_resource_get_version(r), id); + free(d); + if (!bad) { wl_client_post_no_memory(client); return; } + wl_resource_set_implementation(bad, &image_description_impl, NULL, NULL); + wp_image_description_v1_send_failed(bad, WP_IMAGE_DESCRIPTION_V1_CAUSE_UNSUPPORTED, + "the primaries do not form a colour space"); + droiddeck_log(TAG, "image description from %s refused: its primaries do not form a colour space", + droiddeck_client_name(client)); + wl_resource_destroy(r); + return; + } char dropped[160] = ""; float mlum_min = 0.005f, mlum_max = 10000.0f; @@ -781,7 +891,12 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3 } if (cll > 0.0f || fall > 0.0f) { c->has_cta861 = 1; c->max_cll = cll; c->max_fall = fall; } - int n = snprintf(c->text, sizeof(c->text), "%s, %s", primaries_name(c->primaries), tf_name(c->tf)); + int n = snprintf(c->text, sizeof(c->text), "%s, %s", p->has_prim ? "custom primaries" : primaries_name(c->primaries), + tf_name(c->tf)); + if (c->convert && n < (int)sizeof(c->text)) + n += snprintf(c->text + n, sizeof(c->text) - (size_t)n, + "; R %.4f,%.4f G %.4f,%.4f B %.4f,%.4f W %.4f,%.4f, reference white %.0f nits", + xy[0], xy[1], xy[2], xy[3], xy[4], xy[5], xy[6], xy[7], ref); if (c->has_st2086 && n < (int)sizeof(c->text)) n += snprintf(c->text + n, sizeof(c->text) - (size_t)n, "; mastering R %.4f,%.4f G %.4f,%.4f B %.4f,%.4f W %.4f,%.4f, %.4f-%.0f nits%s", @@ -793,19 +908,13 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3 if (!c->has_st2086 && !c->has_cta861 && n < (int)sizeof(c->text)) snprintf(c->text + n, sizeof(c->text) - (size_t)n, " (no HDR metadata: the game has not called vkSetHdrMetadataEXT)"); - struct wl_resource *out = wl_resource_create(client, &wp_image_description_v1_interface, - wl_resource_get_version(r), id); - if (!out) { free(d); wl_client_post_no_memory(client); return; } - d->refs = 1; - wl_resource_set_implementation(out, &image_description_impl, d, image_description_resource_destroy); - wp_image_description_v1_send_ready(out, c->identity); - if (c->dataspace) { - pthread_mutex_lock(&g_mu); - g_hdr.descs++; - pthread_mutex_unlock(&g_mu); - } - droiddeck_log(TAG, "image description #%u from %s: %s -> ready (on a display layer: dataspace %s)", c->identity, - droiddeck_client_name(client), c->text, dataspace_name(c->dataspace)); + if (!publish_description(client, r, id, d)) return; + if (c->convert) + droiddeck_log(TAG, "image description #%u from %s: %s -> ready (converted to BT.2020 PQ when the scene is " + "composed)", c->identity, droiddeck_client_name(client), c->text); + else + droiddeck_log(TAG, "image description #%u from %s: %s -> ready (on a display layer: dataspace %s)", c->identity, + droiddeck_client_name(client), c->text, dataspace_name(c->dataspace)); if (dropped[0]) { size_t l = strlen(dropped); if (l && dropped[l - 1] == ',') dropped[l - 1] = 0; @@ -840,8 +949,8 @@ static void params_set_tf_power(struct wl_client *c, struct wl_resource *r, uint } static void params_set_primaries_named(struct wl_client *c, struct wl_resource *r, uint32_t primaries) { struct cm_params *p = wl_resource_get_user_data(r); - PARAMS_ONCE(p->primaries, "primaries"); - if (primaries != WP_COLOR_MANAGER_V1_PRIMARIES_BT2020) { + PARAMS_ONCE(p->primaries || p->has_prim, "primaries"); + if (primaries != WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && primaries != WP_COLOR_MANAGER_V1_PRIMARIES_SRGB) { wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_PRIMARIES_NAMED, "primaries %u were not advertised", primaries); return; @@ -850,12 +959,21 @@ static void params_set_primaries_named(struct wl_client *c, struct wl_resource * } static void params_set_primaries(struct wl_client *c, struct wl_resource *r, int32_t rx, int32_t ry, int32_t gx, int32_t gy, int32_t bx, int32_t by, int32_t wx, int32_t wy) { - wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, - "set_primaries is not supported"); + struct cm_params *p = wl_resource_get_user_data(r); + PARAMS_ONCE(p->primaries || p->has_prim, "primaries"); + p->has_prim = 1; + p->prim[0] = rx; p->prim[1] = ry; p->prim[2] = gx; p->prim[3] = gy; + p->prim[4] = bx; p->prim[5] = by; p->prim[6] = wx; p->prim[7] = wy; } static void params_set_luminances(struct wl_client *c, struct wl_resource *r, uint32_t mn, uint32_t mx, uint32_t ref) { - wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, - "set_luminances is not supported"); + struct cm_params *p = wl_resource_get_user_data(r); + PARAMS_ONCE(p->has_lum, "luminances"); + if ((uint64_t)mx * 10000u <= mn || (uint64_t)ref * 10000u <= mn) { + wl_resource_post_error(r, WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_LUMINANCE, + "maximum and reference luminance must be above the minimum"); + return; + } + p->has_lum = 1; p->lum_ref = ref; } static void params_set_mastering_display_primaries(struct wl_client *c, struct wl_resource *r, int32_t rx, int32_t ry, int32_t gx, int32_t gy, int32_t bx, int32_t by, int32_t wx, int32_t wy) { @@ -1083,7 +1201,20 @@ static void cm_create_parametric_creator(struct wl_client *c, struct wl_resource } static void cm_create_windows_scrgb(struct wl_client *c, struct wl_resource *r, uint32_t id) { - wl_resource_post_error(r, WP_COLOR_MANAGER_V1_ERROR_UNSUPPORTED_FEATURE, "windows_scrgb is not supported"); + struct cm_desc *d = calloc(1, sizeof(*d)); + if (!d) { wl_client_post_no_memory(c); return; } + struct droiddeck_color *col = &d->c; + col->identity = g_next_identity++; + if (!g_next_identity) g_next_identity = 1; + col->primaries = WP_COLOR_MANAGER_V1_PRIMARIES_SRGB; + col->tf = WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_EXT_LINEAR; + col->convert = 2; + col->gain = 80.0f; + matrix_to_bt2020(BT709_XY, col->to2020); + snprintf(col->text, sizeof(col->text), "%s, %s (1.0 = 80 nits)", primaries_name(col->primaries), tf_name(col->tf)); + if (!publish_description(c, r, id, d)) return; + droiddeck_log(TAG, "image description #%u from %s: %s -> ready (converted to BT.2020 PQ when the scene is composed)", + col->identity, droiddeck_client_name(c), col->text); } static const struct wp_color_manager_v1_interface cm_impl = { @@ -1103,14 +1234,20 @@ static void bind_cm(struct wl_client *c, void *data, uint32_t ver, uint32_t id) wl_resource_set_implementation(r, &cm_impl, NULL, NULL); wp_color_manager_v1_send_supported_intent(r, WP_COLOR_MANAGER_V1_RENDER_INTENT_PERCEPTUAL); wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_PARAMETRIC); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_PRIMARIES); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_LUMINANCES); wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_SET_MASTERING_DISPLAY_PRIMARIES); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_EXTENDED_TARGET_VOLUME); + wp_color_manager_v1_send_supported_feature(r, WP_COLOR_MANAGER_V1_FEATURE_WINDOWS_SCRGB); + wp_color_manager_v1_send_supported_primaries_named(r, WP_COLOR_MANAGER_V1_PRIMARIES_SRGB); wp_color_manager_v1_send_supported_primaries_named(r, WP_COLOR_MANAGER_V1_PRIMARIES_BT2020); wp_color_manager_v1_send_supported_tf_named(r, WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ); wp_color_manager_v1_send_done(r); if (last_named != c) { last_named = c; droiddeck_log(TAG, "%s bound wp_color_manager_v1 version %u (offered: perceptual intent; parametric descriptions " - "with mastering metadata; BT.2020 primaries; ST 2084 PQ) - its Vulkan driver can now list " + "with custom primaries, luminances and mastering metadata; Windows scRGB; sRGB and BT.2020 primaries; " + "ST 2084 PQ) - its Vulkan driver can now list " "VK_COLOR_SPACE_HDR10_ST2084_EXT", droiddeck_client_name(c), ver > 1 ? 1u : ver); } } @@ -1150,6 +1287,7 @@ void droiddeck_color_init(struct wl_display *display) { char asked[128]; if (mode == 2) snprintf(asked, sizeof(asked), "DROIDDECK_WAYLAND_HDR=force (%s)", source); + else if (mode == 3) snprintf(asked, sizeof(asked), "HDR is on, tone-mapped for this display (%s)", source); else if (strstr(source, "env")) snprintf(asked, sizeof(asked), "DROIDDECK_WAYLAND_HDR=1 (%s)", source); else snprintf(asked, sizeof(asked), "HDR output is on (%s)", source); @@ -1168,7 +1306,7 @@ void droiddeck_color_init(struct wl_display *display) { snprintf(why, sizeof(why), "this Android has no display layers with dataspace control " "(ASurfaceControl + ASurfaceTransaction_setBufferDataSpace, Android 10+)"); else if (!ahb_ok) - snprintf(why, sizeof(why), "zero-copy presentation is unavailable here (banner_ahb_v1 not advertised), and an " + snprintf(why, sizeof(why), "zero-copy presentation is unavailable here (droiddeck_ahb_v1 not advertised), and an " "HDR frame is only honest on the game's own display layer"); if (why[0]) { @@ -1198,13 +1336,20 @@ void droiddeck_color_init(struct wl_display *display) { log_verdict(1); return; } + pthread_mutex_lock(&g_output_mu); atomic_store(&g_gate, 1); + if (mode == 3 || !atomic_load(&g_output_wanted)) atomic_store(&g_output_on, 0); + pthread_mutex_unlock(&g_output_mu); char syms[160]; sc_layer_hdr_symbols(syms, sizeof(syms)); droiddeck_log(TAG, "HDR gate %s: %s and %s. Offering games HDR10: wp_color_manager_v1 version 1 (BT.2020 primaries " "+ ST 2084 PQ, parametric descriptions with mastering metadata) and 10-bit AB30/XB30 dma-buf formats; HDR " "frames go on the game's own display layer as BT2020_PQ (%s)", mode == 2 ? "FORCED OPEN (testing)" : "OPEN", asked, disp, syms); + if (mode == 3) { + droiddeck_log(TAG, "this display cannot show HDR10: games still render HDR and every HDR frame is tone-mapped to " + "SDR on the game's display layer"); + } if (mode == 2 && !hdr10) droiddeck_log(TAG, "DROIDDECK_WAYLAND_HDR=force on a display without HDR10 - testing only: SurfaceFlinger will tone-map " "the game layer for this panel (expect GPU/CLIENT composition for it), nothing looks HDR"); diff --git a/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c b/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c index cc85bd32e6..a6e0eac3a6 100644 --- a/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c +++ b/app/src/main/cpp/waylandcomp/src/wl_dmabuf.c @@ -14,6 +14,7 @@ #include "droiddeck_ext.h" #include "droiddeck_color.h" #include "compositor_internal.h" +#include "display_buffers.h" static void dbuf_buffer_resource_destroy(struct wl_resource *r) { @@ -58,6 +59,7 @@ static struct wl_resource *params_do_create(struct wl_client *c, struct wl_resou wl_resource_set_implementation(buf, &dbuf_buffer_impl, b, dbuf_buffer_resource_destroy); struct client_info *ci = client_info_of(c); if (ci) ci->dmabuf_buffers++; + display_buffers_match(c, buf, b); return buf; } static void params_create(struct wl_client *c, struct wl_resource *r, int32_t w, int32_t h, @@ -111,13 +113,16 @@ static const struct zwp_linux_dmabuf_v1_interface dmabuf_impl = { static struct { uint32_t fmt; uint64_t mods[DMABUF_NMOD]; int n; } g_dmabuf_fmts[DMABUF_NFMT_MAX] = { {DRM_ARGB8888}, {DRM_XRGB8888}, {DRM_ABGR8888}, {DRM_XBGR8888}, {DRM_ABGR2101010}, {DRM_XBGR2101010}}; static int g_dmabuf_nfmt = DMABUF_NFMT_SDR; -static int g_dmabuf_fmts_ready; +static volatile int g_dmabuf_fmts_ready; static void dmabuf_build_feedback(void); +void droiddeck_dmabuf_formats_stale(void) { g_dmabuf_fmts_ready = 0; } + static void dmabuf_build_formats(void) { char line[320]; - int pos = 0, compressed = 0; + int pos = 0, compressed = 0, backed = 0; g_dmabuf_fmts_ready = 1; + display_buffers_withdraw_ubwc(); g_dmabuf_nfmt = droiddeck_color_hdr_open() ? DMABUF_NFMT_MAX : DMABUF_NFMT_SDR; for (int f = 0; f < g_dmabuf_nfmt; f++) { uint64_t got[DMABUF_NMOD]; @@ -129,6 +134,12 @@ static void dmabuf_build_formats(void) { g_dmabuf_fmts[f].mods[k++] = got[i]; if (got[i] == VKP_MOD_QCOM_COMPRESSED) compressed++; } + int listed = 0; + for (int i = 0; i < k; i++) if (g_dmabuf_fmts[f].mods[i] == VKP_MOD_QCOM_COMPRESSED) listed = 1; + if (display_buffers_offer_ubwc(g_dmabuf_fmts[f].fmt) && !listed) { + g_dmabuf_fmts[f].mods[k++] = VKP_MOD_QCOM_COMPRESSED; + backed++; + } g_dmabuf_fmts[f].mods[k++] = MOD_INVALID; g_dmabuf_fmts[f].n = k; uint32_t fmt = g_dmabuf_fmts[f].fmt; @@ -141,7 +152,10 @@ static void dmabuf_build_formats(void) { } droiddeck_log("dmabuf", "formats: %s%s", line, !g_ubwc ? " (DROIDDECK_WAYLAND_UBWC=0: qcom_compressed not advertised)" : ""); - if (g_ubwc && !compressed) + if (backed) + droiddeck_log("dmabuf", "qcom_compressed is advertised for %d formats the compositor's driver (%s) does not " + "import as dma-bufs: this session's driver renders them into gralloc buffers", backed, vkp_gpu_name()); + else if (g_ubwc && !compressed) droiddeck_log("dmabuf", "the compositor's driver (%s) reports no importable qcom_compressed layout: " "game swapchains stay linear", vkp_gpu_name()); if (g_dmabuf_nfmt > DMABUF_NFMT_SDR) { @@ -212,6 +226,7 @@ static void dmabuf_build_feedback(void) { return; } fcntl(fd, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE); + if (g_fmt_table_fd >= 0) close(g_fmt_table_fd); g_fmt_table_fd = fd; g_fmt_table_size = size; g_fmt_table_n = (uint16_t)n; diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 1a45ab8512..58e7e12b2c 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -21,6 +21,7 @@ class App : Application() { override fun onCreate() { super.onCreate() com.droiddeck.launcher.runtime.NativeGuest.init(this) + com.droiddeck.launcher.session.Onboarding.attach(this) Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start() com.droiddeck.launcher.ui.Themes.loadGradient(this) com.droiddeck.launcher.ui.BuildWatermark.install(this) @@ -46,6 +47,7 @@ class App : Application() { com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this) com.droiddeck.launcher.agent.AgentHost.refresh(this) com.droiddeck.launcher.ui.NavTabs.load(this) + com.droiddeck.launcher.ui.DrawerPages.load(this) com.droiddeck.launcher.ui.DeveloperTools.load(this) com.droiddeck.launcher.ui.AgentPet.install(this) if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent" @@ -96,6 +98,8 @@ class App : Application() { com.droiddeck.launcher.session.SessionFiles.ensureUbisoftService(app) if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.ROCKSTAR) != null) com.droiddeck.launcher.session.SessionFiles.ensureRockstarService(app) + if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.EPIC) != null) + com.droiddeck.launcher.session.SessionFiles.ensureEpicParent(app) com.droiddeck.launcher.handtracking.HandTracking.load(app) }.onFailure { android.util.Log.w("App", "add-on pack prefetch failed", it) } }, "addon-packs").start() diff --git a/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt b/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt index e5e74f791f..79e2017962 100644 --- a/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ComponentsMenu.kt @@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat checkAgain = null checkComponentUpdates(again) } - if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show() + if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; ")) refreshComponents() } }, "component-updates").start() diff --git a/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt b/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt index 240202daec..983eea5ea0 100644 --- a/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt @@ -6,6 +6,7 @@ import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.droiddeck.launcher.runtime.DeckyManager +import com.droiddeck.launcher.runtime.DeckyStore import com.droiddeck.launcher.session.SessionState import java.io.File @@ -21,6 +22,59 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val var deckySupervisor by mutableStateOf(false) var deckyPendingZip by mutableStateOf(null) var deckyReleaseRequest = 0 + var deckyPlugins by mutableStateOf>(emptyList()) + var deckyStore by mutableStateOf?>(null) + var deckyStoreFailed by mutableStateOf(false) + private var storeRequest = 0 + + fun refreshPlugins() { + Thread({ + val found = DeckyStore.installed(activity) + ui.post { deckyPlugins = found } + }, "decky-plugins").start() + } + + fun refreshStore() { + val request = ++storeRequest + deckyStore = null; deckyStoreFailed = false + Thread({ + val listing = DeckyStore.fetch() + ui.post { + if (request != storeRequest) return@post + deckyStore = listing.orEmpty(); deckyStoreFailed = listing == null + } + }, "decky-store").start() + } + + fun installStorePlugin(plugin: DeckyStore.Plugin) { + val version = plugin.latest ?: return + if (deckyStage != null || SessionState.running || deckyInstalled == null) return + deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1 + Thread({ + val problem = runCatching { + DeckyStore.install(activity, plugin, version) { label, value -> + val binary = DeckyManager.downloadingBinary + ui.post { deckyStage = label; deckyPercent = value; deckyDownloadingBinary = binary } + } + }.getOrElse { error -> activity.getString(R.string.decky_plugin_failed, error.message ?: error.javaClass.simpleName) } + ui.post { + deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false + android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.decky_plugin_installed), android.widget.Toast.LENGTH_LONG).show() + refreshPlugins() + } + }, "install-decky-store").start() + } + + fun removePlugin(plugin: DeckyStore.Installed) { + if (deckyStage != null || SessionState.running) return + Thread({ + val problem = DeckyStore.remove(activity, plugin) + ui.post { + if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show() + refreshPlugins() + } + }, "remove-decky-plugin").start() + } fun refreshDecky() { val request = ++deckyReleaseRequest @@ -90,6 +144,7 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false val message = problem ?: activity.getString(R.string.decky_plugin_installed) android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show() + refreshPlugins() } }, "import-decky-plugin").start() } diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index d286cce1f5..a26bb5d81e 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -17,8 +17,11 @@ import android.os.Looper import android.util.Log import android.view.Display import android.view.KeyEvent +import android.view.MotionEvent import android.view.View +import android.view.ViewConfiguration import android.view.WindowManager +import android.widget.EditText import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts @@ -50,6 +53,8 @@ import com.droiddeck.launcher.session.SessionLogShare import com.droiddeck.launcher.session.SessionPaths import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SteamRepair +import com.droiddeck.launcher.session.LaunchCoordinator +import com.droiddeck.launcher.session.LaunchTicket import com.droiddeck.launcher.core.CpuCores import com.droiddeck.launcher.core.DownloadSource import com.droiddeck.launcher.core.PhantomProcessLimit @@ -184,7 +189,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var gpuClockPin by mutableStateOf(false) private var prootNoSeccomp by mutableStateOf(false) private var prootFastPath by mutableStateOf(true) - private var nativeUserland by mutableStateOf(false) + private var nativeUserland by mutableStateOf(true) private var cursorComposite by mutableStateOf(false) private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME) private var phantomWarning by mutableStateOf(null) @@ -194,10 +199,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var picturePosition by mutableStateOf("center") private var integerScaling by mutableStateOf(false) private var stretch16x9 by mutableStateOf(false) + private var avoidNotch by mutableStateOf(false) private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM) private var launcherFullscreen by mutableStateOf(true) + private var controllerHaptics by mutableStateOf(true) private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO) private var downloadMirror by mutableStateOf("") private var downloadPrefix by mutableStateOf("") @@ -210,7 +217,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var soundtracksLoaded by mutableStateOf(false) private var gameStoresSpeedTier by mutableStateOf("fast") private var navRequest by mutableStateOf(null) - private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong() + private val launchCoordinator = LaunchCoordinator() private var preparingGames by mutableStateOf(emptySet()) private var storesShowMature by mutableStateOf(false) private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first()) @@ -249,6 +256,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this)) refreshWifiDiscovery() } + private val bluetoothPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + if (!granted && !shouldShowRequestPermissionRationale(android.Manifest.permission.BLUETOOTH_CONNECT)) { + integrationSettings(SteamIntegration.appInfo(this)) + } + integrationState = readIntegration() + } private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { com.droiddeck.launcher.handtracking.HandTracking.refreshPermission(this) } @@ -370,6 +383,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet SteamIntegration.Feature.SHORTCUTS -> { if (integrationState.shortcuts) openShortcutSettings() else installShortcuts() } + SteamIntegration.Feature.BLUETOOTH -> { + if (SteamIntegration.bluetoothAllowed(this)) integrationSettings(SteamIntegration.appInfo(this)) + else bluetoothPermission.launch(android.Manifest.permission.BLUETOOTH_CONNECT) + } } } @@ -528,7 +545,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet saveAction(getString(R.string.main_addons_importing, name)) { if (SessionState.running) return@saveAction getString(R.string.main_addons_close_session) val imported = try { - com.droiddeck.launcher.runtime.WowAddons.import(zip, target) + com.droiddeck.launcher.runtime.WowAddons.import(zip, target, context = this@FrontEndActivity) } catch (_: com.droiddeck.launcher.runtime.WowAddons.TooLarge) { return@saveAction getString(R.string.main_addons_too_large, zip.name) } @@ -537,7 +554,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } val downloads = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path - pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_addons_pick_zip, name), downloads)) + pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip", "rar", "7z"), getString(R.string.main_addons_pick_zip, name), downloads)) } private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) { @@ -584,6 +601,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } private var settingsMode by mutableStateOf(null) private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION) + private var resolutionPortrait by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE) private var fexPreset by mutableStateOf("") private var forceSsbs by mutableStateOf(false) private var steamClientArch by mutableStateOf("arm64") @@ -596,9 +614,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var theme by mutableStateOf("graphite") private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) private var hdrOn by mutableStateOf(false) + private var zeroCopyOn by mutableStateOf(true) private var upscaler by mutableStateOf(0) private var upscaleSharpness by mutableStateOf(75) private var hdrReason by mutableStateOf(null) + private var hdrDisplay by mutableStateOf(true) private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO) private var pen by mutableStateOf(null) private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) @@ -619,6 +639,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } private var storageDiagnostics by mutableStateOf(false) private var storageOptions by mutableStateOf>(emptyList()) + private var storageFat32 by mutableStateOf(false) private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) } } @@ -634,6 +655,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private fun addSteamLibrary(path: String) { Thread({ val result = SteamLibraries.add(this, path) + val fat32 = result is SteamLibraries.AddResult.Added && GameStorage.isFat32(result.entry.path) ui.post { steamLibraries = SteamLibraries.list(this) refreshFoundSteamLibraries() @@ -644,6 +666,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet result is SteamLibraries.AddResult.Added && result.entry.path != path -> android.widget.Toast.makeText(this, getString(R.string.libraries_used_inner, result.entry.label), android.widget.Toast.LENGTH_LONG).show() } + if (fat32) android.widget.Toast.makeText(this, R.string.main_storage_fat32, android.widget.Toast.LENGTH_LONG).show() } }, "steam-library-add").start() } @@ -699,6 +722,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } private var secondScreenDisplays by mutableStateOf>(emptyList()) + private var ownScreen by mutableStateOf(null) private var dualDisplayId by mutableStateOf(-1) private var dualScreenDevice by mutableStateOf(false) private var dualScreenMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO) @@ -875,7 +899,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) } }, "components-restore").start() } - private var pendingGameLink: com.droiddeck.launcher.frontend.GameRequest? = null private var gameLinkReading = false private var gameLinkTried = false private var gameSyncFolder by mutableStateOf(null) @@ -901,23 +924,34 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet LauncherIcon.set(this, style) launcherIcon = LauncherIcon.current(this) if (launcherIcon == before) return false + restartLauncher() + return true + } + + // recreate() leaves this activity's window drawing nothing and ignoring input on some devices (#2668). + private fun restartLauncher() { + LauncherHandoff.put(Bundle().also(::saveLauncherState)) + switchPoll?.let { ui.removeCallbacks(it) } + switchPoll = null + switchingTo = null + queuedLaunch.clear() + cancelCompatLaunch() startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER) .setComponent(LauncherIcon.activity(this)) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK) - .putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher")) + .putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher") + .putExtra(EXTRA_RESTARTED, true)) finishAndRemoveTask() - return true } 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) } request.data?.takeIf { it.scheme == "droiddeck" && it.host == "settings" }?.let { uri -> val section = uri.pathSegments.firstOrNull() - navRequest = if (section in setOf("storage", "sync", "downloads")) section + navRequest = if (section in setOf("storage", "sync", "downloads", "decky", "boot-movies")) section else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key request.data = null gameLinkReading = false - pendingGameLink = null syncDualPanel() return } @@ -930,7 +964,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet steamGames = emptyList() shortcutLibraryScanning = true } else shortcutLibraryScanning = false - pendingGameLink = null gameLinkReading = false gameLinkTried = false soundtrackLaunch = false @@ -943,6 +976,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet return } if (GameLaunchIntent.accepts(request.action)) { + val ticket = launchCoordinator.beginLink(request) gameLinkReading = true com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId) val copy = Intent(request) @@ -951,12 +985,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet ui.post { if (intent === request && !isDestroyed) { gameLinkReading = false - pendingGameLink = game + if (!launchCoordinator.resolve(ticket, game)) { + clearGameLinkIntent(request) + syncDualPanel() + return@post + } if (game == null) { + launchCoordinator.consume(ticket) syncDualPanel() android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show() } else { - handleGameLink(steamGames, scanned = false) + handleGameLink(steamGames, scanned = false, ticket = ticket) refresh() } } @@ -965,37 +1004,66 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } - private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) { - val request = gameLaunchRequest.incrementAndGet() + private fun beginUiLaunch(): LaunchTicket { + val dropped = launchCoordinator.pendingLink() + val ticket = launchCoordinator.beginLaunch() + dropped?.let { if (intent === it.owner) clearGameLinkIntent(it.owner) } + return ticket + } + + private fun clearGameLinkIntent(link: Intent) { + link.data = null + link.action = Intent.ACTION_MAIN + link.removeExtra(GameLaunchIntent.EXTRA_APP_ID) + } + + private fun launchGame( + game: Library.SteamGame, + returnHome: Boolean = false, + onHandled: () -> Unit = {}, + onSettled: () -> Unit = {}, + ticket: LaunchTicket? = null, + ) { if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this) if (pkgStage != null) { + ticket?.let(launchCoordinator::releaseHandling) onHandled() android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() return } + val request = ticket ?: beginUiLaunch() + if (!launchCoordinator.isCurrent(request)) { + onHandled() + return + } val files = game.gameFiles if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) { - if (startGame(game, returnHome, onHandled)) onSettled() + if (startGame(game, returnHome, onHandled, request)) onSettled() + else launchCoordinator.releaseHandling(request) return } Thread({ val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files) ui.post { when { - request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled() + !launchCoordinator.isCurrent(request) || isFinishing || isDestroyed -> { + launchCoordinator.releaseHandling(request) + onHandled() + } refused -> { onHandled() android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show() onSettled() } - startGame(game, returnHome, onHandled) -> onSettled() + startGame(game, returnHome, onHandled, request) -> onSettled() + else -> launchCoordinator.releaseHandling(request) } } }, "xbox-app-model").start() } - private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean { - if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled) + private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit, ticket: LaunchTicket): Boolean { + if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled, ticket) onHandled() if (SessionState.running) { if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) { @@ -1040,15 +1108,34 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet .apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) } } - private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit = {}): Boolean { + private fun launchWithoutSteam( + game: Library.SteamGame, + returnHome: Boolean, + onHandled: () -> Unit = {}, + ticket: LaunchTicket? = null, + ): Boolean { + if (pkgStage != null) { + onHandled() + android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() + return false + } val app = applicationContext + val request = ticket ?: beginUiLaunch() + if (!launchCoordinator.isCurrent(request)) { + onHandled() + return false + } Thread({ val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added) ui.post { onHandled() - if (isDestroyed) return@post + if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) { + launchCoordinator.releaseHandling(request) + return@post + } if (command == null) { + launchCoordinator.releaseHandling(request) android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show() return@post } @@ -1200,22 +1287,27 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet ui.postDelayed(poll, SESSION_SWITCH_POLL_MS) } - private fun handleGameLink(games: List, scanned: Boolean = true) { + private fun handleGameLink(games: List, scanned: Boolean = true, ticket: LaunchTicket? = null) { if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return - val request = pendingGameLink ?: return + val link = launchCoordinator.pendingLink() ?: return + if (ticket != null && link.ticket !== ticket) return + val request = link.request ?: return + if (launchCoordinator.isHandling(link.ticket)) return + if (ticket == null && !link.ownedBy(intent)) { + // A refresh may only finish the link that belongs to the intent this activity shows. + launchCoordinator.consume(link.ticket) + return + } val game = request.find(games, byTitle = scanned) if (!scanned && game == null) return gameLinkTried = true ui.postDelayed({ if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel() }, LINK_PANEL_MS) - val link = intent + val linkIntent = link.owner fun consume() { - if (intent !== link || pendingGameLink !== request) return - pendingGameLink = null - link.data = null - link.action = Intent.ACTION_MAIN - link.removeExtra(GameLaunchIntent.EXTRA_APP_ID) + if (!launchCoordinator.consume(link.ticket)) return + if (intent === linkIntent) clearGameLinkIntent(linkIntent) } if (game == null) { consume() @@ -1223,7 +1315,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet android.widget.Toast.makeText(this, if (request.program != null) R.string.game_link_program_unknown else R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show() - } else launchGame(game, returnHome = true, onSettled = ::consume) + } else { + if (!launchCoordinator.beginHandling(link.ticket)) return + launchGame(game, returnHome = true, onSettled = ::consume, ticket = link.ticket) + } } private fun chooseGameShortcut(game: Library.SteamGame) { @@ -1235,9 +1330,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet super.onCreate(savedInstanceState) drivers.restartBlocked = ::runtimeChangesBlocked drivers.loadTpUbwcMode() - pendingSessionLogExport = savedInstanceState?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File) - homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true - gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true + val handoff = if (savedInstanceState == null && intent.getBooleanExtra(EXTRA_RESTARTED, false)) LauncherHandoff.take() else null + val saved = savedInstanceState ?: handoff + pendingSessionLogExport = saved?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File) + queuedLaunch.restore( + saved?.let { androidx.core.os.BundleCompat.getParcelable(it, STATE_PENDING_GATE_LAUNCH, Intent::class.java) }, + saved?.getLong(STATE_PENDING_GATE_LAUNCH_AT, 0L) ?: 0L, System.currentTimeMillis(), + ) + homeChoiceOpen = saved?.getBoolean(STATE_HOME_CHOICE_OPEN) == true + gameSpaceOffered = saved?.getBoolean(STATE_GAME_SPACE_OFFERED) == true if (savedInstanceState == null) readIntegrationIntent(intent) val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS) if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED) @@ -1261,6 +1362,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet requestedOrientation = launcherOrientation homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this) launcherFullscreen = SessionPrefs.launcherFullscreen(this) + controllerHaptics = SessionPrefs.controllerHaptics(this) downloadSource = DownloadSource.mode(this) downloadMirror = DownloadSource.mirror(this) downloadPrefix = DownloadSource.custom(this) @@ -1336,6 +1438,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet integrationFocus = integrationFocus, androidApps = androidApps, secondScreenDisplays = secondScreenDisplays, + ownScreen = ownScreen, dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available, dualScreenDevice = dualScreenDevice, dualScreenMode = dualScreenMode, @@ -1360,6 +1463,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet launcherOrientation = launcherOrientation, homePage = homePage, launcherFullscreen = launcherFullscreen, + controllerHaptics = controllerHaptics, downloadSource = downloadSource, downloadMirror = downloadMirror, downloadPrefix = downloadPrefix, @@ -1382,6 +1486,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet ), FrontEndActions( onPlay = { playSteam() }, + onQueuePlaySteam = { + queuedLaunch.queue(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, false), System.currentTimeMillis()) + }, onPlaySteamVr = { playSteamVr() }, onSteamUrl = { url -> if (!SessionState.running) startSession( @@ -1402,16 +1509,20 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet }, onStoreGame = { store, id -> val key = "${store.id}:$id" - if (key !in preparingGames) { + if (pkgStage != null) { + android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() + } else if (key !in preparingGames) { preparingGames = preparingGames + key + val ticket = beginUiLaunch() val app = applicationContext Thread({ val g = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull() runOnUiThread { - if (g != null && !isFinishing && !isDestroyed) prepareAndLaunch(g, key) - else { + if (g != null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) { + prepareAndLaunch(g, key, ticket) + } else { preparingGames = preparingGames - key - if (g == null && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show() + if (g == null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show() } } }, "store-play").start() @@ -1521,7 +1632,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onAddonImport = { sg, target -> importAddons(sg.name, target) }, onAddonDelete = { target, name -> saveAction(getString(R.string.main_addons_deleting, name)) { - com.droiddeck.launcher.runtime.WowAddons.delete(target, name) + com.droiddeck.launcher.ui.deleteAddon(this, target, name) getString(R.string.main_addons_deleted, name) } }, @@ -1656,7 +1767,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onLanguage = { tag -> if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) { com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag) - recreate() + restartLauncher() } }, onAppScale = { percent -> @@ -1676,6 +1787,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet com.droiddeck.launcher.core.AppUiPrefs.setHomePage(this, value) homePage = value }, + onControllerHaptics = { on -> SessionPrefs.setControllerHaptics(this, on); controllerHaptics = on }, onLauncherFullscreen = { on -> SessionPrefs.setLauncherFullscreen(this, on) launcherFullscreen = on @@ -1752,31 +1864,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet }, onRefreshPhantomStatus = { refreshPhantomStatus() }, onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) }, - onWirelessAdbPair = { host, port, code, complete -> - Thread({ - val result = runCatching { - kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@FrontEndActivity, host, port, code) } - } - val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_pair_failed) } - ui.post { complete(error) } - }, "wireless-adb-pair").start() - }, - onFindWirelessAdbPort = { host, complete -> - Thread({ - val port = WirelessAdbFix.findConnectPort(this@FrontEndActivity, host) - ui.post { complete(port) } - }, "wireless-adb-discovery").start() - }, - onWirelessAdbApply = { host, port, enabled, complete -> - Thread({ - val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@FrontEndActivity, host, port, enabled) } - val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_command_failed) } - ui.post { - if (error == null) refreshPhantomStatus() - complete(error) - } - }, "wireless-adb-fix").start() - }, onSetPhantomProcessLimit = { enabled, complete -> Thread({ val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@FrontEndActivity, enabled) } @@ -1793,18 +1880,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet ) android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show() }, - onDismissPhantomGate = { showPhantomGate = false }, + onDismissPhantomGate = { queuedLaunch.clear(); showPhantomGate = false }, onShowPhantomGate = { refreshPhantomStatus() showPhantomGate = true }, - onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) }, + onStartWirelessAdbPairing = { enabled -> WirelessAdbPairingService.start(this, enabled) }, onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) }, - onOpenNotificationSettings = { - startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS) - .putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) - }, + onEnsureNotifications = { done -> ensureNotifications(done) }, updates = updates.actions(), controller = ControllerActions( onMapping = { showPerformance = false; showComponents = false; showMapping = true }, @@ -1900,10 +1983,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet !SessionPrefs.allFilesAsked(this) if (savedInstanceState == null) { if (!askAllFiles) ui.post { startSteamAtStartupIfEnabled(cold = true) } - } else { - restoreCompatLaunch(savedInstanceState) - pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH) - savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) } + } + saved?.let { state -> + restoreCompatLaunch(state) + pendingSwitch = savedIntent(state, KEY_PENDING_SWITCH) + savedIntent(state, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, state.getLong(KEY_SWITCH_DEADLINE)) } } val wanted = ArrayList() @@ -1941,10 +2025,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) - gameLaunchRequest.incrementAndGet() + supersedeUncommittedLaunch() if (intent.action == SteamIntegration.ACTION_SETUP) { gameLinkReading = false - pendingGameLink = null syncDualPanel() readIntegrationIntent(intent) return @@ -1954,10 +2037,19 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet startSteamAtStartupIfEnabled() } + /** A replacement activity intent supersedes anything this activity has not dispatched yet. */ + private fun supersedeUncommittedLaunch() { + launchCoordinator.cancelAll() + } + private var soundtrackLaunch = false + // A restarted launcher starts before the old one stops, so each clears the hooks only if they are still its own. + private val libraryHook: () -> Unit = { refreshAddedGames(); refresh() } + private val battleNetHook: (List) -> Unit = { args -> openBattleNet(args) } + private fun startSteamAtStartupIfEnabled(cold: Boolean = false) { - if (soundtrackLaunch) return + if (soundtrackLaunch || intent.getBooleanExtra(EXTRA_RESTARTED, false)) return if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return if (isFinishing || isDestroyed) return when (SessionPrefs.startupSession(this)) { @@ -1984,7 +2076,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } private fun startSteamSession(steamVr: Boolean = false) { - startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true) + startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true, queueIfBlocked = !steamVr) } @Suppress("OVERRIDE_DEPRECATION") @@ -2005,6 +2097,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) + if (!hasFocus) triggerKeys.cancel() if (hasFocus) { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) applyLauncherFullscreen() @@ -2034,6 +2127,36 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } + private var touchDownX = 0f + private var touchDownY = 0f + private var touchDragged = false + + override fun dispatchTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> { + com.droiddeck.launcher.ui.ScreenTaps.count++ + touchDownX = event.rawX + touchDownY = event.rawY + touchDragged = false + } + // A drag that wanders back to where it began is still a drag, not a tap. + MotionEvent.ACTION_MOVE -> if (!touchDragged && + kotlin.math.hypot(event.rawX - touchDownX, event.rawY - touchDownY) > ViewConfiguration.get(this).scaledTouchSlop + ) touchDragged = true + MotionEvent.ACTION_CANCEL -> touchDragged = true + } + val handled = super.dispatchTouchEvent(event) + if (event.actionMasked == MotionEvent.ACTION_UP) leaveTextFieldOnOutsideTap(event) + return handled + } + + private fun leaveTextFieldOnOutsideTap(event: MotionEvent) { + val field = currentFocus as? EditText ?: return + val slop = ViewConfiguration.get(this).scaledTouchSlop + if (touchDragged || kotlin.math.hypot(event.rawX - touchDownX, event.rawY - touchDownY) > slop) return + com.droiddeck.launcher.ui.releaseTextField(field, IntArray(2).also(field::getLocationOnScreen), event.rawX, event.rawY) + } + override fun dispatchKeyEvent(event: KeyEvent): Boolean { if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true if (compatLaunch != null) { @@ -2044,6 +2167,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (!compatLaunch!!.loading.ended && event.keyCode !in listOf( KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true } + if (!triggerKeys.synthesizing && triggerKeys.nativeKey(event)) return true + val tabStep = com.droiddeck.launcher.ui.dualPageStep(event) + val tabs = com.droiddeck.launcher.ui.MainTabSteps.handler + if (tabStep != null && tabs != null) { + if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event) + if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) tabs(tabStep) + return true + } + if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event) 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) { @@ -2060,9 +2192,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } + private val triggerKeys = com.droiddeck.launcher.input.TriggerKeys { dispatchKeyEvent(it) } + override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean { if (compatLaunch != null && !compatLaunch!!.loading.ended && com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true + triggerKeys.onMotion(event) return super.dispatchGenericMotionEvent(event) } @@ -2079,6 +2214,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet refreshHomeAppState() } if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries() + settingsMode?.let { hdrOn = SessionPrefs.hdr(this, it) } compatLaunchVisible = true com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false) @@ -2088,8 +2224,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this) refreshWifiDiscovery() com.droiddeck.launcher.stores.StoresState.refresh(this) - com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() } - com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) } + com.droiddeck.launcher.stores.StoresState.libraryListener = libraryHook + com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = battleNetHook com.droiddeck.launcher.ui.Motion.refresh(this) com.droiddeck.launcher.ui.QuitFlood.take()?.let { c -> returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn()) @@ -2111,9 +2247,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (!OfflineMode.enabled(this)) { val updated = runCatching { ComponentUpdater.ensure(this, force = false) } .onFailure { android.util.Log.w("ComponentUpdater", "automatic component updates", it) }.getOrDefault(emptyList()) - if (updated.isNotEmpty()) ui.post { - android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show() - } + if (updated.isNotEmpty()) android.util.Log.i("ComponentUpdater", updated.joinToString("; ")) } ui.post { componentsQueueBusy = false @@ -2162,9 +2296,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) + saveLauncherState(outState) + } + + private fun saveLauncherState(outState: Bundle) { outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen) outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered) pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) } + queuedLaunch.launch?.let { + outState.putParcelable(STATE_PENDING_GATE_LAUNCH, it) + outState.putLong(STATE_PENDING_GATE_LAUNCH_AT, queuedLaunch.queuedAt) + } if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this) saveCompatLaunch(outState) pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) } @@ -2178,20 +2320,32 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (Build.VERSION.SDK_INT >= 33) state.getParcelable(key, Intent::class.java) else @Suppress("DEPRECATION") state.getParcelable(key) - private fun prepareAndLaunch(g: Library.SteamGame, key: String) { - val request = gameLaunchRequest.incrementAndGet() + private fun prepareAndLaunch(g: Library.SteamGame, key: String, ticket: LaunchTicket? = null) { + if (pkgStage != null) { + preparingGames = preparingGames - key + android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() + return + } + val request = ticket ?: beginUiLaunch() + if (!launchCoordinator.isCurrent(request)) { + preparingGames = preparingGames - key + return + } val done = { preparingGames = preparingGames - key } com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) { - if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch } + if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) { done(); return@beforeLaunch } com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { - if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g, onHandled = done) + if (launchCoordinator.isCurrent(request) && !isFinishing && !isDestroyed) launchGame(g, onHandled = done, ticket = request) else done() } } } override fun onDestroy() { - gameLaunchRequest.incrementAndGet() + // The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too. + queuedLaunchRunner.destroy() + triggerKeys.cancel() + launchCoordinator.cancelAll() cancelCompatLaunch() updates.unregister() runCatching { unregisterReceiver(shortcutsInstallStatus) } @@ -2211,8 +2365,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback) HomeWidgets.stopListening(this) ui.removeCallbacks(mediaRefresh) - com.droiddeck.launcher.stores.StoresState.libraryListener = null - com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null + if (com.droiddeck.launcher.stores.StoresState.libraryListener === libraryHook) com.droiddeck.launcher.stores.StoresState.libraryListener = null + if (com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener === battleNetHook) com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null displayManager.unregisterDisplayListener(secondScreenDisplayListener) com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener) getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener) @@ -2252,6 +2406,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet val ownDisplayId = if (android.os.Build.VERSION.SDK_INT >= 30) display?.displayId ?: android.view.Display.DEFAULT_DISPLAY else @Suppress("DEPRECATION") windowManager.defaultDisplay.displayId dualScreenMode = SessionPrefs.dualScreenMode(this) secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId) + ownScreen = ownDisplayId.takeIf { it != Display.DEFAULT_DISPLAY }?.let { id -> + displayManager.getDisplay(id)?.takeIf { it.isValid }?.let { SecondScreenDisplay(id, "${it.name} · ${it.mode.physicalWidth}×${it.mode.physicalHeight}") } + } dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null dualScreenSessions = SessionPrefs.dualScreenSessionMode(this) dualScreenControls = SessionPrefs.dualScreenSessionControls(this) @@ -2267,22 +2424,29 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId) } - private fun launchPending(): Boolean = gameLinkReading || (pendingGameLink != null && !gameLinkTried) + private fun launchPending(): Boolean = gameLinkReading || (launchCoordinator.hasPending() && !gameLinkTried) private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) { val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY) if (onOwnScreen) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true) - try { - HomeApp.launch(this, app, displayId) - } catch (_: Exception) { - com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) - val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label - val message = when { - displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label) - label != null -> getString(R.string.android_app_open_failed_on, app.label, label) - else -> getString(R.string.android_app_open_failed_display, app.label, displayId) + val open = { + try { + HomeApp.launch(this, app, displayId) + } catch (_: Exception) { + com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) + val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label + val message = when { + displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label) + label != null -> getString(R.string.android_app_open_failed_on, app.label, label) + else -> getString(R.string.android_app_open_failed_display, app.label, displayId) + } + android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show() } - android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show() + } + if (displayId != null && displayId == com.droiddeck.launcher.ui.DualScreenPanel.shownOn) { + com.droiddeck.launcher.ui.DualScreenPanel.makeRoomForApp(this, displayId, open) + } else { + open() } } @@ -2584,9 +2748,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (settingsMode != mode) return com.droiddeck.launcher.ui.ModeSheetRows( ModeSettings( - mode = mode, resolution = resolution, + mode = mode, resolution = resolution, resolutionPortrait = resolutionPortrait, panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this), - hdr = hdrOn, hdrReason = hdrReason, + hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn, upscaler = upscaler, upscaleSharpness = upscaleSharpness, gpuDrivers = drivers.summary(), touchMode = touchMode, @@ -2604,9 +2768,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null, integerScaling = if (mode == SessionService.MODE_STEAM) integerScaling else null, stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null, + avoidNotch = if (mode == SessionService.MODE_STEAM) avoidNotch else null, mic = if (mode == SessionService.MODE_STEAM) mic else null, gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null, storageOptions = storageOptions, + storageFat32 = storageFat32, steamLibraries = steamLibraries, foundSteamLibraries = foundSteamLibraries, allFilesAccessMissing = allFilesAccessMissing, @@ -2633,13 +2799,21 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent, deckyDownloadingBinary = decky.deckyDownloadingBinary, deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running, + deckyPlugins = decky.deckyPlugins, deckyStore = decky.deckyStore, deckyStoreFailed = decky.deckyStoreFailed, ), ModeSettingsActions( onIntegration = ::configureIntegration, onIntegrationAppInfo = ::openAppInfo, onIntegrationLocation = ::openWifiDiscoverySettings, - onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value }, - onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, + onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); loadResolutions(mode) }, + onResolutionPortrait = { value -> SessionPrefs.setResolutionChoice(this, mode, value, portrait = true); loadResolutions(mode) }, + onHdr = { on -> com.droiddeck.launcher.session.SessionHdr.set(this, mode, on); hdrOn = on }, + onZeroCopy = { on -> + SessionPrefs.setZeroCopy(this, mode, on); zeroCopyOn = on + if (com.droiddeck.launcher.wayland.CompositorHost.isStarted && !SessionState.hdr && + SessionPrefs.prefMode(SessionState.mode) == SessionPrefs.prefMode(mode)) + com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetZeroCopy(on) + }, onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) }, onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m }, onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct }, @@ -2666,6 +2840,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onPicturePosition = { value -> SessionPrefs.setPicturePosition(this, value); picturePosition = value }, onIntegerScaling = { on -> SessionPrefs.setIntegerScaling(this, on); integerScaling = on }, onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on }, + onAvoidNotch = { on -> SessionPrefs.setAvoidNotch(this, on); avoidNotch = on }, onMic = { on -> SessionPrefs.setMicEnabled(this, on) mic = on @@ -2735,6 +2910,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet decky.deckyInstalled = null decky.deckySupervisor = false }, + onDeckyStoreRefresh = { decky.refreshStore() }, + onDeckyStoreInstall = { plugin -> decky.installStorePlugin(plugin) }, + onDeckyRemove = { plugin -> decky.removePlugin(plugin) }, onPickDeckyPluginZip = { pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.main_pick_decky_zip))) }, @@ -2964,11 +3142,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet }, "shader-precache").start() } + private fun loadResolutions(mode: String) { + val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this) + resolution = SessionPrefs.resolutionStored(this, mode, panel, false) + resolutionPortrait = SessionPrefs.resolutionStored(this, mode, panel, true) + } + private fun loadModeSettings(mode: String) { pipAutoEnter = SessionPrefs.pipAutoEnter(this) unfoldedControls = SessionPrefs.unfoldedControls(this) unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) - resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) + loadResolutions(mode) fexPreset = SessionPrefs.fexPreset(this) forceSsbs = SessionPrefs.forceSsbs(this) fastSync = SessionPrefs.fastSync(this) @@ -2983,9 +3167,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet startupSession = SessionPrefs.startupSession(this) loadBootMovie() hdrOn = SessionPrefs.hdr(this, mode) + zeroCopyOn = SessionPrefs.zeroCopy(this, mode) upscaler = SessionPrefs.upscaler(this) upscaleSharpness = SessionPrefs.upscaleSharpness(this) - hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason + hdrReason = com.droiddeck.launcher.wayland.HdrSupport.blocked(this) + hdrDisplay = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason == null touchMode = SessionPrefs.touchMode(this) if (!SessionPrefs.penSeen(this) && com.droiddeck.launcher.input.PenStream.penConnected()) SessionPrefs.setPenSeen(this) pen = SessionPrefs.pen(this).takeIf { SessionPrefs.penSeen(this) } @@ -2998,6 +3184,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet picturePosition = SessionPrefs.picturePosition(this) integerScaling = SessionPrefs.integerScaling(this) stretch16x9 = SessionPrefs.stretch16x9(this) + avoidNotch = SessionPrefs.avoidNotch(this) mic = SessionPrefs.micEnabled(this) refreshWifiDiscovery() gameStorage = SessionPrefs.gameStorage(this) @@ -3008,14 +3195,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet Thread({ drivers.refreshDrivers() val storage = GameStorage.options(this) + val fat32 = GameStorage.effective(this)?.path?.let(GameStorage::isFat32) == true val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this) ui.post { storageOptions = storage + storageFat32 = fat32 if (mode == SessionService.MODE_STEAM) { decky.deckyInstalled = deckyInstalled decky.deckySupervisor = deckySupervisor decky.refreshDecky() + decky.refreshPlugins() } fetchAddedGameArt() } @@ -3032,6 +3222,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } SessionPrefs.setGameStorage(this, path, label) gameStorage = path + storageFat32 = GameStorage.effective(this)?.path?.let(GameStorage::isFat32) == true + if (storageFat32) android.widget.Toast.makeText(this, R.string.main_storage_fat32, android.widget.Toast.LENGTH_LONG).show() checkUsbLink() if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries() } @@ -3130,6 +3322,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this) removalPending = LinuxRuntimeInstaller.hasRemovalPending(this) ui.post { autoUpdateRuntime() } + Thread({ com.droiddeck.launcher.session.Onboarding.recheck(this) }, "onboarding-recheck").start() frameGenLabel = FrameGen.label(this) romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() } logsEnabled = SessionPrefs.logsEnabled(this) @@ -3255,7 +3448,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet install(release) } - private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean { + private fun startSession(intent: Intent, steamSession: Boolean = false, queueIfBlocked: Boolean = false): Boolean { if (busy || LinuxRuntimeInstaller.isBusy()) return false if (SessionState.installing != null && !SessionState.running) { android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show() @@ -3267,6 +3460,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } refreshPhantomStatus() if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) { + if (queueIfBlocked) queuedLaunch.queue(intent, System.currentTimeMillis()) showPhantomGate = true return false } @@ -3276,8 +3470,64 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet return true } + private var notificationsDone: ((Boolean) -> Unit)? = null + + private fun ensureNotifications(done: (Boolean) -> Unit) { + if (WirelessAdbPairingService.notificationsEnabled(this)) { + done(true) + return + } + if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { + notificationsDone = done + requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_NOTIFICATIONS) + return + } + openNotificationSettings() + done(false) + } + + private fun openNotificationSettings() { + android.widget.Toast.makeText(this, R.string.gate_notifications_toast, android.widget.Toast.LENGTH_LONG).show() + val appAllowed = getSystemService(android.app.NotificationManager::class.java)?.areNotificationsEnabled() != false + val intent = if (appAllowed && WirelessAdbPairingService.channelBlocked(this)) { + Intent(android.provider.Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS) + .putExtra(android.provider.Settings.EXTRA_CHANNEL_ID, WirelessAdbPairingService.channelId()) + } else { + Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS) + } + startActivity(intent.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode != REQUEST_NOTIFICATIONS) return + val done = notificationsDone ?: return + notificationsDone = null + val granted = WirelessAdbPairingService.notificationsEnabled(this) + if (!granted) openNotificationSettings() + done(granted) + } + + private val queuedLaunch = com.droiddeck.launcher.session.QueuedLaunch(GATE_LAUNCH_MS) + private val queuedLaunchRunner = com.droiddeck.launcher.session.QueuedLaunchRunner( + queue = queuedLaunch, + now = System::currentTimeMillis, + blocked = { PhantomProcessLimit.blocksSteam(phantomProcessStatus) }, + busy = ::steamStartBusy, + schedule = { delay, task -> if (delay <= 0L) ui.post(task) else ui.postDelayed(task, delay) }, + unschedule = ui::removeCallbacks, + start = { launch -> startSession(launch, steamSession = true, queueIfBlocked = true) }, + retryMs = GATE_LAUNCH_RETRY_MS, + ) + + /** The conditions under which a Steam start waits instead of being refused: setup, a runtime or desktop install, or a storage cleanup. */ + private fun steamStartBusy(): Boolean = busy || LinuxRuntimeInstaller.isBusy() || com.droiddeck.launcher.session.Onboarding.settling() || + (SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning + private fun refreshPhantomStatus() { phantomProcessStatus = PhantomProcessLimit.read(this) + if (queuedLaunch.launch != null && !PhantomProcessLimit.blocksSteam(phantomProcessStatus)) showPhantomGate = false + queuedLaunchRunner.poke() adbPaired = WirelessAdbFix.hasSavedPairing(this) phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) { getString( @@ -3289,7 +3539,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private fun openDeveloperOptions(displayId: Int?) { val highlight = if (PhantomProcessLimit.hasDeveloperToggle() && - WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) null else "toggle_adb_wireless" + WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) "disable_phantom_process_monitor" else "toggle_adb_wireless" val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .apply { if (highlight != null) putExtra(":settings:fragment_args_key", highlight) } @@ -3328,13 +3578,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet Thread({ val ok = com.droiddeck.launcher.session.SettingsReset.resetAll(this, gameProfiles, scopes) ui.post { + com.droiddeck.launcher.ui.DrawerPages.load(applicationContext) if (isDestroyed) return@post com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM) if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show() com.droiddeck.launcher.ui.Motion.refresh(this) com.droiddeck.launcher.ui.DeveloperTools.load(this) com.droiddeck.launcher.ui.NavTabs.load(this) - if (!switchLauncherIcon(LauncherIcon.DARK)) recreate() + if (!switchLauncherIcon(LauncherIcon.DARK)) restartLauncher() } }, "reset-settings").start() } @@ -3350,18 +3601,24 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private fun install(release: LinuxRuntimeInstaller.Release) { com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release) - followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) } + followRuntimeOperation(onboarding = true) { listener -> LinuxRuntimeInstaller.install(this, release, listener) } } - private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) { + private fun followRuntimeOperation(onboarding: Boolean = false, run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) { busy = true failed = false 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 -> + if (onboarding) com.droiddeck.launcher.session.Onboarding.report(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, s, p) ui.post { stage = s; percent = p } }) + if (onboarding) { + if (ok == false) com.droiddeck.launcher.session.Onboarding.fail(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, LinuxRuntimeInstaller.removalError() ?: "") + else com.droiddeck.launcher.session.Onboarding.finish(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME) + } + com.droiddeck.launcher.session.Onboarding.recheck(this) ui.post { busy = false if (ok != null) failed = !ok @@ -3370,7 +3627,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } refresh() com.droiddeck.launcher.agent.AgentHost.refresh(this) - if (ok == true && LinuxRuntime.isInstalled(this)) protons.checkUpdates() + if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() } } }, "runtime-operation").start() } @@ -3381,9 +3638,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (installed != null) com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this) if (release.version == installed) return if (installed == null && (OfflineMode.enabled(this) || !com.droiddeck.launcher.core.DeviceSupport.canDraw(this) || - !com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.unfavourable(this))) return + !com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.firstRunHeldBack(this))) return if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) { Log.i(TAG, "runtime: installing ${release.version} over ${installed ?: "nothing"} by itself") + if (installed == null) protons.prefetchOwn() install(release) } } @@ -3400,7 +3658,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } companion object { + private const val REQUEST_NOTIFICATIONS = 7103 + private const val EXTRA_RESTARTED = "com.droiddeck.launcher.extra.RESTARTED" private const val STATE_HOME_CHOICE_OPEN = "home_choice_open" + private const val STATE_PENDING_GATE_LAUNCH = "pending_gate_launch" + private const val STATE_PENDING_GATE_LAUNCH_AT = "pending_gate_launch_at" + private const val GATE_LAUNCH_MS = 15 * 60_000L + private const val GATE_LAUNCH_RETRY_MS = 2_000L private const val KEY_PENDING_SESSION_LOG_EXPORT = "pending_session_log_export" private const val STATE_GAME_SPACE_OFFERED = "game_space_offered" private const val TAG = "MainActivity" diff --git a/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt b/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt index 886f5f0e89..967ba6ee47 100644 --- a/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/HomeWidgets.kt @@ -118,12 +118,18 @@ object HomeWidgets { if (live.size != parsed.size) save(context) } + private val listeners: MutableSet = java.util.Collections.newSetFromMap(java.util.IdentityHashMap()) + fun startListening(context: Context) { + listeners.add(context) load(context) runCatching { host(context).startListening() } } + // A restarted launcher starts before the old one stops; the host keeps listening until the last owner stops. fun stopListening(context: Context) { + listeners.remove(context) + if (listeners.isNotEmpty()) return runCatching { host(context).stopListening() } } diff --git a/app/src/main/java/com/droiddeck/launcher/LauncherHandoff.kt b/app/src/main/java/com/droiddeck/launcher/LauncherHandoff.kt new file mode 100644 index 0000000000..2284a531c8 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/LauncherHandoff.kt @@ -0,0 +1,27 @@ +package com.droiddeck.launcher + +import android.os.Bundle +import android.os.SystemClock + +/** + * State a restarting launcher passes to its replacement inside this process. Intent extras are not used + * because FrontEndActivity is exported and any app could fill them. + */ +internal object LauncherHandoff { + private const val LIFETIME_MS = 10_000L + private var state: Bundle? = null + private var at = 0L + + @Synchronized + fun put(carried: Bundle) { + state = carried + at = SystemClock.elapsedRealtime() + } + + @Synchronized + fun take(): Bundle? { + val carried = state + state = null + return carried?.takeIf { SystemClock.elapsedRealtime() - at <= LIFETIME_MS } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt b/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt index 5632c08546..8347bb65c4 100644 --- a/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/PairingGuideActivity.kt @@ -93,6 +93,14 @@ class PairingGuideActivity : ComponentActivity() { launchPending = true } + override fun onDestroy() { + super.onDestroy() + val stage = WirelessAdbPairingService.stage.value + if (isFinishing && (stage is WirelessAdbPairingService.Stage.Waiting || stage is WirelessAdbPairingService.Stage.CodeNeeded)) { + WirelessAdbPairingService.cancel(this) + } + } + override fun onResume() { super.onResume() if (!launchPending) return diff --git a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt index aaaa2cf34f..bb12dd31af 100644 --- a/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ProtonMenu.kt @@ -8,7 +8,9 @@ import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.droiddeck.launcher.session.ExperimentalProtons +import com.droiddeck.launcher.session.Onboarding import com.droiddeck.launcher.session.ProtonExtras +import com.droiddeck.launcher.session.SteamClientPrefetch import com.droiddeck.launcher.ui.ProtonRow import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.SessionPhase @@ -60,10 +62,15 @@ internal class ProtonMenu( Thread({ val problem = runCatching { installer(tool) { label, value -> + if (tool.id == ProtonExtras.OWN) Onboarding.report(Onboarding.Step.PROTON, label, value) ui.post { protonStage = label; protonPercent = value } } }.getOrElse { it.message ?: it.javaClass.simpleName } if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false) + if (tool.id == ProtonExtras.OWN) { + if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem) + Onboarding.recheck(activity) + } ui.post { protonProblem = problem protonBusyId = null @@ -170,16 +177,46 @@ internal class ProtonMenu( Operation.checking.set(false) } ensureAutoUpdates() + ensureSteamClient() } if (!published) Operation.checking.set(false) }, "proton-updates").start() } + /** Downloads the DroidDeck Proton archive while the runtime installs; the install step later finds it whole. */ + fun prefetchOwn() { + val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN } + if (ProtonExtras.declined(activity) || ProtonExtras.installedAll(activity, tool).isNotEmpty() || + ProtonExtras.installInProgress || !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity)) return + Thread({ + val problem = runCatching { + ProtonExtras.prefetch(activity, tool) { label, value -> Onboarding.report(Onboarding.Step.PROTON, label, value) } + }.getOrElse { it.message ?: it.javaClass.simpleName } + if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem) + Onboarding.recheck(activity) + ui.post { ensureAutoUpdates() } + }, "proton-prefetch").start() + } + + /** Fetches Steam's client in the background once the runtime exists, so the first Play does not wait for it. */ + fun ensureSteamClient() { + if (activity.isFinishing || activity.isDestroyed || !idle() || SessionState.running || LinuxRuntimeInstaller.isBusy() || + SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) || + !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity) || SteamClientPrefetch.running()) return + SteamClientPrefetch.start( + activity, + { mb -> activity.getString(if (mb > 0) R.string.onboarding_steam_downloading_mb else R.string.onboarding_steam_downloading, mb) }, + activity.getString(R.string.onboarding_steam_failed), + ) + } + internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) { if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null || - ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() || + ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() || SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || - !LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return + !LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity)) return + val firstInstall = !ProtonExtras.declined(activity) && ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).isEmpty() + if (if (firstInstall) AutoComponents.firstRunHeldBack(activity) else AutoComponents.unfavourable(activity)) return if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) { protonBusyId = ProtonExtras.OWN protonProblem = null diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index be228331ce..7deb31a83e 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -77,6 +77,7 @@ import com.droiddeck.launcher.input.KeyboardHost import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.SessionClipboard import com.droiddeck.launcher.input.OnScreenControls +import com.droiddeck.launcher.input.OnScreenLayout import com.droiddeck.launcher.input.InputRouter import com.droiddeck.launcher.input.InputOutput import com.droiddeck.launcher.input.InputCommand @@ -109,6 +110,7 @@ import com.droiddeck.launcher.input.TouchpadGestures import com.droiddeck.launcher.input.TouchscreenGestures import com.droiddeck.launcher.input.ScrollTouchGestures import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.ContentCadence import com.droiddeck.launcher.session.LoadingState import com.droiddeck.launcher.hud.DroidDeckHudConfig import com.droiddeck.launcher.hud.DroidDeckHudHost @@ -152,6 +154,8 @@ import com.droiddeck.launcher.session.ComponentsManager import com.droiddeck.launcher.session.LatestRequestCoordinator import com.droiddeck.launcher.ui.SessionDrawerPage import com.droiddeck.launcher.ui.sessionDrawerPages +import com.droiddeck.launcher.ui.strip +import com.droiddeck.launcher.ui.tabFor import com.droiddeck.launcher.ui.step import kotlin.math.abs @@ -175,6 +179,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var quickButtons by mutableStateOf>(emptyMap()) private var picturePosition by mutableStateOf("center") private var integerScaling by mutableStateOf(false) + private var avoidNotch = false + + private fun applyNotchInset(insets: android.view.WindowInsets? = window.decorView.rootWindowInsets) { + if (!::sessionRoot.isInitialized) return + val cutout = if (avoidNotch && Build.VERSION.SDK_INT >= 28 && SessionState.mode == SessionService.MODE_STEAM && + !pipUi && !isInPictureInPictureMode && glassesScreen == null && bottomGame == null && !activeCardboard.enabled) + insets?.displayCutout else null + val left = cutout?.safeInsetLeft ?: 0 + val top = cutout?.safeInsetTop ?: 0 + val right = cutout?.safeInsetRight ?: 0 + val bottom = cutout?.safeInsetBottom ?: 0 + if (sessionRoot.paddingLeft == left && sessionRoot.paddingTop == top && + sessionRoot.paddingRight == right && sessionRoot.paddingBottom == bottom) return + sessionRoot.setPadding(left, top, right, bottom) + uiHandler.post { applyUnfoldedControls() } + } + + private fun rootContentWidth() = sessionRoot.width - sessionRoot.paddingLeft - sessionRoot.paddingRight + + private fun rootContentHeight() = sessionRoot.height - sessionRoot.paddingTop - sessionRoot.paddingBottom + + private inline fun inSurfaceSpace(event: MotionEvent, block: () -> T): T { + val dx = if (outputView() === surfaceView) -surfaceView.left.toFloat() else 0f + val dy = if (outputView() === surfaceView) -surfaceView.top.toFloat() else 0f + if (dx == 0f && dy == 0f) return block() + event.offsetLocation(dx, dy) + try { + return block() + } finally { + event.offsetLocation(-dx, -dy) + } + } private fun applyGameAlignment() { if (!CompositorHost.isStarted) return @@ -210,9 +246,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun key(code: Int, down: Boolean) { heldKeys.set(4, code, down) } override fun button(code: Int, down: Boolean) { heldButtons.set(4, code, down) } override fun pointer(dx: Float, dy: Float) { - if (Looper.myLooper() == Looper.getMainLooper()) moveInputPointer(dx, dy) - else uiHandler.post { - if (resumed && !SessionState.suspended && !pipUi && !drawerOpen && !inputSettingsOpen) + if (Looper.myLooper() == Looper.getMainLooper()) { + if (!menuOwnsController) moveInputPointer(dx, dy) + } else uiHandler.post { + if (resumed && !SessionState.suspended && !pipUi && !menuOwnsController && !inputSettingsOpen) moveInputPointer(dx, dy) } } @@ -245,7 +282,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null private var padMotion: com.droiddeck.launcher.input.PadMotion? = null private var resumed by mutableStateOf(false) - private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion(); openDeckRing("deck pad changed"); applyUnfoldedControls(); leaveDeckPanel() } } + private val deckPadListener: () -> Unit = { + uiHandler.post { + updatePadMotion() + openDeckRing("deck pad changed") + onScreenControls?.reload() + bottomInputControls?.reload() + applyUnfoldedControls() + leaveDeckPanel() + } + } private fun openDeckRing(why: String) { val deck = SessionState.deckPad @@ -306,7 +352,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK) private var relativeMouseMode by mutableIntStateOf(0) @Volatile private var appliedRelativeMouseMode: Int? = null - private val agentReadyListener: () -> Unit = { relativeMouseRetries = 0; requestRelativeMouse() } + private val agentReadyListener: () -> Unit = { + relativeMouseRetries = 0 + requestRelativeMouse() + appliedOverlayPlanes = null + overlayPlanesRetries = 0 + requestOverlayPlanes() + } private val appTextFocus get() = wowChat.request != null private val wowChat by lazy { com.droiddeck.launcher.ui.WowChat(this, ::sendWowChat, ::cancelWowChat, ::readGameField) } private var wowChatBottom: SecondScreenPresentation? = null @@ -496,6 +548,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde drawerOpenState = value if (!value && drawerDocked) closeDockedMenu() } + private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController) + private val dockedTouchOnly: Boolean get() = drawerOpen && drawerDocked && !dockedMenuController + private val menuOwnsController: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuOwnsController(drawerOpen, drawerDocked, dockedMenuController) private var quitFrom by mutableStateOf(null) private var quitFlooded = false private var leaving by mutableStateOf(false) @@ -510,6 +565,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun fpsLimitKey(): String? = if (SessionState.running) SessionPrefs.fpsLimitKey(SessionState.mode, SessionState.gameId) else SessionPrefs.fpsLimitKey(intent.getStringExtra(SessionService.EXTRA_MODE), intent.getStringExtra(SessionService.EXTRA_GAME_ID)) private var blackFrameInsertion by mutableStateOf(false) + private var hdrWanted by mutableStateOf(false) + private var hdrAvailable by mutableStateOf(false) private fun noSteamSession(): Boolean = (SessionState.mode == SessionService.MODE_RUN && SessionState.program in setOf( @@ -537,6 +594,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER) private var drawerControllerActive by mutableStateOf(false) private var backHold by mutableStateOf(true) + private var dockedMenuController by mutableStateOf(false) + private var sessionOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) + private var dualScreenSessionMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO) private var backActionsInverted by mutableStateOf(false) private var backDoubleTapMs by mutableStateOf(500) private var lowLatency by mutableStateOf(true) @@ -610,6 +670,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde syncActiveScreenEffectsProfile() } } + private val hdrPrefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key -> + if (key == SessionPrefs.hdrKey(hdrPrefMode())) uiHandler.post { hdrWanted = SessionPrefs.hdr(this, hdrPrefMode()) } + } private val shortcutPrefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == null || key == PhysicalShortcuts.KEY) { physicalShortcuts.bindings = PhysicalShortcuts.read(this) @@ -647,6 +710,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) private var steamDownloadsInBackground by mutableStateOf(false) private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO) + private var oscRearButtons by mutableStateOf(false) + private var oscTrackpads by mutableStateOf(false) private var onScreenButtonsVisible by mutableStateOf(false) private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode) private var secondScreenDisplays by mutableStateOf>(emptyList()) @@ -782,10 +847,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty() SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM))) SessionState.secondScreenAutoOpened = false + SessionState.bottomMenu = false SessionState.secondScreenProvisional = false SessionState.secondScreenAutomatic = false - SessionState.gameOnBottom = false - gameOnBottom = false + SessionState.gameOnBottom = SessionPrefs.dualScreenSessionMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED + gameOnBottom = SessionState.gameOnBottom } if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) { SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) @@ -809,9 +875,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde cornerTap = SessionPrefs.drawerCornerTap(this) applyOutputPacing() if (!SessionState.running) { - SessionState.followScreen = followChoice() - SessionState.followScale = followScale() + SessionState.followScales = SessionPrefs.followScales(this, displayMode(), + com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) } + applyFollowChoice() applyFollowOrientation(resources.configuration) goFullscreen() volumeControlStream = android.media.AudioManager.STREAM_MUSIC @@ -839,6 +906,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde else super.onResolvePointerIcon(event, pointerIndex) } sessionRoot = root + window.decorView.setOnApplyWindowInsetsListener { view, insets -> + applyNotchInset(insets) + view.onApplyWindowInsets(insets) + } surfaceView = SurfaceView(this) surfaceView.holder.addCallback(this) root.addView(surfaceView) @@ -866,11 +937,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } } steamController = SteamControllerBle(this, inputRouter).also { it.start() } - if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED && - !SessionPrefs.bluetoothAsked(this)) { - SessionPrefs.setBluetoothAsked(this) - requestPermissions(arrayOf(BLUETOOTH_CONNECT), REQUEST_BLUETOOTH) - } 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 @@ -883,7 +949,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde controls.onTouchMiss = miss@{ event -> if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss event.offsetLocation(controls.left - surfaceView.left.toFloat(), controls.top - surfaceView.top.toFloat()) - onTouchEvent(event) + handleTouch(event) } root.addView(controls) } @@ -928,7 +994,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde false } else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) { false - } else onTouchEvent(event) + } else handleTouch(event) } padMouse = PadMouse(padMouseListener) bridge.setTouchRoute(object : PadBridge.TouchRoute { @@ -1038,6 +1104,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde updateOnScreenControls() WaylandCompositor.setFirstFrameListener(firstFrameListener) WaylandCompositor.setPointerLockListener(pointerLockListener) + WaylandCompositor.setOverlayPlanesListener(overlayPlanesListener) + WaylandCompositor.setRefreshTargetListener(refreshTargetListener) + WaylandCompositor.setContentRateListener(contentRateListener) SessionEvents.markReadyIfPossible() SessionState.endListener = endListener onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { @@ -1046,6 +1115,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde when { ::loading.isInitialized && loading.ended -> finish() inputSettingsOpen -> inputSettingsOpen = false + dockedTouchOnly -> routeBackAction() drawerOpen -> drawerOpen = false achievementsOpen -> closeAchievements() pcKeyboardOpen -> pcKeyboardOpen = false @@ -1074,6 +1144,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } val uiPointer = appUiOwnsPointer() + val cursorHidden = cursorHiddenByUi() androidx.compose.runtime.SideEffect { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, (drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING) @@ -1124,7 +1195,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } else { com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) { - CursorOverlay({ cursorPos }, cursorVisible && (!uiPointer || onlyPcKeyboardOpen()) && !bottomOutputActive, + CursorOverlay({ cursorPos }, cursorVisible && (!cursorHidden || onlyPcKeyboardOpen()) && !bottomOutputActive, resources.displayMetrics.density, cursorImage, cursorHotX, cursorHotY, cursorImageScale) if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity) @@ -1241,9 +1312,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) } } } - LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) { + LaunchedEffect(drawerOpen, menuOwnsController, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) { updateOnScreenControls() - padBridge?.setInputEnabled(resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended) + padBridge?.setInputEnabled(resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended) if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || appTextFocus || SessionState.suspended) { backQamInput.cancel() com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity) @@ -1255,7 +1326,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() }, onChanged = { controllerSettings = ControllerPrefs.read(this@SessionActivity) - oscMode = SessionPrefs.oscMode(this@SessionActivity) + oscMode = SessionPrefs.oscMode(this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM) padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this@SessionActivity)) joyConVr?.refresh() onScreenControls?.reload() @@ -1295,13 +1366,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onDismiss = { gestureSettingsOpen = false }, onSaved = { gestureSettingsOpen = false; refreshGestureConfig() }, ) - androidx.compose.runtime.LaunchedEffect(drawerOpen) { + androidx.compose.runtime.LaunchedEffect(drawerOpen, menuOwnsController) { if (drawerOpen) { syncLossless() - releasePads() - androidx.compose.runtime.withFrameNanos { } - val requested = focusDrawer() - Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked") + if (menuOwnsController) { + releasePads() + androidx.compose.runtime.withFrameNanos { } + val requested = focusDrawer() + Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked") + } else { + releaseDrawerDirection() + } } else { releaseDrawerDirection() } @@ -1360,7 +1435,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!SessionState.manualPause && !SessionState.suspended) pauseAnimated = false } SessionPausedOverlay( - suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed || SessionState.manualPause), + suspended = (SessionState.suspended || SessionState.manualPause) && (!autoResume || SessionState.resumeFailed || SessionState.manualPause), engaged = SessionState.resumeRequested || SessionState.resuming, failures = SessionState.resumeFailures, frame = pausedFrame, @@ -1459,6 +1534,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde fexPreset = fexPreset, secondScreenMode = secondScreenMode, secondScreenNone = !bottomOutputActive && !dockDrawer(), + dualScreenMode = dualScreenSessionMode, + onDualScreenMode = ::chooseDualScreenSessionMode, gameOnBottom = bottomOutputActive, gameSwapAvailable = bottomSwapAvailable, gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay) @@ -1469,6 +1546,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde secondScreenDisplays = secondScreenDisplays, selectedSecondScreenDisplay = selectedSecondScreenDisplay, onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() }, + onHudOnlyDuringGame = { on -> + SessionPrefs.setHudOnlyDuringGame(this@SessionActivity, on) + hud.refresh() + }, onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this@SessionActivity, on) gpuClockPin = on @@ -1645,6 +1726,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde blackFrameInsertion = on CompositorHost.setBlackFrameInsertion(on, refreshHz(), outputFpsLimit()) }, + hdr = hdrWanted, + hdrAvailable = hdrAvailable, + onHdr = { on -> com.droiddeck.launcher.session.SessionHdr.set(this@SessionActivity, hdrPrefMode(), on); hdrWanted = on }, onFrameGenPick = { mode -> val appId = frameGenTargetGameId() @@ -1685,12 +1769,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(id)) com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id)) padType = id + onScreenControls?.reload() + applyUnfoldedControls() + unfoldedPanel?.reload() + bottomInputControls?.reload() }, backHold = backHold, onBackHold = { on -> SessionPrefs.setBackHold(this@SessionActivity, on) backHold = on }, + dockedMenuController = dockedMenuController, + onDockedMenuController = { on -> + SessionPrefs.setDockedMenuController(this@SessionActivity, on) + dockedMenuController = on + if (!on && drawerDocked) drawerControllerActive = false + }, backActionsInverted = backActionsInverted, backDoubleTapMs = backDoubleTapMs, onBackDoubleTapMs = { ms -> @@ -1759,6 +1853,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde setRelativeMouse(mode) }, onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() }, + onSelectMenuMode = ::pickMenuMode, onSecondScreenMode = { mode -> if (docked) drawerOpen = false pickSecondScreenMode(mode) @@ -1782,6 +1877,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pipAutoEnter = pipAutoEnter, onPip = { pip.enter() }, onPause = ::pauseNow, + paused = SessionState.suspended || SessionState.manualPause, + onResume = { SessionService.resume(this@SessionActivity) }, + orientation = sessionOrientation, + onOrientation = { value -> + SessionPrefs.setOrientation(this@SessionActivity, value) + sessionOrientation = value + applyFollowOrientation(resources.configuration) + }, onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this@SessionActivity, on) pipAutoEnter = on @@ -1796,6 +1899,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde primaryInputLayout?.let { com.droiddeck.launcher.input.InputLibraries.setAdaptiveSticks(this@SessionActivity, it.id, on) } refreshInputProfile() }, + showFloatingSteamControls = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad && unfoldedPanel == null && + oscMode != SessionPrefs.OSC_NEVER && oscMode != SessionPrefs.OSC_STEAM_QAM && + !steamTouchInUse && OnScreenLayout.supportsFloatingSteamControls(padType, primaryInputLayout), + oscRearButtons = oscRearButtons, + oscTrackpads = oscTrackpads, + onOscRearButtons = { shown -> + SessionPrefs.setOscRearButtons(this@SessionActivity, shown) + oscRearButtons = shown + onScreenControls?.reload() + bottomInputControls?.reload() + }, + onOscTrackpads = { shown -> + SessionPrefs.setOscTrackpads(this@SessionActivity, shown) + oscTrackpads = shown + onScreenControls?.reload() + bottomInputControls?.reload() + }, quickButtons = quickButtons.takeIf { unfoldedPanel != null || oscMode != SessionPrefs.OSC_NEVER && !steamTouchInUse }.orEmpty(), @@ -1862,7 +1982,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun sendSteamGuide() { - drawerOpen = false + if (!dockedTouchOnly) drawerOpen = false padBridge?.triggerSteamMenu() } @@ -1909,7 +2029,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun triggerSteamQam() { - drawerOpen = false + if (!dockedTouchOnly) drawerOpen = false padBridge?.triggerQam() } @@ -1998,7 +2118,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun performBackAction(double: Boolean) { val isSteam = SessionState.mode == SessionService.MODE_STEAM val opensQam = isSteam && (double xor backActionsInverted) - if (opensQam) triggerSteamQam() else drawerOpen = !drawerOpen + if (opensQam) triggerSteamQam() else if (!dockedTouchOnly) drawerOpen = !drawerOpen } private fun handleHomeGuideIntent(incoming: Intent?) { @@ -2489,9 +2609,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) picturePosition = SessionPrefs.picturePosition(this) integerScaling = SessionPrefs.integerScaling(this) + avoidNotch = SessionPrefs.avoidNotch(this) + applyNotchInset() hudOn = SessionPrefs.hudEnabled(this) gpuClockPin = gpuClockHeld() blackFrameInsertion = SessionPrefs.blackFrameInsertion(this) + hdrWanted = SessionPrefs.hdr(this, hdrPrefMode()) + hdrAvailable = HdrSupport.probe(this, glassesScreen?.display).reason == null hudConfig = DroidDeckHudConfig.load(this) hudColor = SessionPrefs.hudColor(this) hudOpacity = SessionPrefs.hudOpacity(this) @@ -2534,8 +2658,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde fexPreset = SessionPrefs.fexPreset(this) suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this) - oscMode = SessionPrefs.oscMode(this) + oscMode = SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM) + oscRearButtons = SessionPrefs.oscRearButtons(this) + oscTrackpads = SessionPrefs.oscTrackpads(this) backHold = SessionPrefs.backHold(this) + dockedMenuController = SessionPrefs.dockedMenuController(this) + sessionOrientation = SessionPrefs.orientation(this) + dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this) backActionsInverted = SessionPrefs.backActionsInverted(this) physicalShortcuts.bindings = PhysicalShortcuts.read(this) backDoubleTapMs = SessionPrefs.backDoubleTapMs(this) @@ -2747,6 +2876,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde .onFailure { Log.e(TAG, "Could not update game environment", it) } }, "game-env-publish").start() applyGameAlignment() + val attached = CompositorHost.isStarted + val probe = if (attached) null else HdrSupport.probe(this, glassesScreen?.display) + if (probe != null) SessionState.hdrDisplay = probe.reason == null val activeProfileId = currentScreenEffectsProfileId() val activeUpscaler = SessionPrefs.screenEffectsUpscaler(this, activeProfileId) val activeEffects = SessionPrefs.screenEffects(this, activeProfileId) @@ -2766,27 +2898,31 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde Log.w(TAG, "could not point the compositor's log at $waylandLog", e) } } - if (!CompositorHost.isStarted) { - val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) - val probe = HdrSupport.probe(this, glassesScreen?.display) + val mode = hdrPrefMode() + if (probe != null) { WaylandCompositor.nativeSetHdrDisplay( probe.displayId, probe.name, probe.formats, probe.hdr10, probe.maxLuminance, probe.maxAverageLuminance, probe.minLuminance, probe.ratioAvailable, probe.ratio, Build.VERSION.SDK_INT, ) - val wanted = SessionPrefs.hdr(this, mode) - val on = wanted && probe.reason == null - SessionState.hdr = on - if (on) { + val capable = HdrSupport.blocked(this) == null + val tonemap = capable && probe.reason != null + SessionState.hdrCapable = capable + if (capable) { try { android.system.Os.setenv("DROIDDECK_WAYLAND_HDR", "1", true) } catch (e: Exception) { Log.w(TAG, "DROIDDECK_WAYLAND_HDR", e) } - WaylandCompositor.nativeSetZeroCopy(true) } WaylandCompositor.nativeSetHdrRequest( - if (on) WaylandCompositor.HDR_MODE_ON else WaylandCompositor.HDR_MODE_OFF, - "$mode session settings" + (if (wanted && !on) " (refused: ${probe.reason})" else ""), - on, on, + if (tonemap) WaylandCompositor.HDR_MODE_TONEMAP else if (capable) WaylandCompositor.HDR_MODE_ON else WaylandCompositor.HDR_MODE_OFF, + "$mode session settings", capable, false, ) - Log.i(TAG, "hdr: " + (if (on) "on" else if (wanted) "wanted but ${probe.reason}" else "off") + " · display ${probe.formats.ifEmpty { "SDR" }}") + Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}") + } + if (!SessionState.running) { + val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode) + SessionState.hdr = on + WaylandCompositor.nativeSetHdrOutput(on) + WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode)) + Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session") } com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId") CompositorHost.startOrAttach( @@ -2858,16 +2994,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde WaylandCompositor.nativeResizeOutput(size.first, size.second) } - private fun followScale(): Float { - val mode = displayMode() - val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) - return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f - } + private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this) - private fun followChoice(): Boolean { - val mode = displayMode() - return com.droiddeck.launcher.session.SessionDisplay.isFollow( - SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))) + private fun applyFollowChoice() { + val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first } + SessionState.followScreen = scale != null + SessionState.followScale = scale ?: 1f } private fun applyFollowOrientation(config: android.content.res.Configuration) { @@ -2881,7 +3013,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionService.setActivityDisplay(this, sessionActivityDisplayId) } cancelTouchGestures() + applyFollowChoice() applyFollowOrientation(newConfig) + applyNotchInset() applyUnfoldedControls() resizeOutputForWindow(surfaceW, surfaceH) } @@ -2932,17 +3066,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun displayMode(): String = SessionPrefs.displayMode(this, intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM)) + private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted() + private fun outputSize(): Pair = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this), - resolutionChoice(), SessionPrefs.portrait(this) && !controlsBelowWanted()) + resolutionChoice(), portraitOutput()) - private fun resolutionChoice(): String { + private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String { val mode = displayMode() val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN && - Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode)) + Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode, portrait)) com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN - else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) + else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), portrait) } private fun refreshHz(): Float = refreshHz(null) @@ -2962,6 +3098,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde return if (capped > 1f) capped else 60f } + private fun hdrPrefMode(): String = SessionPrefs.prefMode( + if (SessionState.running) SessionState.mode + else intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, + ) + private fun blackFrameInsertionAvailable(): Boolean { // Glasses that present the game run at their own rate, uncapped, as refreshHz() reads them. glassesScreen?.display?.let { glasses -> @@ -2981,9 +3122,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun outputFpsLimit(pip: Boolean): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pip) + private var panelHeld = false + private val panelHeldCheck = Runnable { + if (!panelHeld && hasWindowFocus() && PerfMode.panelHeld(this)) { + panelHeld = true + uiHandler.removeCallbacks(panelHeldRetry) + uiHandler.postDelayed(panelHeldRetry, PANEL_HELD_RETRY_MS) + applyOutputPacing() + } + } + private val panelHeldRetry = Runnable { + if (panelHeld && !isDestroyed) { + panelHeld = false + applyOutputPacing() + } + } + private fun applyOutputPacing() { - Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(false), mirrorRefreshLimit())) + val frameGen = appliedFrameGenMode + pacedFrameGenMode = frameGen + val ownLimit = outputFpsLimit(false) + val content = PerfMode.contentRate( + PerfMode.pacedRate(ownLimit, guestFrameRate, guestRefresh, contentCadence.rate), + frameGen?.outputFactor ?: 1, frameGen?.target ?: 0, + ) + Log.i(TAG, "perf: " + PerfMode.apply(this, content, mirrorRefreshLimit(), if (ownLimit > 0) 0 else guestRefresh, panelHeld)) + uiHandler.removeCallbacks(panelHeldCheck) + if (!panelHeld) uiHandler.postDelayed(panelHeldCheck, PANEL_HELD_CHECK_MS) if (CompositorHost.isStarted) { + WaylandCompositor.nativeSetPanelRates( + if (glassesScreen == null && !bottomOutputActive) PerfMode.panelRates(this, mirrorRefreshLimit(), panelHeld) + else IntArray(0), + ) val hz = refreshHz() val changed = kotlin.math.abs(SessionState.refreshHz - hz) > 0.1f CompositorHost.updatePacing(hz, outputFpsLimit()) @@ -3149,6 +3319,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (frameGenActivityGeneration != frameGenGlobalGeneration.get()) return@runOnUiThread lossless = state if (problem != null) Toast.makeText(this, problem, Toast.LENGTH_LONG).show() + if (appliedFrameGenMode != pacedFrameGenMode) applyOutputPacing() } }, "frame-gen").start() } @@ -3209,8 +3380,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun onSessionEnded(status: Int) { ended = true - uiHandler.removeCallbacks(guardWhenRunning) - com.droiddeck.launcher.session.KeepTopActivity.release() ++steamVrRequestGeneration if (isInPictureInPictureMode) { runOnUiThread { finish() } @@ -3379,13 +3548,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun dispatchKeyEvent(event: KeyEvent): Boolean { + val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event) + if (normalized === event) return dispatchSessionKeyEvent(event) + if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { + Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}") + } + return dispatchSessionKeyEvent(normalized) + } + + private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean { if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> { val steamVolume = SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen && !SessionState.suspended && !ended && - !pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && + !pipUi && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !appTextFocus && window.decorView.hasWindowFocus() if (steamVolume) { val audio = getSystemService(android.media.AudioManager::class.java) @@ -3399,13 +3577,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (penStream.holdsKey(event) || (penSettings.mode != SessionPrefs.PEN_TOUCH && PenStream.isPenKey(event))) return penStream.onKey(event) if (appTextFocus) return super.dispatchKeyEvent(event) if (!pipUi) { - if (physicalInputBindings?.onKey(event, resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && + if (physicalInputBindings?.onKey(event, resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true if (physicalShortcuts.onKey( event, enabled = resumed && SessionState.running && !SessionState.suspended && - !(drawerOpen && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) && - !(drawerOpen && PhysicalShortcuts.isDrawerNavigationKey(event)) && + !(menuOwnsController && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) && + !(menuOwnsController && PhysicalShortcuts.isDrawerNavigationKey(event)) && (event.deviceId to event.keyCode) !in resumeKeysDown && !(::loading.isInitialized && (loading.visible || loading.ended)) && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen, @@ -3413,12 +3591,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ) { action -> pendingBackAction?.let(uiHandler::removeCallbacks) pendingBackAction = null - drawerControllerActive = true + if (!dockedMenuIdle) drawerControllerActive = true Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}") when (action) { PhysicalShortcuts.Action.STEAM -> sendSteamGuide() PhysicalShortcuts.Action.QAM -> triggerSteamQam() - PhysicalShortcuts.Action.DROIDDECK -> drawerOpen = !drawerOpen + PhysicalShortcuts.Action.DROIDDECK -> if (!dockedTouchOnly) drawerOpen = !drawerOpen } }) return true } @@ -3444,7 +3622,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } if (mouseBackHandled) return true - val backToQam = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && + val backToQam = !pipUi && !appTextFocus && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen && !gestureSettingsOpen && SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen && !SessionState.suspended && padBridge?.canHoldQam() == true @@ -3457,12 +3635,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val pad = com.droiddeck.launcher.input.JoyCon.normalize(event) if (pad !== event) return dispatchKeyEvent(pad) val fromController = PadBridge.isControllerKeyEvent(event) - if (fromController && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) { + if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) { padBridge?.setInputEnabled(false) padBridge?.onKeyEvent(event) } - if (fromController && event.action == KeyEvent.ACTION_DOWN) { - if (drawerOpen && !drawerControllerActive) focusDrawer() + if (fromController && event.action == KeyEvent.ACTION_DOWN && !dockedMenuIdle) { + if (menuOwnsController && !drawerControllerActive) focusDrawer() drawerControllerActive = true } if (fromController && event.keyCode == KeyEvent.KEYCODE_BUTTON_B && ::loading.isInitialized && loading.visible && !loading.ended && !drawerOpen) { @@ -3481,7 +3659,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } val drawerShortcutKey = event.deviceId to event.keyCode if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT || event.keyCode == KeyEvent.KEYCODE_BUTTON_START) && - ((drawerOpen && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) { + ((menuOwnsController && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) { if (event.action == KeyEvent.ACTION_DOWN) { drawerShortcutKeysDown.add(drawerShortcutKey) if (event.repeatCount == 0) { @@ -3493,11 +3671,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } return true } - if (drawerOpen) { + if (drawerOpen && (menuOwnsController || (!fromController && !(dockedTouchOnly && event.keyCode == KeyEvent.KEYCODE_BACK)))) { if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { - drawerPage = sessionDrawerPages(glasses.present) - .step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) + // The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab. + val pages = sessionDrawerPages(glasses.present) + drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) releaseDrawerDirection() } return true @@ -3563,11 +3742,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { if (pipUi) return true notePress(event) - if (PadBridge.isControllerMotionEvent(event) && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) { + if (PadBridge.isControllerMotionEvent(event) && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) { padBridge?.setInputEnabled(false) padBridge?.onMotionEvent(event) } - if (drawerOpen && PadBridge.isControllerMotionEvent(event)) { + if (menuOwnsController && PadBridge.isControllerMotionEvent(event)) { if (!drawerControllerActive) focusDrawer() drawerControllerActive = true if (event.actionMasked == MotionEvent.ACTION_MOVE && @@ -3586,12 +3765,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (pen >= 0) when (routePen(event, pen)) { PenRouter.Route.TOUCH -> {} PenRouter.Route.PEN -> { - if (!appUiOwnsPointer()) return penSample(event, pen) || super.dispatchGenericMotionEvent(event) + if (!appUiOwnsPointer()) return inSurfaceSpace(event) { penSample(event, pen) } || super.dispatchGenericMotionEvent(event) if (super.dispatchGenericMotionEvent(event)) { penStream.cancel() return true } - return !touchEditorOpen && penSample(event, pen) + return !touchEditorOpen && inSurfaceSpace(event) { penSample(event, pen) } } else -> return super.dispatchGenericMotionEvent(event) } @@ -3599,10 +3778,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (appUiOwnsPointer()) { if (super.dispatchGenericMotionEvent(event)) return true if (touchEditorOpen) return false - if (onMouse(event)) return true + if (inSurfaceSpace(event) { onMouse(event) }) return true return false } - if (onMouse(event)) return true + if (inSurfaceSpace(event) { onMouse(event) }) return true } return super.dispatchGenericMotionEvent(event) } @@ -3744,6 +3923,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun closeDockedMenu() { + SessionState.bottomMenu = false drawerDocked = false val presentation = secondScreenPresentation ?: return presentation.showMenu(false) @@ -3751,8 +3931,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } - private val relativeMouseRequests = java.util.concurrent.Executors.newSingleThreadExecutor { runnable -> - Thread(runnable, "relative-mouse").apply { isDaemon = true } + private val gamescopeConvarRequests = java.util.concurrent.Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "gamescope-convar").apply { isDaemon = true } } @Volatile private var desiredRelativeMouseMode = 0 @@ -3765,7 +3945,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun requestRelativeMouse() { - runCatching { relativeMouseRequests.execute { applyRelativeMouse() } } + runCatching { gamescopeConvarRequests.execute { applyRelativeMouse() } } } private fun applyRelativeMouse() { @@ -3779,23 +3959,58 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde )) == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD val mode = com.droiddeck.launcher.input.TouchGestureConfig.gamescopeRelativeMouse(wanted, mouseAttached(), touchpadRoute) if (appliedRelativeMouseMode == mode) return - val request = org.json.JSONObject() - .put("kind", "exec") - .put("argv", org.json.JSONArray(listOf("gamescopectl", "relative_mouse", mode.toString()))) - .put("timeout", 5.0) - val result = runCatching { AgentGuest.call(this, request, 8_000, trusted = true) } - val answer = result.getOrNull() - val applied = answer?.optBoolean("ok") == true - && answer.optInt("exitCode", -1) == 0 - && !answer.optBoolean("timedOut") - if (applied) appliedRelativeMouseMode = mode - else { - Log.w(TAG, "gamescope did not take relative mouse $mode: ${result.exceptionOrNull() ?: answer}") - if (relativeMouseRetries++ < RELATIVE_MOUSE_MAX_RETRIES) uiHandler.postDelayed({ requestRelativeMouse() }, 2_000) - } + if (AgentGuest.setGamescopeConvar(this, "relative_mouse", mode)) appliedRelativeMouseMode = mode + else if (relativeMouseRetries++ < RELATIVE_MOUSE_MAX_RETRIES) uiHandler.postDelayed({ requestRelativeMouse() }, 2_000) if (desiredRelativeMouseMode != wanted) requestRelativeMouse() } + @Volatile private var desiredOverlayPlanes = -1 + @Volatile private var appliedOverlayPlanes: Int? = -1 + @Volatile private var overlayPlanesRetries = 0 + @Volatile private var guestRefresh = 0 + @Volatile private var guestFrameRate = 0 + private var pacedFrameGenMode: FrameGen.Mode? = null + private val contentCadence = ContentCadence() + private val contentRateListener = WaylandCompositor.ContentRateListener { fps -> + runOnUiThread { + if (isDestroyed) return@runOnUiThread + val changed = if (fps > 0) contentCadence.note(fps, PerfMode.panelRates(this, mirrorRefreshLimit(), panelHeld)) + else contentCadence.reset() + if (changed) { + Log.i(TAG, "perf: steady content rate " + contentCadence.rate + " fps") + applyOutputPacing() + } + } + } + private val refreshTargetListener = WaylandCompositor.RefreshTargetListener { refresh, frameRate -> + runOnUiThread { + if (isDestroyed) return@runOnUiThread + if (guestRefresh != refresh || guestFrameRate != frameRate) { + guestRefresh = refresh + guestFrameRate = frameRate + applyOutputPacing() + } + } + } + + private val overlayPlanesListener = WaylandCompositor.OverlayPlanesListener { planes -> + desiredOverlayPlanes = planes + overlayPlanesRetries = 0 + requestOverlayPlanes() + } + + private fun requestOverlayPlanes() { + runCatching { gamescopeConvarRequests.execute { applyOverlayPlanes() } } + } + + private fun applyOverlayPlanes() { + val wanted = desiredOverlayPlanes + if (appliedOverlayPlanes == wanted) return + if (AgentGuest.setGamescopeConvar(this, "wayland_overlay_planes", wanted)) appliedOverlayPlanes = wanted + else if (overlayPlanesRetries++ < RELATIVE_MOUSE_MAX_RETRIES) uiHandler.postDelayed({ requestOverlayPlanes() }, 2_000) + if (desiredOverlayPlanes != wanted) requestOverlayPlanes() + } + private fun refreshGestureConfig() { gestureConfig = com.droiddeck.launcher.input.GesturePrefs.read(this, gestureGame) directHoldBehavior = gestureConfig.directHoldBehavior @@ -4134,7 +4349,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ?: if (SessionState.gameOnBottom) bottomGameDisplay()?.displayId else null SessionState.secondScreenAutoOpened = true if (gameDisplay != null && gameDisplay != target.displayId && secondScreenDisplays.any { it.id == gameDisplay }) { - panelMode(openingPanel()) + panelMode(openingSurface()) } else { val selectionChanged = selectedSecondScreenDisplay != target.displayId selectedSecondScreenDisplay = target.displayId @@ -4153,14 +4368,69 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun openingPanel() = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this, desktopSession), SessionState.deckPad, - bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available(), desktopSession) + bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available()) + + private fun openingSurface() = openingPanel().takeIf { it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD + + private fun menuShownOnBottom() = drawerDocked && (drawerOpen || drawerPinned) + + private fun pinDockedMenu() { + if (!dockDrawer()) return + drawerLayerOpen = false + if (!openDockedMenu()) return + drawerDocked = true + drawerOpenState = false + drawerPinned = true + updateKeyboardRoute() + } + + private fun showMenuMode() { + dualControlsProvisional = false + selectSecondScreenMode(secondScreenMode.takeIf { it != SecondScreenMode.NONE } ?: SecondScreenMode.KEYBOARD_TRACKPAD) + if (secondScreenMode != SecondScreenMode.NONE) pinDockedMenu() + } + + private fun pickMenuMode() { + typingReturnMode = null + automaticPanel = false + SessionPrefs.setSecondScreenPanel(this, desktopSession, SecondScreenMode.MENU.id) + drawerOpen = true + } private fun settleDualScreenControls() { if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return dualControlsProvisional = false if (secondScreenMode == SecondScreenMode.NONE) return val wanted = openingPanel() - if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal() + if (wanted == SecondScreenMode.MENU) { + if (!menuShownOnBottom()) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal() + } else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal() + } + + private fun chooseDualScreenSessionMode(mode: String) { + if (mode !in com.droiddeck.launcher.input.DualScreen.modes || mode == dualScreenSessionMode) return + SessionPrefs.setDualScreenSessionMode(this, mode) + dualScreenSessionMode = mode + SessionState.secondScreenAutoOpened = false + val menuOnBottom = drawerDocked + val menuOnTop = drawerOpenState && !drawerDocked + if (mode == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED) { + putGameOnBottom(true) + } else if (gameOnBottom && mode != com.droiddeck.launcher.input.DualScreen.MODE_OFF) { + putGameOnBottom(false) + } + if (mode == com.droiddeck.launcher.input.DualScreen.MODE_OFF) { + if (gameOnBottom) putGameOnBottom(false) + if (secondScreenMode != SecondScreenMode.NONE || menuOnBottom) closeSecondScreen(reset = true) + if (menuOnBottom) drawerOpen = true + } else if (menuOnTop) { + // The menu moves to the second screen as the menu itself, not as one of the control panels. + SessionState.secondScreenAutoOpened = true + refreshSecondScreenDisplays() + pinDockedMenu() + return + } + refreshSecondScreenDisplays() } private fun selectSecondScreenDisplay(displayId: Int) { @@ -4181,6 +4451,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde closeSecondScreen(reset = true) return } + if (mode == SecondScreenMode.MENU) { + showMenuMode() + return + } if (secondScreenDisplays.isEmpty()) { panelMode(SecondScreenMode.NONE) return @@ -4197,7 +4471,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun showSecondScreen(requested: SecondScreenMode) { if (pipUi || !started) return - val mode = if (requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) openingPanel() else requested + val mode = when { + requested == SecondScreenMode.MENU -> + secondScreenMode.takeIf { it != SecondScreenMode.NONE && it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD + requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> openingSurface() + else -> requested + } val target = displayManager.getDisplay(selectedSecondScreenDisplay) if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) { closeSecondScreen(reset = false) @@ -4234,6 +4513,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun pickSecondScreenMode(mode: SecondScreenMode) { typingReturnMode = null automaticPanel = false + SessionState.bottomMenu = false if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id) selectSecondScreenMode(mode) } @@ -4241,7 +4521,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun bottomScreenPicker(mode: SecondScreenMode) = com.droiddeck.launcher.ui.ScreenPicker( com.droiddeck.launcher.ui.secondScreenModes(false, SessionState.deckPad, bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available()), - mode, ::pickSecondScreenMode, onMenu = { drawerOpen = true }, + mode, ::pickSecondScreenMode, onMenu = ::pickMenuMode, ) private fun secondScreenPresentation(target: Display) = SecondScreenPresentation( @@ -4441,19 +4721,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun controlsBelowWanted(): Boolean { if (!::sessionRoot.isInitialized || glassesScreen != null || bottomGame != null || cardboard.enabled) return false - return SessionPrefs.controlsBelowWanted(this, SessionState.mode, sessionRoot.width, sessionRoot.height, + return SessionPrefs.controlsBelowWanted(this, SessionState.mode, rootContentWidth(), rootContentHeight(), pipUi || isInPictureInPictureMode) } private fun applyUnfoldedControls() { if (!::sessionRoot.isInitialized) return - val width = sessionRoot.width - val height = sessionRoot.height + val width = rootContentWidth() + val height = rootContentHeight() val wanted = controlsBelowWanted() val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let { it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt() } ?: 0 - val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow) + val outputAspect = if (!wanted || SessionState.followScreen) 0f + else outputSize().let { it.first.toFloat() / it.second.coerceAtLeast(1) } + val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, outputAspect) else FrameLayout.LayoutParams.MATCH_PARENT val params = surfaceView.layoutParams as FrameLayout.LayoutParams if (params.height != gameHeight) { @@ -4462,7 +4744,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde else "unfolded controls: game full screen") } val portrait = !com.droiddeck.launcher.session.SessionDisplay.foldable(this) - val dock = if (SessionState.deckPad) com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD]) + val kit = com.droiddeck.launcher.input.PadKit.forOverlay(this, primaryInputLayout) + val dock = if (SessionState.deckPad && kit?.steam != false) + com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD]) else com.droiddeck.launcher.input.OnScreenLayout.Dock(portrait, false) var panel = unfoldedPanel if (panel != null && (!wanted || panel.dock != dock)) { @@ -4663,6 +4947,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun dropDockedDrawer() { + if (drawerDocked && (drawerOpenState || drawerPinned)) SessionState.bottomMenu = true drawerPinned = false if (!drawerDocked) return drawerDocked = false @@ -4681,6 +4966,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (reset) { panelMode(SecondScreenMode.NONE) automaticPanel = false + SessionState.bottomMenu = false } } @@ -4877,7 +5163,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde secondScreenPresentation?.controlsView, swappedInputSurface, ).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) } - override fun onTouchEvent(event: MotionEvent): Boolean { + override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) } + + private fun handleTouch(event: MotionEvent): Boolean { val pen = PenStream.penIndex(event) val penRouted = if (pen >= 0) routePen(event, pen).takeIf { it != PenRouter.Route.TOUCH } else null if (penRouted == null && event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event) @@ -5004,7 +5292,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (event.pointerCount > 1) { var fingers = 0 for (index in 0 until event.pointerCount) if (!PenStream.isPen(event, index)) fingers = fingers or (1 shl event.getPointerId(index)) - event.pointerSubset(fingers)?.let { split -> try { onTouchEvent(split) } finally { split.recycle() } } + event.pointerSubset(fingers)?.let { split -> try { handleTouch(split) } finally { split.recycle() } } } when (route) { PenRouter.Route.PEN -> penSample(event, pen) @@ -5231,8 +5519,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun onlyPcKeyboardOpen(): Boolean = pcKeyboardOpen && !drawerOpen && !achievementsOpen && !inputSettingsOpen && !pipUi && !glassesOutputActive && !touchEditorOpen && !wowChatOnTop - private fun appUiOwnsPointer(): Boolean = - drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop + private fun otherUiOwnsPointer(): Boolean = + pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop + + private fun appUiOwnsPointer(): Boolean = drawerOpen || otherUiOwnsPointer() + + /** A touch-only docked menu leaves the game cursor alone, so controller pointer moves stay visible. */ + private fun cursorHiddenByUi(): Boolean = menuOwnsController || otherUiOwnsPointer() private fun applyPlatformPointer(shown: Boolean) { if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return @@ -5315,7 +5608,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde view.onTouchMiss = miss@{ event -> if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss event.offsetLocation(view.left - surfaceView.left.toFloat(), view.top - surfaceView.top.toFloat()) - onTouchEvent(event) + handleTouch(event) } root.addView(view, root.indexOfChild(onScreenControls) + 1) steamTouchControls = view @@ -5340,7 +5633,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc") .takeIf { it.isFile } ?.let { FileUtils.readString(it)?.trim()?.lowercase() } - ?: SessionPrefs.oscMode(this) + ?: SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM) + unfoldedColumn?.let { column -> + val shown = if (inputSettingsOpen) View.INVISIBLE else View.VISIBLE + if (column.visibility != shown) { unfoldedPanel?.releaseAll(); unfoldedDeckSurface?.releaseInputs(); column.visibility = shown } + } val controls = onScreenControls ?: return fun showPinned() { controls.setPinnedOnly(true) @@ -5506,31 +5803,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde heldKeys.set(owner, code, down) } - private fun capturePausedFrame(manual: Boolean = false) { - if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) return + private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) { + fun skipped(reason: String) { + if (manual) SessionEvents.record("pause.frame_skipped", mapOf("reason" to reason)) + onDone() + } + if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) { + return skipped("state running=${SessionState.running} pip=$pipUi glasses=$glassesOutputActive bottom=$bottomOutputActive") + } if (SessionState.suspended && pausedFrame != null) return - if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return - if (surfaceView.holder.surface?.isValid != true) return + if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return skipped("policy") + if (surfaceView.holder.surface?.isValid != true) return skipped("surface invalid") val width = surfaceView.width val height = surfaceView.height - if (width <= 0 || height <= 0) return + if (width <= 0 || height <= 0) return skipped("size ${width}x$height") val scale = minOf(1f, PAUSED_FRAME_MAX_EDGE / maxOf(width, height).toFloat()) val bitmap = try { android.graphics.Bitmap.createBitmap( maxOf(1, (width * scale).toInt()), maxOf(1, (height * scale).toInt()), android.graphics.Bitmap.Config.ARGB_8888, ) } catch (_: OutOfMemoryError) { - return + return skipped("oom") } val surfaceAt = IntArray(2).also { surfaceView.getLocationInWindow(it) } val overlayAt = IntArray(2).also { sessionOverlay.getLocationInWindow(it) } val left = surfaceAt[0] - overlayAt[0] val top = surfaceAt[1] - overlayAt[1] val bounds = android.graphics.Rect(left, top, left + width, top + height) + val requestedAt = SystemClock.elapsedRealtime() withPictureFrame { done -> try { android.view.PixelCopy.request(surfaceView, bitmap, { result -> done() + onDone() + if (manual) SessionEvents.record("pause.frame_copy", mapOf( + "result" to result, "ms" to SystemClock.elapsedRealtime() - requestedAt, + "zeroCopy" to SessionPrefs.zeroCopy(this, SessionState.mode), "size" to "${width}x$height", + "lit" to (result == android.view.PixelCopy.SUCCESS && bitmapHasPicture(bitmap)), + )) if (result == android.view.PixelCopy.SUCCESS && !isDestroyed) { pausedFrame = com.droiddeck.launcher.ui.PausedFrame(bitmap.asImageBitmap(), bounds) pausedFrameWanted = false @@ -5541,6 +5851,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } catch (_: IllegalArgumentException) { done() bitmap.recycle() + skipped("copy rejected") } } } @@ -5548,12 +5859,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun pauseNow() { if (!SessionState.running || SessionState.suspended) return pauseAnimated = true - drawerOpen = false + if (!dockedTouchOnly) drawerOpen = false pausedFrame = null - capturePausedFrame(manual = true) + if (zeroCopyActive()) { + WaylandCompositor.nativeSetZeroCopy(false) + val restore = java.util.concurrent.atomic.AtomicBoolean(false) + val back = { if (restore.compareAndSet(false, true)) WaylandCompositor.nativeSetZeroCopy(true) } + uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS) + uiHandler.postDelayed({ back() }, ZERO_COPY_RESTORE_MS) + } else { + capturePausedFrame(manual = true) + } SessionService.pause(this) } + private fun zeroCopyActive(): Boolean = + CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy(this, SessionState.mode) + + private fun bitmapHasPicture(bitmap: android.graphics.Bitmap): Boolean { + val w = bitmap.width + val h = bitmap.height + if (w <= 0 || h <= 0) return false + var lit = 0 + for (i in 0 until 64) { + val c = bitmap.getPixel((w * (i % 8 + 1)) / 9, (h * (i / 8 + 1)) / 9) + if (android.graphics.Color.red(c) + android.graphics.Color.green(c) + android.graphics.Color.blue(c) > 24) lit++ + } + return lit >= 3 + } + private fun requestPausedFrame() { if (pausedFrame != null) return pausedFrameWanted = true @@ -5628,11 +5962,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) { super.onPictureInPictureModeChanged(inPip, newConfig) - if (inPip) { - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.removeCallbacks(rearmAfterYield) - com.droiddeck.launcher.session.KeepTopActivity.stepAside() - } if (::pip.isInitialized) pip.changed(inPip) if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH) applyUnfoldedControls() @@ -5641,8 +5970,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) { - if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name && - (requestCode >= 0 || intent.component?.packageName == packageName || + if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName || intent.action in setOf(Intent.ACTION_CHOOSER, Intent.ACTION_SEND, Intent.ACTION_OPEN_DOCUMENT, Intent.ACTION_GET_CONTENT, "android.settings.PICTURE_IN_PICTURE_SETTINGS"))) pip.background() super.startActivityForResult(intent, requestCode, options) @@ -5663,8 +5991,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde reconcileDock(shownOnDisplayId) settleDualScreenControls() refreshSecondScreenDisplays() - if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode) - else openDualScreenControls() + if (secondScreenMode != SecondScreenMode.NONE) { + if (secondScreenPresentation == null) showSecondScreen(secondScreenMode) + if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu() + SessionState.bottomMenu = false + } else { + if (SessionState.bottomMenu && !menuShownOnBottom()) pinDockedMenu() + SessionState.bottomMenu = false + if (!menuShownOnBottom()) openDualScreenControls() + } startedScreens++ SessionService.setActivityVisible(this, true, sessionActivityDisplayId) Glasses.rescan() @@ -5674,10 +6009,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onStop() { - if (lightPause.stopped()) departureCleanup() - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.removeCallbacks(rearmAfterYield) - com.droiddeck.launcher.session.KeepTopActivity.stepAside() if (runtimeRemovalBlocked) { super.onStop(); return } started = false if (::hud.isInitialized) hud.setBackgrounded(true) @@ -5722,13 +6053,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onResume() { super.onResume() - com.droiddeck.launcher.session.KeepTopActivity.onYield = onGuardYield - uiHandler.removeCallbacks(lightPauseCheck) - when (lightPause.resumed(com.droiddeck.launcher.session.KeepTopActivity.bounces)) { - com.droiddeck.launcher.session.LightPause.Resume.LIGHT -> return - com.droiddeck.launcher.session.LightPause.Resume.CLEANUP_FIRST -> departureCleanup() - com.droiddeck.launcher.session.LightPause.Resume.NORMAL -> Unit - } drawerGameInventoryRevision++ com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event -> com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) } @@ -5773,6 +6097,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde updatePadMotion() ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener) SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener) + SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(hdrPrefListener) observedScreenEffectsProfileId = SessionPrefs.activeScreenEffectsProfileId(this) readPrefs() observedScreenEffectsProfileId = SessionPrefs.activeScreenEffectsProfileId(this) @@ -5794,73 +6119,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(cardboardPrefListener) } - private var memoryPressureAt = 0L - private var focusBounce = false - private val lightPause = com.droiddeck.launcher.session.LightPause() - private val lightPauseCheck = Runnable { if (lightPause.timedOut()) departureCleanup() } - private var topResumed = false - private val guardWhenRunning = object : Runnable { - override fun run() { - if (!topResumed || isFinishing) return - if (SessionState.running) guardOtherDisplays() else uiHandler.postDelayed(this, 2_000) - } - } - - // A touch that removed a guard while the session kept the top spot did not move focus to that - // display, so the guard comes back unless the user carries on there. - private val rearmAfterYield = Runnable { - if (topResumed && !isFinishing) { - com.droiddeck.launcher.session.KeepTopActivity.rearm() - guardOtherDisplays() - } - } - private val onGuardYield: () -> Unit = { - uiHandler.removeCallbacks(rearmAfterYield) - uiHandler.postDelayed(rearmAfterYield, com.droiddeck.launcher.session.KeepTopActivity.YIELD_GRACE_MS) - } - - // RUNNING_LOW and RUNNING_CRITICAL are not delivered from API 34, so the guard also goes up - // as soon as a running session is on top. - override fun onTrimMemory(level: Int) { - super.onTrimMemory(level) - if (!com.droiddeck.launcher.session.TopUnderPressure.isPressure(level)) return - memoryPressureAt = android.os.SystemClock.elapsedRealtime() - guardOtherDisplays() - } - - override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) { - super.onTopResumedActivityChanged(isTopResumedActivity) - topResumed = isTopResumedActivity - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.removeCallbacks(rearmAfterYield) - if (isTopResumedActivity) { - com.droiddeck.launcher.session.KeepTopActivity.rearm() - uiHandler.post(guardWhenRunning) - } - else if (com.droiddeck.launcher.session.TopUnderPressure.shouldReclaim( - android.os.SystemClock.elapsedRealtime(), memoryPressureAt, SessionState.running, isFinishing)) guardOtherDisplays() - } - - private fun guardOtherDisplays() { - if (!SessionState.running || isFinishing || isInPictureInPictureMode) return - val wasResumed = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED) - val bounced = com.droiddeck.launcher.session.KeepTopActivity.guardOtherDisplays(this, display?.displayId ?: android.view.Display.DEFAULT_DISPLAY) - if (com.droiddeck.launcher.session.KeepTopActivity.hasPendingStarts()) { - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.postDelayed(guardWhenRunning, com.droiddeck.launcher.session.KeepTopActivity.RETRY_MS) - } - if (!bounced) return - if (!wasResumed) return - focusBounce = true - uiHandler.postDelayed({ focusBounce = false }, 500) - } - override fun onPause() { - if (focusBounce) { - focusBounce = false - lightPause.paused(com.droiddeck.launcher.session.KeepTopActivity.bounces) - uiHandler.postDelayed(lightPauseCheck, 200) - } else departureCleanup() + departureCleanup() super.onPause() } @@ -5890,7 +6150,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde heldKeys.clear() heldButtons.clear() if (!screenOff) { + val menuUp = menuShownOnBottom() drawerOpen = false + if (menuUp) SessionState.bottomMenu = true pcKeyboardOpen = false achievementsOpen = false } @@ -5908,6 +6170,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde hidePrimaryKeyboard() pendingFieldKeyboard = pendingKeyboard SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(cardboardPrefListener) + SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(hdrPrefListener) SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener) ControllerPrefs.prefs(this).unregisterOnSharedPreferenceChangeListener(shortcutPrefListener) updateHeadTracker() @@ -6061,6 +6324,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val e = effectiveCardboard(c) activeCardboard = e applyGameAlignment() + applyNotchInset() if (CompositorHost.isStarted) pushCardboard(e) if (e.enabled && !was.enabled) headTracker?.recenter() updateHeadTracker() @@ -6144,6 +6408,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde glassesOutputActive = false surfaceW = 0 surfaceH = 0 + applyNotchInset() CompositorHost.detach(screen.holder.surface) surfaceView.visibility = View.VISIBLE applyOutputPacing() @@ -6193,6 +6458,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde bottomGame = screen surfaceW = 0 surfaceH = 0 + applyNotchInset() screen.setOnDismissListener { if (bottomGame === screen) { restoreTopOutput(screen) @@ -6234,6 +6500,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde updateOnScreenPad() surfaceW = 0 surfaceH = 0 + applyNotchInset() CompositorHost.detach(screen.holder.surface) if (glassesScreen != null) return surfaceView.visibility = View.VISIBLE @@ -6264,7 +6531,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde gestureTouchStreamGate.reset() } if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) return false - return onTouchEvent(event) + return handleTouch(event) } @androidx.compose.runtime.Composable @@ -6398,6 +6665,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde bottomGame?.let { restoreTopOutput(it); runCatching { it.dismiss() } } val screen = GlassesScreen(this, target, Glasses.outputHz(), this, Glasses.outputResolution()) glassesScreen = screen + applyNotchInset() applyOutputPacing() surfaceW = 0 surfaceH = 0 @@ -6522,10 +6790,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onDestroy() { - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.removeCallbacks(rearmAfterYield) - if (com.droiddeck.launcher.session.KeepTopActivity.onYield === onGuardYield) com.droiddeck.launcher.session.KeepTopActivity.onYield = null - com.droiddeck.launcher.session.KeepTopActivity.release() + uiHandler.removeCallbacks(panelHeldCheck) + uiHandler.removeCallbacks(panelHeldRetry) synchronized(frameGenGlobalLock) { frameGenActivityActive = false frameGenRequests.incrementAndGet() @@ -6533,7 +6799,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (AgentGuest.readyListener === agentReadyListener) AgentGuest.readyListener = null if (com.droiddeck.launcher.agent.AgentAttachments.gameFrame === gameFrame) com.droiddeck.launcher.agent.AgentAttachments.gameFrame = null com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) - relativeMouseRequests.shutdownNow() + gamescopeConvarRequests.shutdownNow() backQamInput.cancel() steamVrRecovery.close() uiHandler.removeCallbacks(steamTouchRetry) @@ -6576,6 +6842,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (SessionState.endListener === endListener) SessionState.endListener = null WaylandCompositor.clearFirstFrameListener(firstFrameListener) WaylandCompositor.clearPointerLockListener(pointerLockListener) + WaylandCompositor.clearOverlayPlanesListener(overlayPlanesListener) + WaylandCompositor.clearRefreshTargetListener(refreshTargetListener) + WaylandCompositor.clearContentRateListener(contentRateListener) super.onDestroy() } @@ -6650,9 +6919,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde const val EXTRA_STEAMVR = "steamVr" const val EXTRA_PLAYED_GAME = "com.droiddeck.launcher.PLAYED_GAME" const val EXTRA_REPAIR_RUNTIME = "repairRuntime" + private const val PANEL_HELD_CHECK_MS = 2_500L + private const val PANEL_HELD_RETRY_MS = 60_000L private const val LEAVE_TIMEOUT_MS = 1_500L private const val TEXT_FIELD_TAP_MS = 1_000L private const val PAUSED_FRAME_MAX_EDGE = 1920f + private const val ZERO_COPY_SETTLE_MS = 150L + private const val ZERO_COPY_RESTORE_MS = 1200L private const val BFI_PICTURE_SETTLE_MS = 50L private const val PAUSED_FRAME_REDRAW_MS = 150L private const val BOTTOM_RECOVERY_MS = 1_000L diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt index e04dda2580..abe8abb3a3 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt @@ -230,6 +230,20 @@ object AgentGuest { call(context, JSONObject().put("kind", "cdp").put("expression", expression).put("timeout", timeoutMs / 1000.0), timeoutMs + 2_000, trusted = true) + fun setGamescopeConvar(context: Context, name: String, value: Int): Boolean { + val request = JSONObject() + .put("kind", "exec") + .put("argv", org.json.JSONArray(listOf("gamescopectl", name, value.toString()))) + .put("timeout", 5.0) + val result = runCatching { call(context, request, 8_000, trusted = true) } + val answer = result.getOrNull() + val applied = answer?.optBoolean("ok") == true + && answer.optInt("exitCode", -1) == 0 + && !answer.optBoolean("timedOut") + if (!applied) Log.w(TAG, "gamescope did not take $name $value: ${result.exceptionOrNull() ?: answer}") + return applied + } + fun call(context: Context, request: JSONObject, timeoutMs: Long, trusted: Boolean = false): JSONObject { if (!trusted && request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context) if (!SessionState.running) throw AgentException("NO_ACTIVE_SESSION", "There is no running session") diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index df90f6f86b..573814f00c 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt @@ -143,9 +143,9 @@ object AgentSetup { listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " + "apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " + "dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " + - "for i in 1 2 3; do apt update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " + + "for i in 1 2 3; do apt -o APT::Update::Error-Mode=any update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " + "apt -f install -y --fix-missing; " + - "apt install -y --fix-missing --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}") + "apt install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}") } Step.SIGN_IN -> harness.signIn Step.GITHUB -> listOf("dd-gh-login") diff --git a/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt b/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt index fec75b544a..d0e2f2b575 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt @@ -175,5 +175,6 @@ internal class AddonPack( val ROCKSTAR = AddonPack("rockstar", BuildConfig.PACK_ROCKSTAR_SHA256, BuildConfig.PACK_ROCKSTAR_SIZE, listOf("Launcher32.exe", "Launcher64.exe")) val DIRT = AddonPack("dirt", BuildConfig.PACK_DIRT_SHA256, BuildConfig.PACK_DIRT_SIZE, listOf("ws2_32.dll")) + val EPIC = AddonPack("epic", BuildConfig.PACK_EPIC_SHA256, BuildConfig.PACK_EPIC_SIZE, listOf("EpicGamesLauncher.exe")) } } diff --git a/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt b/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt index c4c29a2369..50af093a02 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/AppUiPrefs.kt @@ -53,6 +53,13 @@ object AppUiPrefs { context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply() } + fun pageSwipe(context: Context): Boolean = + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getBoolean("page-swipe", true) + + fun setPageSwipe(context: Context, on: Boolean) { + context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("page-swipe", on).apply() + } + internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE fun scale(context: Context): Int = normalizeScale( 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 fe835b10c8..6cd2585557 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -207,9 +207,11 @@ object DeviceReport { k("refresh_rate_mode", runCatching { Settings.Secure.getString(context.contentResolver, "refresh_rate_mode") }.getOrNull() ?: "not set") val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context) for ((label, mode) in listOf("Resolution (Steam)" to SessionService.MODE_STEAM, "Resolution (Desktop)" to SessionService.MODE_DESKTOP)) { - val choice = SessionPrefs.resolutionChoice(context, mode, panelSize) - val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice) - k(label, "$choice (${size.first}x${size.second})") + for ((suffix, portrait) in listOf("landscape" to false, "portrait" to true)) { + val choice = SessionPrefs.resolutionChoice(context, mode, panelSize, portrait) + val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice, portrait) + k("$label $suffix", "$choice (${size.first}x${size.second})") + } } k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) @@ -289,6 +291,7 @@ object DeviceReport { k("Guest host name", SessionPrefs.guestHostname(context)) k("DirectAudio for games", SessionPrefs.directAudio(context)) k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context)) + k("Avoid notch", SessionPrefs.avoidNotch(context)) k("Return to launcher after a game", SessionPrefs.returnAfterGame(context)) k("Microphone", SessionPrefs.micEnabled(context)) k("On-screen controls", SessionPrefs.oscMode(context)) 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 c847dbcdfc..a063f251da 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt @@ -28,7 +28,9 @@ object DeviceSupport { com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI")) } - fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists() + fun bridgeUsable(): Boolean = bridgeUsable(adreno(), SystemVulkanDriver.isAvailable()) + + internal fun bridgeUsable(adreno: Boolean, systemDriverReady: Boolean): Boolean = !adreno && !systemDriverReady fun openDriverActive(context: Context): Boolean { if (adreno()) return false diff --git a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt index cd10300f4f..f284c98d36 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt @@ -16,7 +16,7 @@ object SteamIntegration { const val EXTRA_FEATURE = "integration_feature" const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS" private const val SHORTCUTS_ASSET = "shortcuts.apk" - enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS } + enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH } data class State( val wifi: Boolean = false, @@ -28,6 +28,7 @@ object SteamIntegration { val shortcuts: Boolean = false, val shortcutsRestricted: Boolean = false, val shortcutsTried: Boolean = false, + val bluetooth: Boolean = false, val suggested: Boolean = true, ) @@ -39,9 +40,16 @@ object SteamIntegration { home = HomeApp.isDefault(context), shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context), shortcutsRestricted = restrictedSettings(context), + bluetooth = bluetoothAllowed(context), suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false), ) + fun bluetoothAllowed(context: Context): Boolean = + android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S || + context.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED + + fun appInfo(context: Context) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}")) + private fun restrictedSettings(context: Context): Boolean { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false val mode = runCatching { diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt index 2d6adb902b..f7097dce7c 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt @@ -38,6 +38,8 @@ class WirelessAdbPairingService : Service() { private var pairingHost: String? = null private var pairingPort: Int? = null @Volatile private var working = false + @Volatile private var limitEnabled = false + @Volatile private var session = 0 private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) } override fun onBind(intent: Intent?): IBinder? = null @@ -50,12 +52,15 @@ class WirelessAdbPairingService : Service() { onCode(code) } ACTION_CANCEL -> finish(Stage.Idle) - else -> begin() + else -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true) } return START_NOT_STICKY } - private fun begin() { + private fun begin(enableLimit: Boolean) { + if (working) return + session++ + limitEnabled = enableLimit pairingHost = null pairingPort = null working = false @@ -68,12 +73,13 @@ class WirelessAdbPairingService : Service() { private fun startDiscovery() { stopDiscovery() + val owner = session val manager = getSystemService(Context.NSD_SERVICE) as NsdManager val listener = object : NsdManager.DiscoveryListener { override fun onDiscoveryStarted(serviceType: String) = Unit override fun onServiceFound(serviceInfo: NsdServiceInfo) { if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return - runCatching { manager.resolveService(serviceInfo, resolveListener()) } + runCatching { manager.resolveService(serviceInfo, resolveListener(owner)) } } override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit override fun onDiscoveryStopped(serviceType: String) = Unit @@ -87,18 +93,20 @@ class WirelessAdbPairingService : Service() { .onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) } } - private fun resolveListener() = object : NsdManager.ResolveListener { + private fun resolveListener(owner: Int): NsdManager.ResolveListener { + return object : NsdManager.ResolveListener { override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit override fun onServiceResolved(serviceInfo: NsdServiceInfo) { val address = serviceInfo.host ?: return if (!WirelessAdbFix.isLocalAddress(address)) return main.post { - if (working || current.value == Stage.Done) return@post + if (owner != session || working || current.value == Stage.Done) return@post pairingHost = address.hostAddress pairingPort = serviceInfo.port if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded()) } } + } } private fun onCode(code: String) { @@ -114,29 +122,34 @@ class WirelessAdbPairingService : Service() { return } working = true + val owner = session + val enable = limitEnabled show(Stage.Working(getString(R.string.adbpair_pairing))) Thread({ val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } } if (paired.isFailure) { main.post { working = false + if (owner != session) return@post pairingPort = null show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected))) } return@Thread } main.post { + if (owner != session) return@post stopDiscovery() show(Stage.Working(getString(R.string.adbpair_connecting))) } val result = runCatching { val connectPort = WirelessAdbFix.localConnectPort(this) ?: error(getString(R.string.adbpair_port_not_found)) - main.post { show(Stage.Working(getString(R.string.adbpair_applying))) } - WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false) + main.post { if (owner == session) show(Stage.Working(getString(R.string.adbpair_applying))) } + WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, enable) } main.post { working = false + if (owner != session) return@post finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: getString(R.string.adbpair_command_failed)) } ?: Stage.Done) } }, "wireless-adb-pairing").start() @@ -148,6 +161,7 @@ class WirelessAdbPairingService : Service() { } private fun finish(stage: Stage) { + session++ main.removeCallbacks(timeout) stopDiscovery() publish(stage) @@ -248,6 +262,7 @@ class WirelessAdbPairingService : Service() { private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE" private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL" private const val KEY_CODE = "code" + private const val EXTRA_ENABLE_LIMIT = "enable_limit" private const val TIMEOUT_MS = 5 * 60_000L private val current = MutableStateFlow(Stage.Idle) @@ -255,10 +270,10 @@ class WirelessAdbPairingService : Service() { private fun publish(stage: Stage) { current.value = stage } - fun start(context: Context) { + fun start(context: Context, enableLimit: Boolean = false) { context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID) publish(Stage.Waiting) - val intent = Intent(context, WirelessAdbPairingService::class.java) + val intent = Intent(context, WirelessAdbPairingService::class.java).putExtra(EXTRA_ENABLE_LIMIT, enableLimit) if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent) } @@ -271,6 +286,12 @@ class WirelessAdbPairingService : Service() { } fun notificationsEnabled(context: Context): Boolean = - context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false + context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false && !channelBlocked(context) + + /** The code is typed into a notification on this channel; a channel the user switched off leaves pairing with nothing to type into. */ + fun channelBlocked(context: Context): Boolean = + context.getSystemService(NotificationManager::class.java)?.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE + + fun channelId(): String = CHANNEL_ID } } diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt index 3fb876ac23..a05dad8e8f 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerItems.kt @@ -28,6 +28,7 @@ import androidx.compose.material.icons.filled.ArrowUpward import androidx.compose.material.icons.filled.Checklist import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.FileCopy +import androidx.compose.material.icons.filled.FileOpen import androidx.compose.material.icons.filled.Folder import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.InsertDriveFile @@ -101,8 +102,18 @@ private fun FileContextMenuItems( onToggleFavorite: () -> Unit, onProperties: () -> Unit, onDismissMenu: () -> Unit, + onOpen: () -> Unit, ) { val isDir = file.isDirectory + if (!isDir) { + DropdownMenuItem( + text = { Text(stringResource(R.string.fm_edit_open)) }, + leadingIcon = { Icon(Icons.Filled.FileOpen, null, tint = MaterialTheme.colorScheme.primary) }, + onClick = { onDismissMenu(); onOpen() }, + modifier = Modifier.focusGlide(), + ) + MenuItemDivider() + } DropdownMenuItem( text = { Text(stringResource(R.string.fm_select)) }, leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) }, @@ -180,6 +191,7 @@ internal fun FileItemRow( onCut: () -> Unit, onDelete: () -> Unit, onRename: () -> Unit, + onOpen: () -> Unit = {}, isFavorite: Boolean = false, onToggleFavorite: () -> Unit = {}, onProperties: () -> Unit = {}, @@ -291,6 +303,7 @@ internal fun FileItemRow( file = file, isFavorite = isFavorite, onSelect = onSelect, + onOpen = onOpen, onRename = onRename, onCopy = onCopy, onCut = onCut, @@ -517,6 +530,7 @@ internal fun FileGridTile( isFavorite: Boolean = false, onSelect: () -> Unit = {}, onRename: () -> Unit = {}, + onOpen: () -> Unit = {}, onCopy: () -> Unit = {}, onCut: () -> Unit = {}, onDelete: () -> Unit = {}, @@ -605,6 +619,7 @@ internal fun FileGridTile( file = file, isFavorite = isFavorite, onSelect = onSelect, + onOpen = onOpen, onRename = onRename, onCopy = onCopy, onCut = onCut, 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 9945083226..7025769d87 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -191,6 +191,7 @@ fun FileManagerScreen( var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) } var showNewFolderDialog by remember { mutableStateOf(false) } var renameTarget by remember { mutableStateOf(null) } + var editingTarget by remember { mutableStateOf(null) } var propertiesTarget by remember { mutableStateOf(null) } var isOperationRunning by remember { mutableStateOf(false) } var operationLabel by remember { mutableStateOf("") } @@ -294,7 +295,7 @@ fun FileManagerScreen( if (isOperationActive()) pendingNavigation = action else navigate(action) } - BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) { + BackHandler(enabled = editingTarget == null && (operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty())) { requestNavigation(FileManagerNavigation.BACK) } @@ -696,6 +697,14 @@ fun FileManagerScreen( val compactToolbar = LocalConfiguration.current.screenWidthDp < 600 Column(modifier = Modifier.fillMaxSize()) { + editingTarget?.let { target -> + TextEditorScreen( + file = target, + onExit = { editingTarget = null }, + modifier = Modifier.fillMaxSize(), + ) + return@Column + } if (pickMode && !pickerTitle.isNullOrEmpty()) { Text( text = pickerTitle, @@ -1194,6 +1203,8 @@ fun FileManagerScreen( pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() onPick?.invoke(file) } + } else { + editingTarget = file } }, onMenu = { showMenuFor = file }, @@ -1205,6 +1216,7 @@ fun FileManagerScreen( selectedPaths = selectedPaths + file.absolutePath showMenuFor = null }, + onOpen = { editingTarget = file; showMenuFor = null }, onRename = { renameTarget = file; showMenuFor = null }, onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null }, onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null }, @@ -1273,6 +1285,8 @@ fun FileManagerScreen( pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() onPick?.invoke(file) } + } else { + editingTarget = file } }, onMenu = { showMenuFor = file }, @@ -1286,6 +1300,7 @@ fun FileManagerScreen( onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null }, onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null }, onDelete = { selectedEntry = file; showMenuFor = null }, + onOpen = { editingTarget = file; showMenuFor = null }, onRename = { renameTarget = file; showMenuFor = null }, isFavorite = isFav, onToggleFavorite = { diff --git a/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt new file mode 100644 index 0000000000..2d9c0a3fea --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt @@ -0,0 +1,726 @@ +package com.droiddeck.launcher.files + +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowBack +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.Save +import androidx.compose.material.icons.filled.Search +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.ui.focusGlide +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.InputStream +import java.nio.ByteBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.Charset +import java.nio.charset.CodingErrorAction +import java.nio.file.Files +import kotlin.math.roundToInt + +internal const val EDITOR_FONT_SIZE_SP = 13 +internal const val EDITOR_LINE_HEIGHT_SP = 18 +internal const val EDITOR_TAB_WIDTH = 4 +internal const val EDITOR_MAX_OPEN_BYTES = 4L * 1024 * 1024 +internal const val EDITOR_MAX_EDIT_BYTES = 512L * 1024 + +internal enum class EditorCharset(val label: String, private val charsetName: String) { + UTF8("UTF-8", "UTF-8"), + GB18030("GB18030", "GB18030"), + ; + + val charset: Charset get() = Charset.forName(charsetName) +} + +internal enum class EditorLock { NONE, BINARY, TOO_LARGE, PERMISSION, LOSSY } + +internal enum class EditorLoadState { LOADING, READY, TOO_LARGE, UNREADABLE } + +internal data class DecodedEditorText(val text: String, val charset: EditorCharset, val lossy: Boolean) + +internal fun editorIsBinary(bytes: ByteArray, sample: Int = 8192): Boolean { + val limit = minOf(bytes.size, sample) + for (i in 0 until limit) if (bytes[i].toInt() == 0) return true + return false +} + +private fun strictDecode(bytes: ByteArray, charset: Charset): String? = try { + charset.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString() +} catch (e: CharacterCodingException) { + null +} + +internal fun decodeEditorText(bytes: ByteArray): DecodedEditorText { + strictDecode(bytes, Charsets.UTF_8)?.let { return DecodedEditorText(it, EditorCharset.UTF8, false) } + strictDecode(bytes, EditorCharset.GB18030.charset)?.let { return DecodedEditorText(it, EditorCharset.GB18030, false) } + return DecodedEditorText(String(bytes, Charsets.UTF_8), EditorCharset.UTF8, true) +} + +internal fun resolveEditorSaveTarget(file: File): File { + val isLink = runCatching { Files.isSymbolicLink(file.toPath()) }.getOrDefault(false) + if (!isLink) return file + // rename(2) replaces the link itself, so stage next to and rename onto the real target + return runCatching { file.canonicalFile }.getOrDefault(file) +} + +internal fun readCapped(input: InputStream, limit: Long): ByteArray? { + val out = ByteArrayOutputStream() + val buffer = ByteArray(64 * 1024) + var total = 0L + while (true) { + val n = input.read(buffer) + if (n < 0) return out.toByteArray() + total += n + if (total > limit) return null + out.write(buffer, 0, n) + } +} + +internal fun expandEditorTabs(text: String, width: Int = EDITOR_TAB_WIDTH): String { + if (text.indexOf('\t') < 0) return text + val out = StringBuilder(text.length) + var column = 0 + for (c in text) { + when (c) { + '\n' -> { + out.append(c) + column = 0 + } + '\t' -> { + val pad = width - (column % width) + repeat(pad) { out.append(' ') } + column += pad + } + else -> { + out.append(c) + column++ + } + } + } + return out.toString() +} + +internal fun lineCountOf(text: String): Int { + var lines = 1 + for (i in text.indices) if (text[i] == '\n') lines++ + return lines +} + +internal fun lineIndexOfOffset(text: String, offset: Int): Int { + val end = offset.coerceIn(0, text.length) + var line = 0 + var i = 0 + while (i < end) { + if (text[i] == '\n') line++ + i++ + } + return line +} + +internal fun columnOfOffset(text: String, offset: Int): Int { + val end = offset.coerceIn(0, text.length) + var start = end + while (start > 0 && text[start - 1] != '\n') start-- + return end - start + 1 +} + +internal fun findEditorMatches( + text: String, + query: String, + matchCase: Boolean = false, + limit: Int = 10000, +): List { + if (query.isEmpty()) return emptyList() + val out = ArrayList() + var at = 0 + while (out.size < limit) { + val found = text.indexOf(query, at, ignoreCase = !matchCase) + if (found < 0) break + out.add(found until found + query.length) + at = found + query.length + } + return out +} + +internal fun replaceEditorMatches(text: String, matches: List, replacement: String): String { + if (matches.isEmpty()) return text + val out = StringBuilder(text.length) + var cursor = 0 + for (m in matches) { + if (m.first < cursor || m.last >= text.length) continue + out.append(text, cursor, m.first).append(replacement) + cursor = m.last + 1 + } + out.append(text, cursor, text.length) + return out.toString() +} + +@Composable +internal fun TextEditorScreen( + file: File, + onExit: () -> Unit, + modifier: Modifier = Modifier, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val density = LocalDensity.current + + var text by remember { mutableStateOf("") } + var selection by remember { mutableStateOf(TextRange.Zero) } + var composing by remember { mutableStateOf(null) } + var loadState by remember { mutableStateOf(EditorLoadState.LOADING) } + var lock by remember { mutableStateOf(EditorLock.NONE) } + var charset by remember { mutableStateOf(EditorCharset.UTF8) } + var dirty by remember { mutableStateOf(false) } + var saving by remember { mutableStateOf(false) } + var showDiscard by remember { mutableStateOf(false) } + var showSearch by remember { mutableStateOf(false) } + var query by remember { mutableStateOf("") } + var replacement by remember { mutableStateOf("") } + var matchCase by remember { mutableStateOf(false) } + var matchIndex by remember { mutableIntStateOf(0) } + + val scrollState = rememberScrollState() + val textHorizontalState = rememberScrollState() + var viewportHeight by remember { mutableIntStateOf(0) } + var viewportWidth by remember { mutableIntStateOf(0) } + + val lineHeightDp = with(density) { EDITOR_LINE_HEIGHT_SP.sp.toDp() } + val lineHeightPx = with(density) { lineHeightDp.toPx() } + val totalLines = remember(text) { lineCountOf(text) } + val cursorLine = lineIndexOfOffset(text, selection.end) + val cursorColumn = columnOfOffset(text, selection.end) + val matches = remember(text, query, matchCase) { findEditorMatches(text, query, matchCase) } + val readOnly = lock != EditorLock.NONE + val bodyStyle = TextStyle( + fontFamily = FontFamily.Monospace, + fontSize = EDITOR_FONT_SIZE_SP.sp, + lineHeight = EDITOR_LINE_HEIGHT_SP.sp, + color = MaterialTheme.colorScheme.onBackground, + ) + val textMeasurer = rememberTextMeasurer() + val charWidthPx = remember(bodyStyle) { textMeasurer.measure(text = "0", style = bodyStyle).size.width.toFloat() } + + LaunchedEffect(file) { + loadState = EditorLoadState.LOADING + val size = withContext(Dispatchers.IO) { file.length() } + if (size > EDITOR_MAX_OPEN_BYTES) { + loadState = EditorLoadState.TOO_LARGE + return@LaunchedEffect + } + val read = withContext(Dispatchers.IO) { + runCatching { file.inputStream().use { readCapped(it, EDITOR_MAX_OPEN_BYTES) } } + } + val bytes = read.getOrNull() + if (bytes == null) { + loadState = if (read.isFailure) EditorLoadState.UNREADABLE else EditorLoadState.TOO_LARGE + return@LaunchedEffect + } + val decoded = decodeEditorText(bytes) + text = expandEditorTabs(decoded.text) + charset = decoded.charset + lock = when { + editorIsBinary(bytes) -> EditorLock.BINARY + decoded.lossy -> EditorLock.LOSSY + bytes.size > EDITOR_MAX_EDIT_BYTES -> EditorLock.TOO_LARGE + !file.canWrite() -> EditorLock.PERMISSION + else -> EditorLock.NONE + } + selection = TextRange.Zero + loadState = EditorLoadState.READY + } + + suspend fun revealLine(line: Int) { + val current = scrollState.value + val top = line * lineHeightPx + val target = when { + top < current -> top + top + lineHeightPx > current + viewportHeight -> top + lineHeightPx - viewportHeight + else -> return + } + val clamped = target.roundToInt().coerceIn(0, scrollState.maxValue) + if (clamped != current) scrollState.scrollTo(clamped) + } + + LaunchedEffect(text, selection.end, viewportHeight, viewportWidth) { + if (loadState != EditorLoadState.READY) return@LaunchedEffect + revealLine(lineIndexOfOffset(text, selection.end)) + if (viewportWidth > 0 && charWidthPx > 0) { + val x = (columnOfOffset(text, selection.end) - 1) * charWidthPx + val current = textHorizontalState.value + val target = when { + x < current -> x + x + charWidthPx > current + viewportWidth -> x + charWidthPx - viewportWidth + else -> null + } + if (target != null) { + val clamped = target.roundToInt().coerceIn(0, textHorizontalState.maxValue) + if (clamped != current) textHorizontalState.scrollTo(clamped) + } + } + } + + LaunchedEffect(query, matchCase) { + if (query.isEmpty()) return@LaunchedEffect + matchIndex = 0 + val first = matches.firstOrNull() ?: return@LaunchedEffect + selection = TextRange(first.first, first.last + 1) + composing = TextRange.Zero + } + + LaunchedEffect(text) { matchIndex = 0 } + + fun gotoMatch(delta: Int) { + if (matches.isEmpty()) return + matchIndex = Math.floorMod(matchIndex + delta, matches.size) + val m = matches[matchIndex] + selection = TextRange(m.first, m.last + 1) + composing = TextRange.Zero + } + + fun replaceCurrent() { + if (readOnly) return + val m = matches.getOrNull(matchIndex) ?: return + text = text.replaceRange(m.first, m.last + 1, replacement) + dirty = true + matchIndex = 0 + selection = TextRange(m.first + replacement.length) + composing = TextRange.Zero + } + + fun replaceAll() { + if (readOnly || matches.isEmpty()) return + val all = findEditorMatches(text, query, matchCase, limit = Int.MAX_VALUE) + text = replaceEditorMatches(text, all, replacement) + dirty = true + matchIndex = 0 + selection = TextRange.Zero + composing = TextRange.Zero + } + + fun save() { + if (readOnly || saving || loadState != EditorLoadState.READY) return + val snapshot = text + val bytes = snapshot.toByteArray(charset.charset) + saving = true + scope.launch { + val ok = withContext(Dispatchers.IO) { + runCatching { + val target = resolveEditorSaveTarget(file) + val parent = target.parentFile + if (parent == null) { + target.writeBytes(bytes) + } else { + val tmp = File.createTempFile(".${target.name}.", ".droiddeck-tmp", parent) + try { + tmp.writeBytes(bytes) + runCatching { + Files.setPosixFilePermissions(tmp.toPath(), Files.getPosixFilePermissions(target.toPath())) + } + if (!tmp.renameTo(target)) error("rename to ${target.name} failed") + } finally { + tmp.delete() + } + } + }.isSuccess + } + saving = false + if (ok) { + if (text == snapshot) dirty = false + } else { + Toast.makeText(context, context.getString(R.string.fm_edit_save_failed, file.name), Toast.LENGTH_SHORT).show() + } + } + } + + fun tryExit() { + if (saving) return + if (dirty && !readOnly) showDiscard = true else onExit() + } + + BackHandler { tryExit() } + + if (showDiscard) { + OutlinedAlertDialog( + onDismissRequest = { showDiscard = false }, + title = { Text(stringResource(R.string.fm_edit_discard_title)) }, + text = { Text(stringResource(R.string.fm_edit_discard_text, file.name)) }, + confirmButton = { + TextButton(onClick = onExit, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.fm_edit_discard)) + } + }, + dismissButton = { + TextButton(onClick = { showDiscard = false }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.common_cancel)) + } + }, + ) + } + + Column( + modifier = modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.surfaceContainer) + .padding(horizontal = 8.dp, vertical = 6.dp), + ) { + IconButton(onClick = { tryExit() }, modifier = Modifier.focusGlide(CircleShape)) { + Icon( + Icons.Filled.ArrowBack, + stringResource(R.string.fm_back), + tint = MaterialTheme.colorScheme.primary, + ) + } + Column(modifier = Modifier.weight(1f).padding(horizontal = 4.dp)) { + Text( + text = file.name, + color = MaterialTheme.colorScheme.onBackground, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (dirty) { + Text( + text = "\u2022 " + stringResource(R.string.fm_edit_modified), + color = MaterialTheme.colorScheme.primary, + fontSize = 11.sp, + maxLines = 1, + ) + } + } + if (loadState == EditorLoadState.READY && lock != EditorLock.NONE) { + Text( + text = stringResource( + if (lock == EditorLock.BINARY) R.string.fm_edit_binary else R.string.fm_edit_read_only, + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 10.sp, + maxLines = 1, + modifier = Modifier + .background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.small) + .padding(horizontal = 6.dp, vertical = 2.dp), + ) + Spacer(Modifier.width(6.dp)) + } + IconButton( + onClick = { showSearch = !showSearch }, + enabled = loadState == EditorLoadState.READY, + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.Search, + stringResource(R.string.fm_edit_find), + tint = if (showSearch) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + IconButton( + onClick = { save() }, + enabled = loadState == EditorLoadState.READY && !readOnly && dirty && !saving, + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.Save, + stringResource(R.string.fm_edit_save), + tint = if (dirty) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + if (showSearch && loadState == EditorLoadState.READY) { + Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainer)) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp, top = 4.dp), + ) { + OutlinedTextField( + value = query, + onValueChange = { query = it; matchIndex = 0 }, + singleLine = true, + placeholder = { Text(stringResource(R.string.fm_edit_find), fontSize = 13.sp) }, + textStyle = MaterialTheme.typography.bodySmall, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { gotoMatch(1) }), + modifier = Modifier.weight(1f).focusGlide(), + ) + Text( + text = if (matches.isEmpty()) "0/${matches.size}" else "${matchIndex.coerceAtMost(matches.size - 1) + 1}/${matches.size}", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 6.dp).widthIn(min = 44.dp, max = 80.dp), + ) + IconButton( + onClick = { gotoMatch(-1) }, + enabled = matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.KeyboardArrowUp, + stringResource(R.string.fm_edit_find_previous), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + } + IconButton( + onClick = { gotoMatch(1) }, + enabled = matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.KeyboardArrowDown, + stringResource(R.string.fm_edit_find_next), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + } + TextButton(onClick = { matchCase = !matchCase }, modifier = Modifier.focusGlide(CircleShape)) { + Text( + text = "Aa", + color = if (matchCase) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 13.sp, + ) + } + IconButton(onClick = { showSearch = false }, modifier = Modifier.focusGlide(CircleShape)) { + Icon( + Icons.Filled.Close, + stringResource(R.string.common_cancel), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + } + } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 2.dp, end = 4.dp, bottom = 2.dp), + ) { + OutlinedTextField( + value = replacement, + onValueChange = { replacement = it }, + singleLine = true, + placeholder = { Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) }, + textStyle = MaterialTheme.typography.bodySmall, + modifier = Modifier.weight(1f).focusGlide(), + ) + TextButton( + onClick = { replaceCurrent() }, + enabled = !readOnly && matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) + } + TextButton( + onClick = { replaceAll() }, + enabled = !readOnly && matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Text(stringResource(R.string.fm_edit_replace_all), fontSize = 13.sp) + } + } + } + } + + Box( + modifier = Modifier + .weight(1f) + .fillMaxWidth() + .onSizeChanged { viewportHeight = it.height }, + ) { + when (loadState) { + EditorLoadState.LOADING -> CircularProgressIndicator( + modifier = Modifier.align(Alignment.Center), + ) + + EditorLoadState.TOO_LARGE, EditorLoadState.UNREADABLE -> Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.align(Alignment.Center).padding(24.dp), + ) { + Text( + text = stringResource( + if (loadState == EditorLoadState.TOO_LARGE) R.string.fm_edit_too_large + else R.string.fm_edit_open_failed, + if (loadState == EditorLoadState.TOO_LARGE) FileOps.formatBytes(context, file.length()) + else file.name, + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 14.sp, + textAlign = TextAlign.Center, + ) + } + + EditorLoadState.READY -> Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(scrollState), + ) { + Row(modifier = Modifier.fillMaxWidth().height(lineHeightDp * totalLines.toFloat())) { + LineNumbers( + scrollState = scrollState, + viewportHeight = viewportHeight, + lineHeightDp = lineHeightDp, + lineHeightPx = lineHeightPx, + totalLines = totalLines, + cursorLine = cursorLine, + style = bodyStyle, + mutedColor = MaterialTheme.colorScheme.onSurfaceVariant, + cursorColor = MaterialTheme.colorScheme.primary, + ) + Box(modifier = Modifier.weight(1f).onSizeChanged { viewportWidth = it.width }.horizontalScroll(textHorizontalState)) { + BasicTextField( + value = TextFieldValue(text = text, selection = selection, composition = composing), + onValueChange = { next -> + val changed = next.text != text + text = next.text + selection = next.selection + composing = next.composition + if (changed) dirty = true + }, + readOnly = readOnly, + textStyle = bodyStyle, + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Text, + capitalization = KeyboardCapitalization.None, + ), + modifier = Modifier.fillMaxHeight().focusGlide(), + ) + } + } + } + } + } + + if (loadState == EditorLoadState.READY) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp), + ) { + Text( + text = stringResource(R.string.fm_edit_position, cursorLine + 1, cursorColumn), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + maxLines = 1, + ) + Spacer(Modifier.weight(1f)) + Text( + text = charset.label + " \u2022 " + FileOps.formatBytes(context, file.length()), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + maxLines = 1, + ) + } + } + } +} + +@Composable +private fun LineNumbers( + scrollState: ScrollState, + viewportHeight: Int, + lineHeightDp: Dp, + lineHeightPx: Float, + totalLines: Int, + cursorLine: Int, + style: TextStyle, + mutedColor: Color, + cursorColor: Color, + modifier: Modifier = Modifier, +) { + val firstLine = (scrollState.value / lineHeightPx).toInt().coerceIn(0, totalLines - 1) + val lastLine = ((scrollState.value + viewportHeight) / lineHeightPx) + .toInt() + .coerceIn(firstLine, totalLines - 1) + Column( + horizontalAlignment = Alignment.End, + modifier = modifier + .width(IntrinsicSize.Min) + .padding(top = lineHeightDp * firstLine.toFloat()), + ) { + for (line in firstLine..lastLine) { + Text( + text = (line + 1).toString(), + color = if (line == cursorLine) cursorColor else mutedColor, + textAlign = TextAlign.End, + maxLines = 1, + style = style, + modifier = Modifier.fillMaxWidth().height(lineHeightDp), + ) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt index e3c2d9a749..9968b1c1fd 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt @@ -31,6 +31,7 @@ object AddedGames { val exeUncertain: Boolean = false, val launchOptions: String = "", val single: Boolean = false, + val steamProgram: Boolean = true, ) { fun folderName(): String = folder.name } @@ -336,7 +337,10 @@ object AddedGames { val owner = ownerFolder(app, exe) if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) { single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let { - if (guestPath(app, exe) != null) AddedExes.put(app, AddedExes.Entry(owner.path, exe.path)) + if (guestPath(app, it.exe) != null) { + SessionPrefs.setAddedGameExe(app, owner.path, it.exe.path) + AddedExes.put(app, AddedExes.Entry(owner.path, it.exe.path)) + } return AddResult.Existing(it) } } @@ -442,9 +446,9 @@ object AddedGames { val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile } ?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile } val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return - val epicLauncher = sidecar?.takeIf { it.store == Store.EPIC && (chosen == null || canonical(chosen) == canonical(it.exeFile(folder))) } + val storeLauncher = sidecar?.takeIf { chosen == null || canonical(chosen) == canonical(it.exeFile(folder)) } ?.launcherFile(folder)?.takeIf { it.isFile } - val launch = epicLauncher ?: if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found + val launch = storeLauncher ?: found val foundGuest = guestPath(context, launch) if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return } val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name @@ -470,7 +474,13 @@ object AddedGames { val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() } ?: sidecarDir ?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return - val steamId = config?.let { steamRoute(it, appId) } + if (adopted == null && SessionPrefs.addedGameAdopted(context, folder.path, "Exe") == null && + guestPath(context, folder)?.let { steamEditedTo(it, record, guestExe) } == true) { + SessionPrefs.setAddedGameAdopted(context, folder.path, "Exe", exe.path) + } + val steamProgram = candidates.firstOrNull()?.let { canonical(it) == canonical(exe) } ?: true || + SessionPrefs.addedGameAdopted(context, folder.path, "Exe")?.let { canonical(File(it)) == canonical(exe) } == true + val steamId = config?.takeIf { steamProgram }?.let { steamRoute(it, appId) } out.add(Game(folder, name, exe, guestExe, guestDir, appId, steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId, source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id, @@ -480,7 +490,7 @@ object AddedGames { sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context) else -> "" }, - single = single != null)) + single = single != null, steamProgram = steamProgram)) } } @@ -520,6 +530,11 @@ object AddedGames { return file.takeIf { inside && it.isFile } } + internal fun steamEditedTo(folderGuest: String, record: JSONObject?, guestExe: String): Boolean { + val steam = unquote(record?.optJSONObject("steam")?.optString("Exe")) + return steam == guestExe && steam != unquote(record?.optJSONObject("app")?.optString("Exe")) && steam.startsWith("$folderGuest/") + } + private fun unquote(value: String?): String = value.orEmpty().trim().trim('"') internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) { @@ -568,6 +583,7 @@ object AddedGames { .append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path)) if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions)) if (g.source != Library.ADDED) json.append(",\"store\":").append(quote(g.source)) + if (!g.steamProgram) json.append(",\"route\":false") val art = AddedGameArt.resolve(context, g) val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon) .mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt index d6fe58ad7f..4da77ee6d7 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AutoComponents.kt @@ -47,6 +47,7 @@ object AutoComponents { { c, comp, all, progress -> WinComponents.install(c, comp, all, progress) } @VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running } @VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) } + @VisibleForTesting internal var firstRunHeldBack: (Context) -> Boolean = { c -> powerSaveOrMetered(c) } @VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) } @VisibleForTesting @Volatile internal var runNow = false @@ -533,6 +534,10 @@ object AutoComponents { caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED) } + fun powerSaveOrMetered(context: Context): Boolean = + context.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true || + context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true + fun constrained(context: Context): Boolean { val power = context.getSystemService(PowerManager::class.java) if (power?.isPowerSaveMode == true) return true diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SteamRedists.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SteamRedists.kt index 17a2e8b6c8..342bfa9b37 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/SteamRedists.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SteamRedists.kt @@ -20,6 +20,12 @@ object SteamRedists { val SCRIPTED = mapOf( 72850 to listOf("xact" to "DirectX XACT audio"), 489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"), + // Warband compiles its postFX .fx effects at launch through d3dx9_42; Wine's own d3dcompiler_42 stops with E5017/E5033 on fx_2_0. + 48700 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_42" to "D3DCompiler 42"), + // DST's bundled ANGLE compiles SM3 shaders through d3dcompiler_43; DXVK's SM3 parser asserts on what Wine's own one emits. + 322330 to listOf("d3dcompiler_43" to "D3DCompiler 43"), + // EU4 builds its map effects through native d3dx9_43, which calls d3dcompiler_43; Wine's own one fails them with E5005, so the map draws black. + 236850 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_43" to "D3DCompiler 43"), ) private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE) private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"") diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/XrealLink.kt b/app/src/main/java/com/droiddeck/launcher/glasses/XrealLink.kt index d2ea72d4d4..530b315828 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/XrealLink.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/XrealLink.kt @@ -45,9 +45,8 @@ internal class XrealLink internal constructor( if (msgId == VitureProtocol.MSG_GET_IMU) return true val valid = when (msgId) { VitureProtocol.MSG_GET_DISPLAY -> true - VitureProtocol.MSG_DISPLAY -> if (model.stereoOnlyControl) value == 5 || value == XrealModel.NATIVE_60HZ - else value in 2..5 || value == XrealModel.NATIVE_60HZ - VitureProtocol.MSG_BRIGHTNESS -> !model.stereoOnlyControl && value in 0..9 + VitureProtocol.MSG_DISPLAY -> model.supportsDisplayMode(value) + VitureProtocol.MSG_BRIGHTNESS -> model.hardwareControls && value in 0..model.brightnessMax VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1 else -> false } @@ -64,12 +63,12 @@ internal class XrealLink internal constructor( channels = connector.connect() connection.set(channels) if (!running) break - val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl) + val control = XrealControl(channels, model = model) listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display()) val current = channels reports = Thread({ try { - var filter = XrealOrientationFilter(model.flipsYz) + var filter = XrealOrientationFilter(model) var wasTracking = false var lastSensor = System.nanoTime() while (running && connection.get() === current) { @@ -78,7 +77,7 @@ internal class XrealLink internal constructor( if (sample != null) { lastSensor = System.nanoTime() val enabled = tracking - if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz) + if (enabled && !wasTracking) filter = XrealOrientationFilter(model) wasTracking = enabled if (enabled) filter.update(sample)?.let { if (running && ready && tracking && connection.get() === current) @@ -155,8 +154,9 @@ internal class XrealLink internal constructor( internal class XrealControl( private val channels: XrealChannels, private val settleDelayMs: Long = 150, - private val stereoOnly: Boolean = false, + private val model: XrealModel = XrealModel.ONE_S, ) { + private val stereoOnly get() = model.stereoOnlyControl private var transaction = 0 private fun exchange(command: Int, value: Int? = null): ByteArray { transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1 @@ -172,7 +172,7 @@ internal class XrealControl( fun display(): Int { if (stereoOnly) return stereoDisplay() val reply = exchange(XrealProtocol.GET_DISPLAY) - return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ } + return XrealProtocol.numeric(reply)?.takeIf(model::supportsDisplayMode) ?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}") } private fun stereoDisplay(): Int { @@ -187,6 +187,7 @@ internal class XrealControl( } } fun changeDisplay(mode: Int): Int { + require(model.supportsDisplayMode(mode)) val stereo = mode == 5 set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0) val current = awaitDisplay { (it == 5) == stereo } diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/XrealModel.kt b/app/src/main/java/com/droiddeck/launcher/glasses/XrealModel.kt index 70b81995e1..0bb7b7379a 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/XrealModel.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/XrealModel.kt @@ -4,6 +4,7 @@ internal class XrealModel private constructor( override val name: String, val family: Family, override val diagonalFovDeg: Float, + private val native60Hz: Int = NATIVE_60HZ, ) : GlassesModel { enum class Family { ONE_S, @@ -14,23 +15,25 @@ internal class XrealModel private constructor( override val controllable = true override val brightnessMax = 9 override val volumeMax = 0 - override val hasSunblock get() = family == Family.ONE_S - override val hardwareControls get() = family == Family.ONE_S + override val hasSunblock get() = !stereoOnlyControl + override val hardwareControls get() = !stereoOnlyControl override val sbs90 = false - override val rates2d get() = if (family == Family.ONE_S) super.rates2d else listOf(60) + override val rates2d get() = if (stereoOnlyControl) listOf(60) else super.rates2d - // Only the 1S has been exercised with SET_DISPLAY; the Aura is known to reboot on an unexpected index. - val stereoOnlyControl get() = family != Family.ONE_S + val stereoOnlyControl get() = family != Family.ONE_S && this !== ONE_PRO_PLUS + + internal fun supportsDisplayMode(mode: Int) = if (stereoOnlyControl) mode == 5 || mode == native60Hz + else mode in 3..5 || mode == native60Hz || (this === ONE_S && mode == 2) // The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it. val flipsYz get() = family != Family.AURA override fun mode(hz: Int, sbs: Boolean) = when { sbs -> 5 - stereoOnlyControl -> NATIVE_60HZ + stereoOnlyControl -> native60Hz hz >= 120 -> 4 hz >= 90 -> 3 - else -> NATIVE_60HZ + else -> native60Hz } override fun modeForStep(step: Int): Int? = null @@ -44,7 +47,7 @@ internal class XrealModel private constructor( val ONE_S = XrealModel("XREAL 1S", Family.ONE_S, 52f) val ONE = XrealModel("XREAL One", Family.ONE, 50f) val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f) - val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f) + val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f, 9) val AURA = XrealModel("XREAL Aura", Family.AURA, 70f) // The odd product ids one below these are the glasses' recovery mode. diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/XrealOrientationFilter.kt b/app/src/main/java/com/droiddeck/launcher/glasses/XrealOrientationFilter.kt index 8bf8dd30e7..ac8e7172c5 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/XrealOrientationFilter.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/XrealOrientationFilter.kt @@ -2,13 +2,18 @@ package com.droiddeck.launcher.glasses import kotlin.math.abs -internal class XrealOrientationFilter(private val flipYz: Boolean = true) { +internal class XrealOrientationFilter(private val model: XrealModel = XrealModel.ONE_S) { private val fusion = ImuFusion() + private val sensorToDisplay = if (model === XrealModel.ONE_PRO_PLUS) + Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.toRadians(35.0).toFloat()) else null fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs, sample.accel.headAxes(), sample.gyro.headAxes()) - private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this + private fun Vec3.headAxes(): Vec3 { + val display = sensorToDisplay?.rotate(this) ?: this + return if (model.flipsYz) Vec3(display.x, -display.y, -display.z) else display + } } internal class ImuFusion { diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt index 1623c10106..25124a6a52 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt @@ -21,6 +21,8 @@ object FrameGen { private const val PREFS = "frame_gen" data class Mode(val engine: String, val multiplier: Int = 2, val target: Int = 0) { + val outputFactor: Int get() = if (engine == ENGINE_OFF) 1 else multiplier + companion object { val OFF = Mode(ENGINE_OFF) } diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java index 4f0b62eddb..11fc19c877 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriverManager.java @@ -89,6 +89,11 @@ public class LinuxVulkanDriverManager { return m != null ? m.optString("minGlibc", "") : ""; } + public boolean rendersToDisplayBuffers(String id) { + JSONObject m = id == null || id.isEmpty() ? null : readMeta(id); + return m != null && m.optBoolean("displayBuffers", false); + } + public void removeDriver(String id) { if (id == null || id.isEmpty() || id.contains("/") || id.contains("..")) return; Log.d(TAG, "removing imported Linux Vulkan driver " + id); @@ -182,6 +187,7 @@ public class LinuxVulkanDriverManager { meta.put("driverVersion", version); meta.put("libc", "glibc"); meta.put("minGlibc", minGlibc); + meta.put("displayBuffers", zipMeta != null && zipMeta.optBoolean("displayBuffers", false)); meta.put("sourceLibraryName", soName); meta.put("libraryName", stored); meta.put("importedAt", System.currentTimeMillis()); diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt b/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt index 84b29bd5d9..c3ecfa5145 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.gpu import androidx.annotation.StringRes import com.droiddeck.launcher.R +import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.wayland.WaylandCompositor import org.json.JSONObject import kotlin.math.abs @@ -30,7 +31,7 @@ data class ScreenEffects( fun push(upscaler: Int) { WaylandCompositor.nativeSetCas(cas, casLevel) - WaylandCompositor.nativeSetHdr(hdr) + WaylandCompositor.nativeSetHdr(hdr && !SessionState.hdrDisplay) WaylandCompositor.nativeSetDeband(deband, debandStrength) WaylandCompositor.nativeSetScreenEffects(brightness.toFloat(), contrast.toFloat(), gamma, saturation.toFloat(), aaMode, toon, crt, ntsc) WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(this, upscaler)?.name) diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt index c1f2966b6d..586950f9d0 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt @@ -7,7 +7,8 @@ object SocNames { "SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870", "SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1", "SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3", - "SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5", + "SM8750" to "Snapdragon 8 Elite", "SM8750P" to "Snapdragon 8 Elite", + "SM8850" to "Snapdragon 8 Elite Gen 5", "SM8975" to "Snapdragon 8 Elite Extreme Gen 6", "SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3", "SM6375" to "Snapdragon 695", @@ -23,7 +24,8 @@ object SocNames { val sdk = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it != Build.UNKNOWN }.orEmpty() else "" return listOf(prop("ro.soc.model"), prop("ro.vendor.qti.soc_model"), sdk, prop("ro.fota.platform")) .map { it.trim() } - .firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty() + .firstOrNull { it.isNotEmpty() && !it.equals(Build.UNKNOWN, ignoreCase = true) && !Regex("(?i)^msm_\\d").containsMatchIn(it) } + .orEmpty() } internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim() diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java index d8aad76348..a26b1987fd 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java @@ -308,8 +308,7 @@ public final class TurnipDriver { } } if (chosen != null && !chosen.isEmpty()) { - if (SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context)) - && SessionPrefs.INSTANCE.gpuAutoInstalled(context).contains(chosen) + if (SessionPrefs.INSTANCE.displayDriverFromAuto(context) && gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) { Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system"); return null; diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt index 59f8a5e6eb..7a96f0b6ac 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudHost.kt @@ -44,6 +44,35 @@ class DroidDeckHudHost(context: Context) { private var protonPid = 0 private var proton = "" @Volatile private var lastWindow: String? = null + @Volatile private var lastCompositorFrameNanos = 0L + @Volatile private var lastVisibilityGameActive = false + private var candidateGameActive = false + private var candidateGameActiveSinceNs = 0L + private var stableGameActive = false + + private fun isGameActive(): Boolean { + val now = System.nanoTime() + val compositorLive = lastCompositorFrameNanos > 0L && + now - lastCompositorFrameNanos <= 1_000_000_000L + val detected = if (feed.live) { + feed.steamFocusKnown && !feed.steamFocused + } else { + compositorLive + } + + if (detected != candidateGameActive) { + candidateGameActive = detected + candidateGameActiveSinceNs = now + } + + if (detected != stableGameActive && + now - candidateGameActiveSinceNs >= GAME_ACTIVITY_STABLE_NS + ) { + stableGameActive = detected + } + + return stableGameActive + } var onPresentingWindowChanged: (() -> Unit)? = null @@ -66,6 +95,12 @@ class DroidDeckHudHost(context: Context) { } override fun onGameFrame() { + if (feed.live && (!feed.steamFocusKnown || feed.steamFocused)) return + lastCompositorFrameNanos = System.nanoTime() + feed.onCompositorFrame(lastCompositorFrameNanos) + } + + override fun onCompositorFrame() { feed.onCompositorFrame(System.nanoTime()) } } @@ -73,7 +108,9 @@ class DroidDeckHudHost(context: Context) { private val frameCallback = object : Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { if (!running || !polling) return + reconcileGameActivity() if (feed.poll(System.nanoTime())) view?.onFrames() + reconcileGameActivity() Choreographer.getInstance().postFrameCallback(this) } } @@ -151,7 +188,7 @@ class DroidDeckHudHost(context: Context) { fun refresh() { applyConfig() - if (!enabled) stop() else if (!running) start() + if (!enabled) stop() else if (!running) start() else applyShown() } fun start() { @@ -181,14 +218,26 @@ class DroidDeckHudHost(context: Context) { applyShown() } + private fun reconcileGameActivity() { + if (!SessionPrefs.hudOnlyDuringGame(context)) { + lastVisibilityGameActive = isGameActive() + return + } + if (isGameActive() != lastVisibilityGameActive) applyShown() + } + private fun applyShown() { if (!running) return - val show = !hidden && !backgrounded + val onlyDuringGame = SessionPrefs.hudOnlyDuringGame(context) + val gameActive = isGameActive() + val show = !hidden && !backgrounded && (!onlyDuringGame || gameActive) view?.visibility = if (show) View.VISIBLE else View.GONE showing = show - if (show != polling) { - polling = show - if (show) Choreographer.getInstance().postFrameCallback(frameCallback) + lastVisibilityGameActive = gameActive + val shouldPoll = !hidden && !backgrounded && (show || onlyDuringGame) + if (shouldPoll != polling) { + polling = shouldPoll + if (shouldPoll) Choreographer.getInstance().postFrameCallback(frameCallback) else Choreographer.getInstance().removeFrameCallback(frameCallback) } } @@ -532,6 +581,7 @@ class DroidDeckHudHost(context: Context) { } companion object { + private const val GAME_ACTIVITY_STABLE_NS = 350_000_000L private const val DOCK_OVERHANG = 0.4f private const val PREVIEW_FROM = 0.55f private const val STRIP_PULL_ACROSS_DP = 360f diff --git a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt index 3c996a03f0..e8967d944d 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt @@ -183,6 +183,8 @@ internal class GameFrameFeed( private set @Volatile var steamFocused = false private set + @Volatile var steamFocusKnown = false + private set @Volatile var pid = 0 private set @Volatile var outputWidth = 0 @@ -198,10 +200,16 @@ internal class GameFrameFeed( val compositorAdded = compositorFrames != seenCompositorFrames seenCompositorFrames = compositorFrames if (handle == 0L) { - if (nowNs < nextOpenNs) return compositorAdded + if (nowNs < nextOpenNs) { + + return compositorAdded + } nextOpenNs = nowNs + REOPEN_NS handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L) - if (handle == 0L) return compositorAdded + if (handle == 0L) { + + return compositorAdded + } HudFrames.nativePoll(handle, frametimes, times) } val n = HudFrames.nativePoll(handle, frametimes, times) @@ -219,6 +227,7 @@ internal class GameFrameFeed( fromGamescope = false } if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close() + if (nowNs - lastInfoNs >= INFO_NS) { lastInfoNs = nowNs readInfo() @@ -250,6 +259,7 @@ internal class GameFrameFeed( } fun close() { + fromGamescope = false if (handle != 0L) HudFrames.nativeClose(handle) handle = 0L } @@ -265,6 +275,7 @@ internal class GameFrameFeed( outputHeight = info[2] refreshMilliHz = info[3] steamFocused = info[4] != 0 + steamFocusKnown = true engine = engineLabel(name) } diff --git a/app/src/main/java/com/droiddeck/launcher/input/AxisPacing.kt b/app/src/main/java/com/droiddeck/launcher/input/AxisPacing.kt new file mode 100644 index 0000000000..2170ab5030 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/AxisPacing.kt @@ -0,0 +1,39 @@ +package com.droiddeck.launcher.input + +internal class AxisPacing(private val intervalMs: Long) { + private var lastWriteAt = 0L + private var written = false + private var heldUntil = NOT_HELD + + fun dueAt(now: Long, axesOnly: Boolean): Long = + if (axesOnly && written && now - lastWriteAt < intervalMs) lastWriteAt + intervalMs else now + + fun wrote(at: Long) { + lastWriteAt = at + written = true + } + + fun hold(due: Long): Boolean { + if (heldUntil != NOT_HELD) return false + heldUntil = due + return true + } + + fun release(now: Long): Boolean { + if (heldUntil == NOT_HELD || now < heldUntil) return false + heldUntil = NOT_HELD + return true + } + + fun cancel(): Boolean { + if (heldUntil == NOT_HELD) return false + heldUntil = NOT_HELD + return true + } + + companion object { + private const val NOT_HELD = Long.MIN_VALUE + + @JvmStatic fun keepsMoving(before: Int, after: Int): Boolean = before == after || (before != 0 && after != 0) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt new file mode 100644 index 0000000000..d274269d4c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerOverlayGeometry.kt @@ -0,0 +1,182 @@ +package com.droiddeck.launcher.input + +import android.graphics.Rect +import android.util.DisplayMetrics +import kotlin.math.max +import kotlin.math.min + +internal class ControllerOverlayGeometry( + width: Int, height: Int, private val safe: Rect, metrics: DisplayMetrics, scale: Float, +) { + private val w = width.toFloat() + private val h = height.toFloat() + private val density = metrics.density + private val dpi = metrics.ydpi.takeIf { it in metrics.densityDpi * .6f..metrics.densityDpi * 1.6f } + ?: metrics.densityDpi.toFloat() + private val fit = minOf( + min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)), + (w - safe.left - safe.right).coerceAtLeast(1f) / 1200f, + (h - safe.top - safe.bottom).coerceAtLeast(1f) / 900f, + ) + private val unit = fit * min(scale, 1f) + private val size = fit * scale + + private fun anchor(value: Float, reference: Float, extent: Float, start: Int, end: Int): Float { + val low = start + value * unit + val high = extent - end - (reference - value) * unit + return when { + value < reference / 3f -> low + value > reference * 2f / 3f -> high + else -> (extent / 2f + (value - reference / 2f) * unit).coerceIn(low, max(low, high)) + } + } + + private fun x(ref: Float) = anchor(ref, 1600f, w, safe.left, safe.right) + + private fun y(ref: Float) = max(safe.top + ref * unit, h - safe.bottom - (900f - ref) * unit) + + fun place(elements: List, kit: PadKit, rearButtons: Boolean, trackpads: Boolean): List { + if (!kit.steam) return placeStandardPad(elements, kit) + val leftEdge = safe.left + 52f * density + val middle = (w + safe.left - safe.right) / 2f + val keyboard = Box(max(x(136f), leftEdge + 46f * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } + val row = fitRow(listOfNotNull(keyboard, + Box(max(x(370f), leftEdge + 66f * size), y(852f), 66f, 30f), + Box(middle - 140f * unit, y(850f), 46f, 26f), + Box(middle + 140f * unit, y(850f), 46f, 26f), + Box(x(1230f), y(852f), 66f, 30f)), leftEdge) + val (guide, select, start, qam) = row.takeLast(4) + val positions = shoulders() + face(1375f, 345f, 96f) + mapOf( + InputControl.UP to Box(x(220f), y(345f) - 102.5f * size, 55.5f, 47.5f), + InputControl.RIGHT to Box(x(220f) + 102.5f * size, y(345f), 47.5f, 55.5f), + InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * size, 55.5f, 47.5f), + InputControl.LEFT to Box(x(220f) - 102.5f * size, y(345f), 47.5f, 55.5f), + InputControl.LS to Box(x(290f), y(640f), 96f), + InputControl.RS to Box(x(1310f), y(640f), 96f), + InputControl.SELECT to select, + InputControl.START to start, + InputControl.GUIDE to guide, + InputControl.QAM to qam, + ) + val rear = mapOf( + InputControl.L4 to Box(x(30f), y(470f), 30f, 58f), + InputControl.L5 to Box(x(30f), y(590f), 30f, 58f), + InputControl.R4 to Box(x(1570f), y(470f), 30f, 58f), + InputControl.R5 to Box(x(1570f), y(590f), 30f, 58f), + ) + val pads = mapOf( + InputControl.LEFT_PAD to Box(x(470f), y(360f), 88f), + InputControl.RIGHT_PAD to Box(x(1130f), y(360f), 88f), + ) + val optional = rear.filterKeys { rearButtons } + pads.filterKeys { trackpads } + val placed = elements.mapNotNull { element -> + when { + element.id == KEYBOARD -> row.first().place(element) + element.id != "legacy:${element.control.id}" -> element + element.control in rear || element.control in pads -> optional[element.control]?.place(element) + else -> positions[element.control]?.place(element) ?: element + } + } + val chosen = placed.filter { it.id == "legacy:${it.control.id}" }.map { it.control } + return placed + optional.mapNotNull { (control, box) -> + if (chosen.any { if (control in rear) it in rear else it in pads }) null else box.place(InputSurfaceElement(control, + 0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad)) + } + } + + private fun placeStandardPad(elements: List, kit: PadKit): List { + val leftEdge = safe.left + 52f * density + val middle = (w + safe.left - safe.right) / 2f + val keyboard = Box(max(x(136f), leftEdge + 46f * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } } + val controls = if (kit.playStation) listOf( + InputControl.QAM to Box(x(220f), y(848f), 46f), + InputControl.SELECT to Box(middle - 160f * unit, y(850f), 50f, 30f), + InputControl.GUIDE to Box(middle, y(850f), 46f), + InputControl.START to Box(middle + 160f * unit, y(850f), 50f, 30f), + ) else listOf( + InputControl.QAM to Box(x(220f), y(848f), 46f), + InputControl.SELECT to Box(middle - 110f * unit, y(850f), 38f), + InputControl.GUIDE to Box(middle, y(850f), 46f), + InputControl.START to Box(middle + 110f * unit, y(850f), 38f), + ) + val row = fitRow(listOfNotNull(keyboard) + controls.map { it.second }, leftEdge) + val positions = controls.map { it.first }.zip(row.takeLast(controls.size)).toMap() + shoulders() + + if (kit.playStation) { + face(1350f, 395f, 96f) + dpad(250f, 395f, 125f, kit.dpad) + mapOf( + InputControl.LS to Box(x(565f), y(690f), 100f), + InputControl.RS to Box(x(1035f), y(690f), 100f), + InputControl.L3 to Box(x(565f) - 135f * size, y(690f) - 100f * size, 42f), + InputControl.R3 to Box(x(1035f) + 135f * size, y(690f) - 100f * size, 42f), + ) + } else { + face(1375f, 400f, 94f) + dpad(470f, 675f, 118f, kit.dpad) + mapOf( + InputControl.LS to Box(x(235f), y(400f), 104f), + InputControl.RS to Box(x(1130f), y(690f), 104f), + InputControl.L3 to Box(x(235f) + 150f * size, y(400f) - 110f * size, 42f), + InputControl.R3 to Box(x(1130f) + 160f * size, y(690f) + 100f * size, 42f), + ) + } + return elements.map { element -> + when (element.id) { + KEYBOARD -> row.first().place(element) + "legacy:${element.control.id}" -> positions[element.control]?.place(element) ?: element + else -> element + } + } + } + + private fun shoulders() = mapOf( + InputControl.LT to Box(x(120f), y(96f), 80f, 34f), + InputControl.LB to Box(x(310f), y(96f), 80f, 34f), + InputControl.RB to Box(x(1290f), y(96f), 80f, 34f), + InputControl.RT to Box(x(1480f), y(96f), 80f, 34f), + ) + + private fun face(cx: Float, cy: Float, offset: Float) = mapOf( + InputControl.Y to Box(x(cx), y(cy) - offset * size, 58f), + InputControl.X to Box(x(cx) - offset * size, y(cy), 58f), + InputControl.B to Box(x(cx) + offset * size, y(cy), 58f), + InputControl.A to Box(x(cx), y(cy) + offset * size, 58f), + ) + + private fun dpad(cx: Float, cy: Float, radius: Float, style: DpadStyle): Map { + val inner = radius * if (style == DpadStyle.DISC) .25f else .14f + val depth = (radius - inner) / 2f + val offset = (radius - depth) * size + val side = radius * .25f + return mapOf( + InputControl.UP to Box(x(cx), y(cy) - offset, side, depth), + InputControl.RIGHT to Box(x(cx) + offset, y(cy), depth, side), + InputControl.DOWN to Box(x(cx), y(cy) + offset, side, depth), + InputControl.LEFT to Box(x(cx) - offset, y(cy), depth, side), + ) + } + + private fun fitRow(row: List, start: Float): List { + val end = w - safe.right + val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density) + var edge = start - gap + val pushed = row.map { box -> box.at(max(box.cx, edge + gap + box.width / 2f)).also { edge = it.cx + it.width / 2f } } + edge = end + gap + return pushed.asReversed().map { box -> box.at(min(box.cx, edge - gap - box.width / 2f)).also { edge = it.cx - it.width / 2f } }.asReversed() + } + + private inner class Box(val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw) { + val width get() = max(hw * 2f * size, w * .03f) + + fun at(cx: Float) = Box(cx, cy, hw, hh) + + fun place(element: InputSurfaceElement): InputSurfaceElement { + val height = max(hh * 2f * size, h * .03f) + return element.copy( + x = (cx - width / 2f).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - width)) / w, + y = (cy - height / 2f).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - height)) / h, + width = width / w, height = height / h, + ).bounded() + } + } + + private companion object { + const val KEYBOARD = "builtin:keyboard" + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt new file mode 100644 index 0000000000..907d71c70d --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt @@ -0,0 +1,127 @@ +package com.droiddeck.launcher.input + +import android.graphics.Rect +import com.droiddeck.launcher.input.GamepadGeometry.Box +import kotlin.math.min + +internal class ControllerPortraitGeometry( + private val width: Float, + private val height: Float, + private val safe: Rect, + private val density: Float, +) { + fun place( + elements: List, kit: PadKit, docked: Boolean, scale: Float, + rearButtons: Boolean, trackpads: Boolean, + ): List { + val w = width - safe.left - safe.right + val h = height - safe.top - safe.bottom + if (w <= 0 || h <= 0) return elements + val presented = elements.toMutableList() + val buttons = mutableMapOf() + val rear = presented.filter { it.control in REAR && isStock(it) } + val pads = presented.filter { it.control.isTrackpad && isStock(it) } + if (!docked && kit.steam) { + if (!rearButtons) presented.removeAll(rear) else if (rear.isEmpty()) REAR.forEach { addOptional(presented, it) } + if (!trackpads) presented.removeAll(pads) else if (pads.isEmpty()) { + addOptional(presented, InputControl.LEFT_PAD) + addOptional(presented, InputControl.RIGHT_PAD) + } + } + fun put(control: InputControl, box: Box) { buttons["legacy:${control.id}"] = box } + val reserve = if (docked) 0f else min(60f * density, h * .15f) + val panel = if (docked) h else min(minOf(h * .60f, w * 1.15f, PANEL_DP * density) * scale, h - reserve) + val top = height - safe.bottom - reserve - panel + val unit = min(density, min(w / 275f, panel / 300f)) + val pad = 8f * unit + val gap = 8f * unit + val buttonHeight = 44f * unit + val shoulders = if (docked) listOf(InputControl.LT, InputControl.LB, InputControl.SELECT, InputControl.START, InputControl.RB, InputControl.RT) + else listOf(InputControl.LT, InputControl.LB, InputControl.RB, InputControl.RT) + fun row(controls: List, y: Float, rowHeight: Float, spacing: Float) { + val cell = (w - 2f * pad - (controls.size - 1) * spacing) / controls.size + controls.forEachIndexed { index, control -> + put(control, Box(safe.left + pad + cell / 2f + index * (cell + spacing), y, cell, rowHeight)) + } + } + row(shoulders, top + pad + buttonHeight / 2f, buttonHeight, 4f * unit) + var bodyTop = top + pad + buttonHeight + gap + if (presented.any { it.control in REAR && isStock(it) }) { + val rearHeight = min(56f * unit, (panel - bodyTop + top) * .12f).coerceAtLeast(buttonHeight) + row(REAR, bodyTop + rearHeight / 2f, rearHeight, gap) + bodyTop += rearHeight + gap + } + val floor = height - safe.bottom - reserve - pad + val bodyHeight = floor - bodyTop - gap + if (bodyHeight <= 0f) return elements + val hasLeftPad = presented.any { it.control == InputControl.LEFT_PAD && isStock(it) } + val hasRightPad = presented.any { it.control == InputControl.RIGHT_PAD && isStock(it) } + val hasLeftStick = presented.any { it.control == InputControl.LS && isStock(it) } + val hasRightStick = presented.any { it.control == InputControl.RS && isStock(it) } + val four = hasLeftPad && hasLeftStick || hasRightPad && hasRightStick + val main = min(w * .46f, bodyHeight * .53f) + val second = min(w * .42f, bodyHeight - main) + val mainY = floor - main / 2f + val secondY = bodyTop + second / 2f + val left = safe.left + w * .25f + val right = safe.left + w * .75f + if (four) { + val col = (w - 2f * pad - 3f * gap) / 4f + val stick = min(col, main) + put(InputControl.LEFT_PAD, Box(safe.left + pad + col * .5f, mainY, col, main)) + put(InputControl.LS, Box(safe.left + pad + col * 1.5f + gap, mainY, stick, stick)) + put(InputControl.RS, Box(safe.left + w - pad - col * 1.5f - gap, mainY, stick, stick)) + put(InputControl.RIGHT_PAD, Box(safe.left + w - pad - col * .5f, mainY, col, main)) + } else { + put(if (hasLeftPad) InputControl.LEFT_PAD else InputControl.LS, Box(left, mainY, main, main)) + put(if (hasRightPad) InputControl.RIGHT_PAD else InputControl.RS, Box(right, mainY, main, main)) + } + val radius = second / 2f + val armWidth = radius * if (kit.dpad == DpadStyle.CROSS) .37f else .25f + val inner = if (kit.dpad == DpadStyle.ARROWS) radius * .14f else armWidth + val depth = radius - inner + val distance = (radius + inner) / 2f + put(InputControl.UP, Box(left, secondY - distance, armWidth * 2f, depth)) + put(InputControl.RIGHT, Box(left + distance, secondY, depth, armWidth * 2f)) + put(InputControl.DOWN, Box(left, secondY + distance, armWidth * 2f, depth)) + put(InputControl.LEFT, Box(left - distance, secondY, depth, armWidth * 2f)) + val face = second * .34f + val spread = second * .30f + put(InputControl.Y, Box(right, secondY - spread, face, face)) + put(InputControl.X, Box(right - spread, secondY, face, face)) + put(InputControl.B, Box(right + spread, secondY, face, face)) + put(InputControl.A, Box(right, secondY + spread, face, face)) + if (!docked) { + val ids = listOf(KEYBOARD, "legacy:guide", "legacy:select", "legacy:start", "legacy:qam") + .filter { id -> presented.any { it.id == id } } + val inset = min(52f * density, w * .17f) + val rowWidth = (w - inset - pad - gap * (ids.size - 1)) / ids.size.coerceAtLeast(1) + val rowHeight = min(reserve * .8f, 44f * unit) + ids.forEachIndexed { i, id -> + val center = safe.left + inset + rowWidth / 2f + i * (rowWidth + gap) + buttons[id] = Box(center, height - safe.bottom - reserve / 2f, rowWidth, rowHeight) + } + } + return presented.map { element -> + val box = buttons[element.id] + if (box == null) element else element.copy( + x = box.left / width, y = box.top / height, width = box.width / width, height = box.height / height, + ).bounded() + } + } + + private fun isStock(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" + + private fun addOptional(elements: MutableList, control: InputControl) { + if (elements.none { it.control == control && isStock(it) }) { + elements += InputSurfaceElement(control, 0f, 0f, 0f, 0f, floating = false, + buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad) + } + } + + private companion object { + const val KEYBOARD = "builtin:keyboard" + const val PANEL_DP = 504f + val REAR = listOf(InputControl.L4, InputControl.L5, InputControl.R5, InputControl.R4) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt index 1d8bf5d682..277a7b5d11 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt @@ -14,7 +14,8 @@ object DualScreen { const val MODE_AUTO = "auto" const val MODE_ON = "on" const val MODE_OFF = "off" - val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF) + const val MODE_SWAPPED = "swapped" + val modes = listOf(MODE_AUTO, MODE_ON, MODE_SWAPPED, MODE_OFF) private const val TYPE_INTERNAL = 1 private const val TYPE_EXTERNAL = 2 private val knownModels = setOf("retroid pocket duo", "ayn thor") @@ -23,6 +24,14 @@ object DualScreen { @Volatile private var takenDisplays: Set = emptySet() private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) } + fun menuOwnsController(open: Boolean, docked: Boolean, optIn: Boolean): Boolean = open && (!docked || optIn) + + fun menuReturnsOnStart(selected: SecondScreenMode, menuWasShown: Boolean, menuUp: Boolean): Boolean = + !menuUp && (selected == SecondScreenMode.MENU || menuWasShown) + + fun menuIdleOnBottom(open: Boolean, docked: Boolean, pinned: Boolean, optIn: Boolean): Boolean = + docked && (open || pinned) && !menuOwnsController(open, docked, optIn) + fun yieldsBottom(model: String): Boolean = model.trim().lowercase().let { m -> knownModels.any(m::startsWith) } fun taken(displayId: Int): Boolean = displayId in takenDisplays @@ -91,7 +100,7 @@ object DualScreen { fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? = when (mode) { MODE_OFF -> null - MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId) + MODE_ON, MODE_SWAPPED -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId) else -> if (dockedToDisplay(displayManager, primaryDisplayId)) null else builtInDisplay(displayManager, primaryDisplayId) }?.takeUnless { taken(it.displayId) } diff --git a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java index 4675546d61..dc847e90ad 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java +++ b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java @@ -1,5 +1,9 @@ package com.droiddeck.launcher.input; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Process; +import android.os.SystemClock; import android.util.Log; import java.io.File; @@ -128,6 +132,16 @@ public class FakeInputWriter { private static final Object RING_LOCK = new Object(); private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS]; + private static final long AXIS_REPORT_INTERVAL_MS = 4; + + private static final class Pacing { + static final Handler HANDLER; + static { + HandlerThread thread = new HandlerThread("pad-pacing", Process.THREAD_PRIORITY_DISPLAY); + thread.start(); + HANDLER = new Handler(thread.getLooper()); + } + } static { System.loadLibrary("sdnative"); @@ -156,6 +170,9 @@ public class FakeInputWriter { private boolean hasChanges = false; private boolean pendingFullResend = false; private boolean forceResend = false; + private final AxisPacing axisPacing = new AxisPacing(AXIS_REPORT_INTERVAL_MS); + private final PadState pacedPad = new PadState(); + private final Runnable pacedWrite = this::writePacedPad; public FakeInputWriter(String fakeInputPath, int slot) { this.slot = slot; @@ -711,10 +728,12 @@ public class FakeInputWriter { } public synchronized void close() { + cancelPacedWrite(); isOpen = false; } public synchronized void reset() { + cancelPacedWrite(); if (!isOpen && !open()) return; @@ -822,6 +841,53 @@ public class FakeInputWriter { } public synchronized void writePad(PadState state) { + long now = SystemClock.uptimeMillis(); + long due = axisPacing.dueAt(now, !pendingFullResend && onlyAxesMove(state)); + if (due > now) { + pacedPad.copyFrom(state); + if (axisPacing.hold(due)) + Pacing.HANDLER.postAtTime(pacedWrite, due); + return; + } + cancelPacedWrite(); + writePadNow(state); + } + + private synchronized void writePacedPad() { + if (axisPacing.release(SystemClock.uptimeMillis())) + writePadNow(pacedPad); + } + + private void cancelPacedWrite() { + if (axisPacing.cancel()) + Pacing.HANDLER.removeCallbacks(pacedWrite); + } + + private boolean onlyAxesMove(PadState state) { + for (int i = 0; i < 10; i++) { + if (prevButtonStates[i] != state.isDown(i)) + return false; + } + return prevButtonStates[SNAPSHOT_IDX_MODE] == state.isDown(PadState.GUIDE) + && prevQam == state.isDown(PadState.QAM) + && prevHatX == state.hatX() && prevHatY == state.hatY() + && AxisPacing.keepsMoving(prevThumbLX, stickValue(state.leftX)) + && AxisPacing.keepsMoving(prevThumbLY, stickValue(state.leftY)) + && AxisPacing.keepsMoving(prevThumbRX, stickValue(state.rightX)) + && AxisPacing.keepsMoving(prevThumbRY, stickValue(state.rightY)) + && AxisPacing.keepsMoving(prevTriggerL, triggerValue(state.leftTrigger)) + && AxisPacing.keepsMoving(prevTriggerR, triggerValue(state.rightTrigger)); + } + + private static int stickValue(float value) { + return (int) (value * 32767); + } + + private static int triggerValue(float value) { + return (int) (value * 255); + } + + private void writePadNow(PadState state) { if (!isOpen && !open()) return; @@ -845,10 +911,10 @@ public class FakeInputWriter { hasChanges = true; } - int lx = (int) (state.leftX * 32767); - int ly = (int) (state.leftY * 32767); - int rx = (int) (state.rightX * 32767); - int ry = (int) (state.rightY * 32767); + int lx = stickValue(state.leftX); + int ly = stickValue(state.leftY); + int rx = stickValue(state.rightX); + int ry = stickValue(state.rightY); if (forceResend || lx != prevThumbLX) { prevThumbLX = lx; @@ -867,8 +933,8 @@ public class FakeInputWriter { writeEvent(EV_ABS, ABS_RY, ry); } - int tl = (int) (state.leftTrigger * 255); - int tr = (int) (state.rightTrigger * 255); + int tl = triggerValue(state.leftTrigger); + int tr = triggerValue(state.rightTrigger); if (forceResend || tl != prevTriggerL) { prevTriggerL = tl; writeEvent(EV_ABS, ABS_BRAKE, tl); @@ -895,6 +961,8 @@ public class FakeInputWriter { if (!flushBuffer()) { Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable"); pendingFullResend = true; + } else { + axisPacing.wrote(SystemClock.uptimeMillis()); } } forceResend = false; diff --git a/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt b/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt new file mode 100644 index 0000000000..39a916fbcd --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/FloatingSteamOverlay.kt @@ -0,0 +1,93 @@ +package com.droiddeck.launcher.input + +import android.graphics.Rect +import kotlin.math.min + +internal class FloatingSteamOverlay(width: Int, height: Int, safe: Rect, density: Float) { + private val w = width.toFloat() + private val h = height.toFloat() + private val left = safe.left / w + private val top = safe.top / h + private val right = 1f - safe.right / w + private val bottom = 1f - safe.bottom / h + private val gap = 3f * density + private val bottomPadding = 14f * density + private val dp = min(density, min(width, height) / 250f) + + fun place(elements: List, lowerShortcuts: Boolean, + rearButtons: Boolean?, trackpads: Boolean?): List { + val visible = elements.filter { element -> + when { + !isStock(element) -> true + element.control in rear -> rearButtons != false + element.control.isTrackpad -> trackpads != false + else -> true + } + } + val lowered = if (lowerShortcuts) lower(visible) else visible + if (rearButtons != true && trackpads != true) return lowered + val placed = lowered.toMutableList() + val chosen = lowered.filter(::isStock).map { it.control } + fun add(control: InputControl, x: Float, y: List, widthDp: Int, heightDp: Int, shape: InputButtonShape) { + if (chosen.any { if (control in rear) it in rear else it.isTrackpad }) return + val element = InputSurfaceElement(control, 0f, 0f, (widthDp * dp / w).coerceAtLeast(.03f), + (heightDp * dp / h).coerceAtLeast(.03f), floating = false, buttonShape = shape, showLabel = !control.isTrackpad) + findSpace(element, x, y, placed)?.let(placed::add) + } + if (rearButtons == true) { + add(InputControl.L4, .045f, listOf(.48f, .38f, .58f), 28, 46, InputButtonShape.PILL) + add(InputControl.L5, .045f, listOf(.62f, .72f, .53f), 28, 46, InputButtonShape.PILL) + add(InputControl.R4, .955f, listOf(.48f, .38f, .58f), 28, 46, InputButtonShape.PILL) + add(InputControl.R5, .955f, listOf(.62f, .72f, .53f), 28, 46, InputButtonShape.PILL) + } + if (trackpads == true) { + val rows = listOf(.45f, .36f, .54f, .27f, .63f) + add(InputControl.LEFT_PAD, .34f, rows, 68, 63, InputButtonShape.ROUNDED) + add(InputControl.RIGHT_PAD, .66f, rows, 68, 63, InputButtonShape.ROUNDED) + } + return placed + } + + private fun lower(elements: List): List { + val row = elements.filter { isStock(it) && it.control in shortcuts } + val occupied = (elements - row.toSet()).toMutableList() + val moved = mutableMapOf() + for (element in row.sortedBy { shortcuts.getValue(it.control) }) { + val y = bottom - bottomPadding / h - element.height / 2f + val position = findSpace(element, shortcuts.getValue(element.control), listOf(y, y - .07f), occupied) + ?: return elements + occupied += position + moved[element.id] = position + } + return elements.map { moved[it.id] ?: it } + } + + private fun findSpace(element: InputSurfaceElement, x: Float, rows: List, + occupied: List): InputSurfaceElement? { + val maxX = right - element.width + val maxY = bottom - element.height + if (maxX < left || maxY < top) return null + for (y in rows) { + for (dx in horizontalOffsets) { + val candidate = element.copy( + x = (x + dx - element.width / 2f).coerceIn(left, maxX), + y = (y - element.height / 2f).coerceIn(top, maxY), + ) + if (occupied.none { overlaps(candidate, it) }) return candidate + } + } + return null + } + + private fun overlaps(a: InputSurfaceElement, b: InputSurfaceElement): Boolean = + a.x < b.x + b.width + gap / w && b.x < a.x + a.width + gap / w && + a.y < b.y + b.height + gap / h && b.y < a.y + a.height + gap / h + + private fun isStock(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" + + private companion object { + val rear = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5) + val shortcuts = mapOf(InputControl.GUIDE to .23f, InputControl.SELECT to .41f, InputControl.START to .59f, InputControl.QAM to .77f) + val horizontalOffsets = listOf(0f, -.035f, .035f, -.07f, .07f, -.105f, .105f) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt index 191760003d..ab626a4246 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt @@ -3,6 +3,12 @@ package com.droiddeck.launcher.input import android.view.KeyEvent object GuestKeys { + fun normalizeKeyboardEscape(event: KeyEvent): KeyEvent { + if (!isKeyboardEscape(event.keyCode, event.scanCode)) return event + return KeyEvent(event.downTime, event.eventTime, event.action, KeyEvent.KEYCODE_ESCAPE, + event.repeatCount, event.metaState, event.deviceId, event.scanCode, event.flags, event.source) + } + /** Sends [event] as evdev presses, with Shift around characters typed by a keyboard that has no Shift key; false when it has no evdev code. */ fun send(event: KeyEvent, sendKey: (code: Int, down: Boolean) -> Unit): Boolean { val down = event.action == KeyEvent.ACTION_DOWN diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt index 5f0b082c8c..4683aece97 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt @@ -11,6 +11,10 @@ import java.util.UUID object InputLibraries { private const val VERSION = 14 + private val redesignVersions = 15..16 + private const val KIT_DPAD = "kit:dpad" + private const val KEYBOARD = "builtin:keyboard" + private const val REDESIGN_BACKUP = "library-before-controller-revert" private const val KEY = "library" private const val RECOVERY = "library-recovery." const val OVERLAY = "builtin.overlay" @@ -23,10 +27,18 @@ object InputLibraries { fun read(context: Context): InputLibrary { val p = prefs(context) val raw = p.getString(KEY, null) - val decoded = raw?.let(::decode) + val decoded = raw?.let { decode(it, context) } if (raw != null && decoded == null) return scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, migrate(context)))) var library = decoded ?: scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, migrate(context)))) val version = raw?.let { JSONObject(it).getInt("version") } ?: 0 + if (version in redesignVersions && raw != null) { + val encoded = encode(library) + if (encoded.length > 2_000_000) return library + if (!commitWithBackup(p, raw, REDESIGN_BACKUP, encoded)) { + android.util.Log.e("InputLibraries", "Could not save the restored input library") + return library + } + } if (version < 5) library = scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, library))) if (version < 11) library = neutralStockLayouts(library) if (version < 10) library = restyleGamepads(context, library) @@ -75,20 +87,35 @@ object InputLibraries { fun update(context: Context, change: (InputLibrary) -> InputLibrary): InputLibrary { val p = prefs(context) val stored = p.getString(KEY, null) - val invalid = stored != null && decode(stored) == null + val invalid = stored != null && decode(stored, context) == null require(!invalid || runCatching { JSONObject(stored!!).getInt("version") }.getOrNull()?.let { it <= VERSION } != false) { "The saved input library cannot be edited by this version." } val updated = change(read(context)).validate() - if (invalid) { + val backupKey = when { + invalid -> RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8)) + stored != null && p.getString(KEY, null) == stored && + JSONObject(stored).getInt("version") in redesignVersions -> REDESIGN_BACKUP + else -> null + } + if (backupKey != null) { val encoded = encode(updated) require(encoded.length <= 2_000_000) { "The input library is too large to save." } - check(p.edit().putString(RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8)), stored) - .putString(KEY, encoded).commit()) { "Could not save the input library and its recovery copy." } + check(commitWithBackup(p, requireNotNull(stored), backupKey, encoded)) { + "Could not save the input library and its recovery copy." + } } else write(context, updated) return updated } + private fun commitWithBackup(prefs: android.content.SharedPreferences, raw: String, backupKey: String, encoded: String): Boolean { + val previousBackup = prefs.getString(backupKey, null) + if (prefs.edit().putString(backupKey, raw).putString(KEY, encoded).commit()) return true + // SharedPreferences updates its in-memory values even when the disk write fails. + prefs.edit().putString(KEY, raw).putString(backupKey, previousBackup).apply() + return false + } + private fun write(context: Context, library: InputLibrary) { val encoded = encode(library.validate()) require(encoded.length <= 2_000_000) { "The input library is too large to save." } @@ -297,15 +324,27 @@ object InputLibraries { layout.copy(screen = screen) }) + private fun encodeElements(list: List) = JSONArray().also { elements -> + for (e in list) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name) + .put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble()) + .put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image) + .put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown)) + } + + private fun decodeElements(array: JSONArray) = array.objects(64).map { e -> + InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(), + e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(), + e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"), + e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""), + e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false)) + } + internal fun encode(library: InputLibrary): String { val layouts = JSONArray() for (layout in library.layouts) { - val elements = JSONArray() - for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name) - .put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble()) - .put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image) - .put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown)) - layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements) + val encoded = JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", encodeElements(layout.elements)) + if (layout.rotated.isNotEmpty()) encoded.put("rotated", encodeElements(layout.rotated)).put("rotatedAspect", layout.rotatedAspect.toDouble()).put("rotatedScale", layout.rotatedScale.toDouble()) + layouts.put(encoded .put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble()) .put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL)) } @@ -336,22 +375,27 @@ object InputLibraries { .put("profiles", profiles).put("layouts", layouts).put("bindings", bindings).toString() } - internal fun decode(raw: String): InputLibrary? = runCatching { + internal fun decode(raw: String, context: Context? = null): InputLibrary? = runCatching { require(raw.length <= 2_000_000) - val doc = JSONObject(raw); require(doc.getInt("version") in 2..VERSION) + val doc = JSONObject(raw) + val version = doc.getInt("version") + val restore = context != null && version in redesignVersions + require(version in 2..VERSION || restore) + val generated = mutableSetOf() val layouts = doc.getJSONArray("layouts").objects(256).map { layout -> - val elements = layout.getJSONArray("elements").objects(64).map { e -> - InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(), - e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(), - e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"), - e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""), - e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false)) - } - SavedInputLayout(layout.getString("id"), layout.getString("name"), elements, InputLayoutTemplate.valueOf(layout.getString("template")), + val stored = decodeElements(layout.getJSONArray("elements")) + val id = layout.getString("id") + val origin = layout.optionalString("origin") + val followsGamepad = restore && !layout.optBoolean("kitless") && + (id == OVERLAY || origin == OVERLAY) && + stored.none { it.id.startsWith("legacy:") || it.id == KIT_DPAD || it.id == KEYBOARD } + if (followsGamepad) generated += id + SavedInputLayout(id, layout.getString("name"), if (restore) stored.map { it.bounded() } else stored, InputLayoutTemplate.valueOf(layout.getString("template")), InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100), layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()), - InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), layout.optionalString("origin"), - layout.optDouble("scale", 1.0).toFloat()) + InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), origin, + layout.optDouble("scale", 1.0).toFloat(), layout.optJSONArray("rotated")?.let(::decodeElements).orEmpty(), + layout.optDouble("rotatedAspect", 0.0).toFloat(), layout.optDouble("rotatedScale", layout.optDouble("scale", 1.0)).toFloat()) } val bindings = doc.getJSONArray("bindings").objects(512).map { b -> val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) } @@ -378,9 +422,41 @@ object InputLibraries { value.optBoolean("profileSelected", profile != InputProfiles.AUTO || parts.length() == 0)) } }.orEmpty() - InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections).validate() + val library = InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections) + (if (restore) restoreGamepads(requireNotNull(context), library, generated) else library).validate() }.getOrNull() + private fun restoreGamepads(context: Context, library: InputLibrary, generated: Set): InputLibrary { + val (display, metrics) = primaryDisplay(context) + val height = metrics.heightPixels.coerceAtLeast(1) + val layouts = library.layouts.map { layout -> + if (layout.id !in generated) return@map layout + val width = if (layout.aspect > 0f) (layout.aspect * height).toInt().coerceAtLeast(1) + else metrics.widthPixels.coerceAtLeast(1) + val gamepad = LegacyGamepadLayout(display, width, height, scale = layout.scale).elements() + layout.copy(elements = gamepad.take(64 - layout.elements.size) + layout.elements, + aspect = (width.toFloat() / height).coerceIn(.05f, 20f)) + } + val byId = layouts.associateBy { it.id } + val bindings = library.bindings.map { preset -> + val layout = byId[preset.layoutId] ?: return@map preset + val elements = layout.elements.associateBy { it.id } + val defaults = layout.elements.mapNotNull { element -> + val action = when (element.id) { + KEYBOARD -> InputAction.Command(InputCommand.KEYBOARD) + KIT_DPAD -> InputAction.Native() + else -> return@mapNotNull null + } + element.id to action + }.toMap() + preset.copy( + elements = defaults + preset.elements.filter { (id, action) -> elements[id]?.let { action.validFor(it) } == true }, + clicks = preset.clicks.filter { (id, action) -> elements[id]?.hasClick == true && action.validForClick() }, + ) + } + return library.copy(layouts = layouts, bindings = bindings) + } + private fun JSONArray.objects(limit: Int): List { require(length() <= limit) return (0 until length()).map { getJSONObject(it) } diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt index 0e5ed4261f..9532f51778 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt @@ -22,8 +22,12 @@ data class SavedInputLayout( val aspect: Float = 0f, val origin: String? = null, val scale: Float = 1f, + val rotated: List = emptyList(), + val rotatedAspect: Float = 0f, + val rotatedScale: Float = 1f, ) { val editable get() = template == InputLayoutTemplate.CUSTOM + val overlay get() = (origin ?: id).let { it == InputLibraries.OVERLAY || it.startsWith("migrated.layout.") } val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } } fun withQuickButton(button: InputCommand, shown: Boolean) = copy(style = style.copy(hidden = if (shown) style.hidden - button else style.hidden + button)) @@ -249,6 +253,8 @@ data class InputLibrary( for (layout in layouts) { require(layout.style.opacity in 1..100 && layout.style.hidden.all { it in QUICK_BUTTONS }) require(layout.aspect == 0f || layout.aspect.isFinite() && layout.aspect in .05f..20f) + require(layout.rotated.isEmpty() || layout.rotatedAspect.isFinite() && layout.rotatedAspect in .05f..20f && layout.rotatedScale.isFinite() && layout.rotatedScale in .5f..2f) + require(layout.rotated.size <= 64 && layout.rotated.all { r -> listOf(r.x, r.y, r.width, r.height).all { it.isFinite() } }) require(layout.scale.isFinite() && layout.scale in .5f..2f) inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id }) for (e in layout.elements) { diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt index e7e1c58a36..888e9bc260 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt @@ -3,6 +3,8 @@ package com.droiddeck.launcher.input import android.content.Context import org.json.JSONArray import org.json.JSONObject +import kotlin.math.max +import kotlin.math.min enum class InputElementKind(val control: InputControl) { BUTTON(InputControl.A), STICK(InputControl.LS), TRACKPAD(InputControl.LEFT_PAD), @@ -63,6 +65,27 @@ internal fun List.scaled(factor: Float): List.groupOf(e: InputSurfaceElement) = if (e.dpadPiece) filter { it.dpadPiece } else listOf(e) + +internal fun List.frame(): InputSurfaceElement { + val left = minOf { it.x }; val top = minOf { it.y } + return first().copy(x = left, y = top, width = maxOf { it.x + it.width } - left, height = maxOf { it.y + it.height } - top) +} + +internal fun List.resizedAroundCentre(factor: Float): List { + if (isEmpty()) return this + val f = frame() + val k = factor.coerceIn(.03f / minOf { min(it.width, it.height) }, 1f / max(f.width, f.height)) + val w = f.width * k; val h = f.height * k + val left = (f.x + f.width / 2 - w / 2).coerceIn(0f, 1f - w) + val top = (f.y + f.height / 2 - h / 2).coerceIn(0f, 1f - h) + return map { it.copy(x = left + (it.x - f.x) * k, y = top + (it.y - f.y) * k, width = it.width * k, height = it.height * k).bounded() } +} + internal fun List.withPositionsOf(defaults: List): List { val byId = defaults.associateBy { it.id } return map { e -> byId[e.id]?.let { d -> e.copy(x = d.x, y = d.y, width = d.width, height = d.height).bounded() } ?: e } diff --git a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt index 2a36489e85..a944ec28ef 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt @@ -197,19 +197,8 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid fun regenerate(stored: List): List = withGeometry(stored, elements()) - fun rescale(stored: List, from: LegacyGamepadLayout): List { - val before = from.elements().associateBy { it.id } - val after = elements().associateBy { it.id } - return stored.map { e -> - val b = before[e.id] ?: return@map e - val a = after[e.id] ?: return@map e - val w = (a.width * e.width / b.width).coerceIn(.03f, 1f) - val h = (a.height * e.height / b.height).coerceIn(.03f, 1f) - val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2) - val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2) - e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded() - } - } + fun rescale(stored: List, from: LegacyGamepadLayout): List = + rescaleBetween(stored, from.elements(), elements()) fun buttonsOnly(stored: List): List { val inset = dp(BUTTONS_ONLY_INSET_DP) @@ -345,7 +334,6 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid const val STICK_REACH = 1.25f const val LEGACY_DPAD_RADIUS_DP = 26f const val LEGACY_DPAD_OFFSET_DP = 52f - val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) const val KEYBOARD_ID = "builtin:keyboard" const val KEYBOARD_RADIUS_DP = 18f const val KEYBOARD_X_DP = 90f @@ -360,3 +348,22 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4) } } + +internal fun rescaleBetween(stored: List, from: List, to: List, + sizeFrom: List = from, sizeTo: List = to): List { + val before = from.associateBy { it.id } + val after = to.associateBy { it.id } + val smaller = sizeFrom.associateBy { it.id } + val larger = sizeTo.associateBy { it.id } + return stored.map { e -> + val b = before[e.id] ?: return@map e + val a = after[e.id] ?: return@map e + val sb = smaller[e.id] ?: b + val sa = larger[e.id] ?: a + val w = (sa.width * e.width / sb.width).coerceIn(.03f, 1f) + val h = (sa.height * e.height / sb.height).coerceIn(.03f, 1f) + val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2) + val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2) + e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt index ee3a6560ae..142846a04f 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt @@ -72,12 +72,15 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo render() } - private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean) + private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean, + val kit: PadKit?, val optional: Pair) private fun placed(): List { - val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly) + val optional = OnScreenLayout.optionalControls(context) + val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly, PadKit.forOverlay(context, layout), optional) return placements.getOrPut(key) { - OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock) + OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock, + rearButtons = optional.first, trackpads = optional.second) } } @@ -88,11 +91,16 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo isQuickHidden -> elements.filter { it.id == "builtin:keyboard" || it.alwaysShown } else -> elements }) - val style = layout?.style ?: InputSurfaceStyle() - surface.updateStyle(style) - quickToggle.tint = style.tint - quickToggle.alpha = style.opacity / 100f quickToggle.visibility = if (isButtonsOnly || isPinnedOnly || layout == null || dock != null) GONE else VISIBLE + refreshAppearance() + } + + private fun refreshAppearance() { + val style = layout?.style ?: InputSurfaceStyle() + val artwork = PadKit.forOverlay(context, layout) + surface.updateStyle(style, artwork) + quickToggle.tint = style.tint.takeUnless { artwork != null } + quickToggle.alpha = style.opacity / 100f quickToggle.invalidate() } @@ -125,7 +133,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo params.bottomMargin = bottom quickToggle.layoutParams = params } - val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0) + val fresh = OnScreenLayout.safeInsets(insets, dock != null) if (fresh != safe) { safe.set(fresh) render() diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt index 9fbb01c7ad..ad5d8e2701 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -2,12 +2,19 @@ package com.droiddeck.launcher.input import android.content.Context import android.graphics.Rect +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt object OnScreenLayout { + internal fun supportsFloatingSteamControls(controller: String, layout: SavedInputLayout?) = + layout?.overlay == true && + (controller == SessionPrefs.CONTROLLER_DECK || controller == SessionPrefs.CONTROLLER_STEAM) + data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) { companion object { fun deck(portrait: Boolean, gamepad: SavedInputLayout?): Dock { @@ -23,31 +30,96 @@ object OnScreenLayout { private const val TOLERANCE = .01f private const val KEYBOARD_ID = "builtin:keyboard" + private val REAR = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5) + private val BAR = setOf(InputControl.GUIDE, InputControl.QAM) - fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, - buttonsOnly: Boolean = false, dock: Dock? = null): List { - val stored = layout?.elements ?: return emptyList() - if (width <= 0 || height <= 0) return stored + fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect, + buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null, + trackpads: Boolean? = null): List { + if (saved == null) return emptyList() + if (width <= 0 || height <= 0) return saved.elements + val layout = oriented(saved, dock?.portrait ?: (height > width)) + val stored = layout.elements val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale) - val (reference, generated) = reference(context, layout, width, height) + val (reference, matched) = reference(context, layout, width, height) if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe) + if (dock?.portrait == true && !dock.grips && !matched && layout.aspect > 0f && layout.aspect < 1f && stored.any(::isGamepad)) + return cluster(stored.filterNot { it.alwaysShown || isGamepad(it) && (it.id == KEYBOARD_ID || it.control in BAR) }, layout.aspect, width, height, safe) + val generated = matched || PadKit.forOverlay(context, layout) != null && stored.any(::isGamepad) && + (dock != null || height > width && layout.aspect >= 1f || height <= width && layout.aspect > 0f && layout.aspect < 1f) val gamepad = if (generated) stored.filter(::isGamepad) else emptyList() val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe) - val placed = when { + val regenerated = when { gamepad.isEmpty() -> emptyList() dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right) else -> generator.regenerate(gamepad) } + val placed = regenerated + gamepad.filter { g -> dock == null && optional(g) && regenerated.none { it.id == g.id } } val byId = (placed + others).associateBy { it.id } - return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } } + val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } } + val kit = PadKit.forOverlay(context, layout) ?: return ordered + if (generated && + ControllerPrefs.layout(context, reference.first.toInt(), reference.second.toInt()).isEmpty() && + ControllerPrefs.layout(context, width, height).isEmpty()) { + if (dock != null || height > width) { + return ControllerPortraitGeometry(width.toFloat(), height.toFloat(), safe, context.resources.displayMetrics.density) + .place(ordered, kit, dock != null, layout.scale, rearButtons == true, trackpads == true) + } + return ControllerOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale) + .place(ordered, kit, rearButtons == true, trackpads == true) + } + if (dock != null || !kit.steam) return ordered + return FloatingSteamOverlay(width, height, safe, context.resources.displayMetrics.density) + .place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads) } - fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List = - elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect()) + fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout = oriented(layout, height > width) + + private fun oriented(layout: SavedInputLayout, portrait: Boolean): SavedInputLayout { + if (layout.rotated.isEmpty() || layout.aspect <= 0f || (layout.aspect < 1f) == portrait || (layout.rotatedAspect < 1f) != portrait) return layout + val rotated = layout.rotated.associateBy { it.id } + return layout.copy(elements = layout.elements.map { e -> rotated[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } ?: e } + + layout.rotated.filter { r -> optional(r) && layout.elements.none { it.id == r.id } }, + aspect = layout.rotatedAspect, scale = layout.rotatedScale, rotated = emptyList(), rotatedAspect = 0f, rotatedScale = 1f) + } + + fun withFrame(context: Context, saved: SavedInputLayout, elements: List, aspect: Float, scale: Float = saved.scale): SavedInputLayout { + val (_, metrics) = InputLibraries.primaryDisplay(context) + val generated = generatedSize(context, saved, metrics.widthPixels, metrics.heightPixels) != null + val portraitMain = saved.aspect > 0f && saved.aspect < 1f + if (aspect <= 0f || aspect >= 1f || portraitMain && !generated) { + val rotated = if (aspect >= 1f && portraitMain && !generated) Triple(saved.elements, saved.aspect, saved.scale) else Triple(saved.rotated, saved.rotatedAspect, saved.rotatedScale) + return saved.copy(elements = elements, aspect = aspect, scale = scale, rotated = rotated.first, + rotatedAspect = if (rotated.first.isEmpty()) 0f else rotated.second, rotatedScale = if (rotated.first.isEmpty()) 1f else rotated.third) + } + val main = if (portraitMain) 1f / saved.aspect else saved.aspect.takeIf { it > 0f } ?: (1f / aspect) + val ids = elements.associateBy { it.id } + val kept = saved.elements.mapNotNull { e -> ids[e.id]?.copy(x = e.x, y = e.y, width = e.width, height = e.height) } + val added = fit(elements.filter { d -> !optional(d) && saved.elements.none { it.id == d.id } }, aspect, 1f, (main * 1000).roundToInt().coerceAtLeast(1), 1000, Rect()) + return saved.copy(elements = kept + added, aspect = main, rotated = elements, rotatedAspect = aspect, rotatedScale = scale) + } + + fun optionalControls(context: Context): Pair { + val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad + return SessionPrefs.oscRearButtons(context).takeIf { steam } to SessionPrefs.oscTrackpads(context).takeIf { steam } + } + + fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false, safe: Rect = Rect()): List { + val (rear, pads) = optionalControls(context) + return elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, safe, + rearButtons = rear, trackpads = pads) + } fun editorFrame(layout: SavedInputLayout, displayed: List): List { val byId = displayed.associateBy { it.id } - return layout.elements.map { byId[it.id] ?: it } + return layout.elements.map { byId[it.id] ?: it } + displayed.filter { d -> + optional(d) && layout.elements.none { it.id == d.id } + } + } + + fun safeInsets(insets: android.view.WindowInsets?, docked: Boolean): Rect { + val cutout = if (android.os.Build.VERSION.SDK_INT >= 28) insets?.displayCutout else null + return Rect(cutout?.safeInsetLeft ?: 0, if (docked) 0 else cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0) } fun fit(elements: List, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List { @@ -63,6 +135,23 @@ object OnScreenLayout { } } + private fun cluster(elements: List, aspect: Float, width: Int, height: Int, safe: Rect): List { + if (elements.isEmpty()) return elements + val left = elements.minOf { it.x } * aspect + val top = elements.minOf { it.y } + val spanX = (elements.maxOf { it.x + it.width } * aspect - left).coerceAtLeast(.0001f) + val spanY = (elements.maxOf { it.y + it.height } - top).coerceAtLeast(.0001f) + val w = (width - safe.left - safe.right).toFloat().coerceAtLeast(1f) + val h = (height - safe.top - safe.bottom).toFloat().coerceAtLeast(1f) + val scale = minOf(w / aspect, w / spanX, h / spanY) + val originX = safe.left + (w - spanX * scale) / 2f - left * scale + val originY = safe.top + (h - spanY * scale) / 2f - top * scale + return elements.map { e -> + e.copy(x = (originX + e.x * aspect * scale) / width, y = (originY + e.y * scale) / height, + width = e.width * aspect * scale / width, height = e.height * scale / height) + } + } + private fun anchor(start: Float, size: Float, reference: Float, actual: Float, scale: Float): Float { val centre = start + size / 2f val scaled = size * reference * scale @@ -73,6 +162,8 @@ object OnScreenLayout { } } + private fun optional(e: InputSurfaceElement) = e.id == "legacy:${e.control.id}" && (e.control.isTrackpad || e.control in REAR) + private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair? = @@ -86,7 +177,7 @@ object OnScreenLayout { if (gamepad.any { it.id.startsWith("legacy:") }) { val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() } ?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] } - val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f } + val aspectSize = layout.aspect.takeIf { layout.overlay && it > 0f } ?.let { (it * height).roundToInt().coerceAtLeast(1) to height } for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) { val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale) diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt b/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt new file mode 100644 index 0000000000..750bceb5c9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/PadKit.kt @@ -0,0 +1,54 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import com.droiddeck.launcher.session.SessionPrefs + +internal enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS } +internal enum class DpadStyle { CROSS, DISC, ARROWS } +internal enum class StickCap { RINGED, DISHED, KNURLED } + +internal enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) { + STEAM_DECK(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED), + STEAM_CONTROLLER(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED), + XBOX(FaceGlyphs.COLOR_LETTERS, DpadStyle.DISC, StickCap.DISHED, xbox = true), + DUALSHOCK(FaceGlyphs.COLOR_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED), + DUALSENSE(FaceGlyphs.MONO_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED); + + val steam get() = this == STEAM_DECK || this == STEAM_CONTROLLER + val playStation get() = this == DUALSHOCK || this == DUALSENSE + + fun label(control: InputControl): String = when (control) { + InputControl.LB -> if (xbox) "LB" else "L1" + InputControl.RB -> if (xbox) "RB" else "R1" + InputControl.LT -> if (xbox) "LT" else "L2" + InputControl.RT -> if (xbox) "RT" else "R2" + else -> control.label + } + + /** What the player calls [control] on this controller. */ + fun name(control: InputControl): String = if (!playStation) label(control) else when (control) { + InputControl.A -> "Cross" + InputControl.B -> "Circle" + InputControl.X -> "Square" + InputControl.Y -> "Triangle" + else -> label(control) + } + + fun native(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" && element.icon == 0 && + (element.name == element.control.label || element.name == name(element.control)) + + fun artwork(element: InputSurfaceElement) = element.image.isEmpty() && element.showLabel && + (native(element) || element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD) + + companion object { + fun forOverlay(context: Context, layout: SavedInputLayout?): PadKit? = + if (layout?.overlay != true) null else when (SessionPrefs.steamController(context)) { + SessionPrefs.CONTROLLER_DECK -> STEAM_DECK + SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER + SessionPrefs.CONTROLLER_XBOX360 -> XBOX + SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK + SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE + else -> null + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt index 590ef4fc08..476ac443ac 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt @@ -9,6 +9,7 @@ import com.droiddeck.launcher.session.SessionPrefs enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindings: String? = null) { NONE("none", R.string.second_mode_none), + MENU("menu", R.string.touch_droiddeck_menu), KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad, InputStockLayouts.TRACKPAD), TERMINAL("terminal", R.string.second_mode_terminal), DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls, InputStockLayouts.DECK), @@ -21,19 +22,12 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi fun panel(context: Context): String? = if (this == DECK_CONTROLS) SessionPrefs.deckPanel(context).bindings else bindings companion object { - fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false, desktopSession: Boolean = false): SecondScreenMode { + /** The mode the bottom screen opens in: the one picked last if it is still available, else the DroidDeck menu. */ + fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false): SecondScreenMode = entries.firstOrNull { it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard) && (it != DESKTOP || bottomDesktop) - }?.let { return it } - val picked = entries.any { it != NONE && it.id == remembered } - return when { - desktopSession -> KEYBOARD_TRACKPAD - deckPad -> DECK_CONTROLS - dashboard && !picked -> DASHBOARD - else -> KEYBOARD_TRACKPAD - } - } + } ?: MENU } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/TriggerKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/TriggerKeys.kt new file mode 100644 index 0000000000..785414ed8b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/TriggerKeys.kt @@ -0,0 +1,81 @@ +package com.droiddeck.launcher.input + +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.view.InputDevice +import android.view.KeyEvent +import android.view.MotionEvent + +internal class TriggerKeys(private val dispatch: (KeyEvent) -> Unit) { + private class Pull { + val held = BooleanArray(2) + val sent = BooleanArray(2) + } + + private val handler = Handler(Looper.getMainLooper()) + private val keyed = HashSet() + private val pulls = HashMap() + var synthesizing = false + private set + + /** True when this real trigger key belongs to a pull that already went out as a synthetic press. */ + fun nativeKey(event: KeyEvent): Boolean { + val i = index(event.keyCode) ?: return false + keyed += event.deviceId + val pull = pulls[event.deviceId] ?: return false + if (!pull.sent[i]) return false + if (event.action == KeyEvent.ACTION_UP) pull.sent[i] = false + return true + } + + fun onMotion(event: MotionEvent) { + if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) return + val device = event.deviceId + if (device in keyed) return + val pull = pulls.getOrPut(device) { Pull() } + update(pull, 0, maxOf(event.getAxisValue(MotionEvent.AXIS_LTRIGGER), event.getAxisValue(MotionEvent.AXIS_BRAKE)), event) + update(pull, 1, maxOf(event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_GAS)), event) + } + + fun cancel() { + handler.removeCallbacksAndMessages(null) + pulls.clear() + } + + private fun update(pull: Pull, i: Int, value: Float, event: MotionEvent) { + if (!pull.held[i] && value >= PRESS) { + pull.held[i] = true + pull.sent[i] = false + val device = event.deviceId + val source = event.source + // A pad that also sends trigger keys delivers them close to the axis; waiting lets that key win. + handler.postDelayed({ + if (device !in keyed && pulls[device] === pull) { + pull.sent[i] = true + press(CODES[i], device, source) + } + }, KEY_WAIT_MS) + } else if (pull.held[i] && value <= RELEASE) pull.held[i] = false + } + + private fun press(code: Int, device: Int, source: Int) { + val now = SystemClock.uptimeMillis() + synthesizing = true + try { + dispatch(KeyEvent(now, now, KeyEvent.ACTION_DOWN, code, 0, 0, device, 0, 0, source)) + dispatch(KeyEvent(now, now, KeyEvent.ACTION_UP, code, 0, 0, device, 0, 0, source)) + } finally { + synthesizing = false + } + } + + private fun index(code: Int): Int? = CODES.indexOf(code).takeIf { it >= 0 } + + private companion object { + val CODES = intArrayOf(KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2) + const val PRESS = 0.6f + const val RELEASE = 0.3f + const val KEY_WAIT_MS = 40L + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt index eeab317afe..4362c9308c 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt @@ -12,9 +12,6 @@ object BattleNet { const val APP_ID = 2596113170L - const val FEX_REQUEST = "battlenet-fex.request" - const val FEX_RESULT = "battlenet-fex.result" - const val PROGRAM = "/usr/local/bin/droiddeck-battlenet" class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null, val flavor: String? = null) @@ -59,7 +56,7 @@ object BattleNet { Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"), ) - val STORE: List get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" } + val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" } // Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity. private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs") @@ -162,8 +159,6 @@ object BattleNet { source = com.droiddeck.launcher.stores.Store.BATTLENET.id, ) - fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"] - internal fun title(uid: String): Title? { val id = uid.lowercase() TITLES.firstOrNull { it.uid == id }?.let { return it } @@ -391,54 +386,6 @@ object BattleNet { Log.i(TAG, "removed") } - private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""") - - private const val LISTING_MAX_AGE = 6 * 3600L - - private val NEWEST = Comparator<Pair<List<Long>, Long>> { a, b -> - for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i]) - if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second) - } - - internal fun d2rfix(file: String): Pair<List<Long>, Long>? { - val m = D2RFIX.matchEntire(file) ?: return null - val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null } - return version to (m.groupValues[2].toLongOrNull() ?: return null) - } - - internal fun newestD2rFix(items: List<ComponentsManager.CatalogItem>): ComponentsManager.CatalogItem? = - items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } } - .maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first - - fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items } - - @Synchronized - internal fun ensureFex(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): String { - val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing") - val file = ComponentsManager.safeName(item.file) - if (ComponentsManager.packages(context).none { it.file == file }) { - Log.i(TAG, "downloading ${item.file}") - ComponentsManager.download(context, item) {} - } - val scope = APP_ID.toString() - if (ComponentsManager.gameComponents(context, scope)["fex"] != file) { - ComponentsManager.setGameComponent(context, scope, "fex", file) - Log.i(TAG, "FEX for the Battle.net prefix: $file") - } else if (ComponentsManager.republish(context)) { - Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton") - } - return file - } - - private fun listing(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): List<ComponentsManager.CatalogItem> { - val cached = ComponentsManager.catalog(context, false) - val age = System.currentTimeMillis() / 1000 - cached.fetchedAt - if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items - val fetched = runCatching { refresh(context) } - .onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty() - return if (newestD2rFix(fetched) != null) fetched else cached.items - } - internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt() internal fun videoMemoryOptions(megabytes: Int): String = @@ -464,21 +411,9 @@ object BattleNet { return true } - fun answerFexRequest(context: Context, dir: File) { - val app = context.applicationContext - Thread({ - runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) } - runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) } - val answer = try { - "ok " + ensureFex(app) - } catch (e: Exception) { - Log.w(TAG, "FEX for the Battle.net prefix", e) - "error " + (e.message ?: e.javaClass.simpleName) - } - Log.i(TAG, "FEX request: $answer") - val result = File(dir, FEX_RESULT) - val partial = File(dir, "$FEX_RESULT.tmp") - runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) } - }, "battlenet-fex").start() + fun ensureDefaults(context: Context, program: String?) { + if (program != PROGRAM && !installed(context)) return + runCatching { ensureVideoMemory(context) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) } + runCatching { ensureNoSteam(context) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt index ca408e3b36..0e42e770e3 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt @@ -112,9 +112,16 @@ object BwrapSpawner { return out } + internal fun withKernelPaths(sessionBinds: List<Bind>, canonical: (String) -> String): List<Bind> = + sessionBinds + sessionBinds.filter { it.host == it.guest }.mapNotNull { bind -> + runCatching { canonical(bind.host) }.getOrNull() + ?.takeIf { it != bind.guest && sessionBinds.none { other -> other.guest == it } } + ?.let { Bind(bind.host, it) } + } + internal fun plan(context: Context, request: JSONObject, dir: File): Plan { val rootfs = LinuxRuntime.rootDir(context).path - val session = LinuxRuntime.lastBinds(context).map { Bind.parse(it) } + val session = withKernelPaths(LinuxRuntime.lastBinds(context).map { Bind.parse(it) }) { File(it).canonicalPath } val root = File(dir, "root").apply { mkdirs() } val binds = ArrayList<Bind>() var scratch = 0 @@ -184,7 +191,10 @@ object BwrapSpawner { request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } } withoutRootfsSettings(env, rootfs) val envTool = request.optString("envTool").takeIf { it.startsWith("/") } - if (envTool == null && binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) } + if (envTool == null && binds.any { it.guest == "/dev" }) { + val glIcd = coveringBind(GL_ICD_DIR) != null && File(hostPath(binds, root.path, GL_ICD_DIR)).isDirectory + gpu(rootfs, root, env, glIcd = glIcd)?.forEach { addBind(it) } + } val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) } if (envTool == null && preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) } zypakShims(binds, root, dir).forEach { addBind(it) } @@ -211,6 +221,7 @@ object BwrapSpawner { } private const val GPU_DIR = "/run/droiddeck-gpu" + private const val GL_ICD_DIR = "/usr/lib/aarch64-linux-gnu/GL/vulkan/icd.d" private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib") private val GPU_LIBS = listOf("libdisplay-info.so.3", "libdisplay-info.so.2", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so") @@ -220,9 +231,9 @@ object BwrapSpawner { internal fun gpu( rootfs: String, root: File, env: MutableMap<String, String>, - kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(), + kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(), glIcd: Boolean = false, ): List<Bind>? { - env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) } + env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock, glIcd) } val driver = runtimeLib(rootfs, "libvulkan_freedreno.so") if (driver == null || !kgslAvailable) return null if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null @@ -235,6 +246,7 @@ object BwrapSpawner { val icd = File(root.parentFile, "freedreno_icd.json") icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_freedreno.so\", \"api_version\": \"1.4.0\"}}\n") binds.add(Bind(icd.path, "$GPU_DIR/freedreno_icd.json")) + if (glIcd) binds.add(icdDir(root, icd)) env["VK_DRIVER_FILES"] = "$GPU_DIR/freedreno_icd.json" env["VK_ICD_FILENAMES"] = "$GPU_DIR/freedreno_icd.json" if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) { @@ -245,7 +257,14 @@ object BwrapSpawner { return binds } - private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String): List<Bind>? { + private fun icdDir(root: File, icd: File): Bind { + val dir = File(root.parentFile, "icd.d") + dir.mkdirs() + icd.copyTo(File(dir, icd.name), overwrite = true) + return Bind(dir.path, GL_ICD_DIR) + } + + private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String, glIcd: Boolean): List<Bind>? { val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so") if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null } val binds = ArrayList<Bind>() @@ -258,6 +277,7 @@ object BwrapSpawner { }.getOrNull() ?: run { Log.w(TAG, "gpu: vkbridge session but the runtime's bridge manifest is unreadable"); return null } icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_droidbridge.so\", \"api_version\": \"$api\"}}\n") binds.add(Bind(icd.path, "$GPU_DIR/vkbridge_icd.json")) + if (glIcd) binds.add(icdDir(root, icd)) env["VK_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json" env["VK_ICD_FILENAMES"] = "$GPU_DIR/vkbridge_icd.json" if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) { @@ -416,6 +436,7 @@ object BwrapSpawner { "DDNATV_ROOT" to sandbox, "DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(), "DDNATV_LINK_ROOT" to rootfs.path, + "DDNATV_REAL_EXE" to program.path, "DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" }, "DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context), "LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path }, @@ -537,6 +558,9 @@ object BwrapSpawner { return f } + internal fun prootEnvironment(plan: Plan, startsThroughEnvTool: Boolean): Map<String, String> = + if (startsThroughEnvTool) emptyMap() else plan.env - "LD_PRELOAD" + private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) { val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull() val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null @@ -558,7 +582,7 @@ object BwrapSpawner { ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b -> b.environment().apply { clear() - if (!envTool) putAll(plan.env) + putAll(prootEnvironment(plan, envTool)) put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path) put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path) if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1") diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt new file mode 100644 index 0000000000..af25344b77 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -0,0 +1,303 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import com.droiddeck.launcher.stores.battlenet.BattleNetInstall +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.time.Instant +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean + +object CurseForgeApp { + const val NAME = "CurseForge" + const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml" + internal const val WOW = 1 + const val HELPER = "/usr/local/bin/droiddeck-curseforge" + internal const val AGENT = "/usr/local/bin/droiddeck-agent" + private const val READY_MS = 120_000L + private const val INSTALL_MS = 300_000L + private const val OUT_OF_DATE = 2 + + enum class Start { READY, BUSY, FAILED } + + class Started(val state: Start, val inspector: String? = null) + + class Project(val id: String, val installedModId: String, val folders: List<String>, val update: Boolean) + + internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + + class Failure(message: String, val code: String? = null) : Exception(message) { + val gone get() = code == "DEVTOOLS_UNREACHABLE" + } + + fun find(apps: List<UserApps.App>): UserApps.App? = apps.firstOrNull { it.feed == FEED } + + fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null) + + internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") } + + internal fun helperArgv(command: String, dir: String): List<String> = listOf(HELPER, command, dir) + + internal fun evalArgv(inspector: String, expression: String, timeoutMs: Long): List<String> = + listOf(AGENT, "--cdp-inspector", inspector, (timeoutMs / 1000.0).toString(), expression) + + internal fun lastJson(lines: List<String>): JSONObject? = + lines.asReversed().firstNotNullOfOrNull { line -> runCatching { JSONObject(line.trim()) }.getOrNull() } + + internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) } + + internal fun startState(exitCode: Int): Start = when (exitCode) { + 0 -> Start.READY + 3 -> Start.BUSY + else -> Start.FAILED + } + + internal fun sortOf(sort: WowAddonCatalog.Sort): Pair<Int, Int> = when (sort) { + WowAddonCatalog.Sort.POPULAR -> 8 to 2 + WowAddonCatalog.Sort.UPDATED -> 16 to 2 + WowAddonCatalog.Sort.NAME -> 1 to 1 + WowAddonCatalog.Sort.DOWNLOADS -> 7 to 2 + } + + internal fun searchRequest(guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): JSONObject { + val (column, order) = sortOf(sort) + return JSONObject().put("gameId", WOW).put("searchText", text.trim()).put("page", page + 1) + .put("sortColumn", column).put("sortOrder", order).put("gameInstanceGuid", guid) + } + + internal fun installRequest(guid: String, projectId: String): JSONObject = + JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1) + .put("installLatestFile", true).put("installSource", 4) + + private const val CACHE = "__droiddeckServices" + + private const val SERVICES = """(() => { + const seen = new Set(), out = {}; + const walk = (o, d) => { + if (!o || typeof o !== 'object' || seen.has(o) || d > 4) return; + seen.add(o); + if (typeof o._nameOfService === 'string') { out[o._nameOfService] = o; return; } + let keys; try { keys = Object.keys(o); } catch (e) { return; } + for (const k of keys.slice(0, 4000)) { + let v; try { v = o[k]; } catch (e) { continue; } + if (v instanceof Map) { for (const x of v.values()) walk(x, d + 1); } else walk(v, d + 1); + } + }; + walk(window, 0); + return out; +})()""" + + internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String { + val name = JSONObject.quote(method) + val run = if (args == null) "true" else "($pick)(await s[$name](...$args))" + val key = JSONObject.quote(service) + val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " + + "if (!s || typeof s[$name] !== 'function') return { missing: true }; " + + "return { value: $run }; })()" + return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" + + ".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " + + "if (!w) return JSON.stringify({ missing: true }); " + + "return w.webContents.executeJavaScript(${JSONObject.quote(inner)}).then(v => JSON.stringify(v)); })()" + } + + internal fun unwrap(answer: JSONObject): Any? { + if (!answer.optBoolean("ok")) { + val error = answer.optJSONObject("error") + throw Failure(error?.optString("message")?.takeIf { it.isNotBlank() } ?: answer.toString(), error?.optString("code")?.takeIf { it.isNotBlank() }) + } + val text = answer.opt("value") as? String ?: throw Failure("CurseForge gave no answer") + val reply = JSONObject(text) + if (reply.optBoolean("missing")) throw Failure("CurseForge is not ready") + return reply.opt("value") + } + + internal fun parseSearch(value: Any?): WowAddonCatalog.Page { + val reply = value as? JSONObject ?: throw Failure("CurseForge search failed") + if (reply.has("success") && !reply.optBoolean("success")) throw Failure("CurseForge search failed") + val mods = reply.optJSONArray("mods") ?: JSONArray() + val items = (0 until mods.length()).mapNotNull { mods.optJSONObject(it) }.mapNotNull { mod -> + val id = mod.optLong("id", 0L).takeIf { it > 0 } ?: return@mapNotNull null + val name = mod.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null + val author = mod.optJSONObject("primaryAuthor")?.optString("name")?.takeIf { it.isNotBlank() } + ?: mod.optJSONArray("authors")?.optJSONObject(0)?.optString("name").orEmpty() + val date = mod.optJSONObject("updateVersion")?.optString("fileDate")?.takeIf { it.isNotBlank() } + ?: mod.optString("projectLatestReleaseDate") + WowAddonCatalog.Addon( + id.toString(), name, author, "", mod.optLong("downloads", 0L).coerceAtLeast(0L), + runCatching { Instant.parse(date).toEpochMilli() }.getOrDefault(0L), + mod.optString("thumbnailUrl").takeIf { WowAddonCatalog.isHttps(it) }, + ) + } + val page = reply.optJSONObject("pagination") + val more = page != null && page.optInt("index") + page.optInt("resultCount") < page.optInt("totalCount") + return WowAddonCatalog.Page(items, more) + } + + internal fun samePath(a: String, b: String) = a.trimEnd('/') == b.trimEnd('/') + + internal fun instanceFor(instances: Any?, flavorDir: String, detected: String?): String? { + val list = instances as? JSONArray + val match = list?.let { all -> + (0 until all.length()).mapNotNull { all.optJSONObject(it) } + .firstOrNull { samePath(it.optString("installPath"), flavorDir) }?.optString("guid") + } + if (list != null && list.length() > 0) return match?.takeIf { it.isNotBlank() } + return detected?.takeIf { it.isNotBlank() } + } + + internal fun parseProjects(value: Any?): List<Project> { + val list = value as? JSONArray ?: return emptyList() + return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.mapNotNull { p -> + val id = p.optString("id").takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null + val folders = p.optJSONArray("folders")?.let { f -> (0 until f.length()).mapNotNull { f.optString(it).takeIf(String::isNotBlank) } }.orEmpty() + Project(id, p.optString("installedModId"), folders, p.optInt("status") == OUT_OF_DATE && !p.optBoolean("locked")) + } + } + + internal fun owner(projects: List<Project>, folder: String): Project? = + projects.firstOrNull { project -> project.folders.any { it.equals(folder, ignoreCase = true) } } + + internal fun byFolder(projects: List<Project>): Map<String, Project> = projects.flatMap { project -> project.folders.map { it.lowercase() to project } }.toMap() + + internal fun onDisk(projects: List<Project>, addOns: File): List<Project> { + val names = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }.map { it.name.lowercase() }.toSet() + return projects.filter { project -> WowAddons.present(project.folders) { it.lowercase() in names } } + } + + internal var guest: (Context, List<String>, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine -> + GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true, + cancelled = cancelled, redact = INSPECTOR, onLine = onLine) + } + + private val holds = ConcurrentHashMap<String, AtomicBoolean>() + private val connected = ConcurrentHashMap.newKeySet<String>() + + private fun lines(context: Context, argv: List<String>): List<String> { + val out = ArrayList<String>() + guest(context, argv, null) { out += it } + return out + } + + private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? = + unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer")) + + private sealed class Launch { + class Url(val inspector: String) : Launch() + class Exit(val code: Int) : Launch() + } + + private fun launch(context: Context, dir: String, hold: AtomicBoolean): Launch? { + val first = LinkedBlockingQueue<Launch>() + Thread({ + val code = runCatching { + guest(context, helperArgv("start", dir), hold) { line -> inspectorUrl(line)?.let { first.offer(Launch.Url(it)) } } + }.getOrDefault(-1) + first.offer(Launch.Exit(code)) + }, "curseforge-headless").apply { isDaemon = true; start() } + return first.poll(READY_MS, TimeUnit.MILLISECONDS) + } + + fun start(context: Context, app: UserApps.App, hold: AtomicBoolean): Started { + val dir = dir(app) ?: return Started(Start.FAILED) + if (hold.get()) return Started(Start.FAILED) + holds.put(dir, hold)?.takeIf { it !== hold }?.let { + it.set(true) + runCatching { lines(context, helperArgv("stop", dir)) } + } + val inspector = when (val first = launch(context, dir, hold)) { + is Launch.Url -> first.inspector + is Launch.Exit -> if (startState(first.code) == Start.BUSY) { + holds.remove(dir, hold) + return Started(Start.BUSY) + } else null + null -> null + } + if (inspector == null) { + stop(context, app, null, hold) + return Started(Start.FAILED) + } + val deadline = System.currentTimeMillis() + READY_MS + while (System.currentTimeMillis() < deadline && !hold.get()) { + if (runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }.isSuccess) return Started(Start.READY, inspector) + Thread.sleep(1_000) + } + stop(context, app, inspector, hold) + return Started(Start.FAILED) + } + + fun stop(context: Context, app: UserApps.App, inspector: String?, hold: AtomicBoolean) { + val dir = dir(app) ?: return + if (holds[dir] !== hold) { + hold.set(true) + return + } + if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") } + hold.set(true) + inspector?.let(connected::remove) + if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) } + } + + private fun connect(context: Context, inspector: String) { + if (inspector in connected) return + call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true") + connected += inspector + } + + private fun instances(context: Context, inspector: String): Any? = + call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000, + "r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))") + + fun instance(context: Context, inspector: String, root: String, flavorDir: String): String { + connect(context, inspector) + instanceFor(instances(context, inspector), flavorDir, null)?.let { return it } + val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject + return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir") + } + + fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page = + parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000)) + + fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> { + connect(context, inspector) + if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000) + return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS)) + } + + private const val PROJECTS = "r => (r || []).map(p => ({ id: String(p.id), installedModId: p.installedModId, status: p.status, " + + "locked: !!(p.installedVersion && p.installedVersion.isLocked), " + + "folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))" + + private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): List<Project>? { + val deadline = System.currentTimeMillis() + INSTALL_MS + while (System.currentTimeMillis() < deadline) { + val listed = runCatching { projects(context, inspector, guid) } + val error = listed.exceptionOrNull() + if (error is Failure && error.gone) throw error + listed.getOrNull()?.let { if (done(it)) return it } + Thread.sleep(1_000) + } + return null + } + + fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? { + connect(context, inspector) + if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null + return settle(context, inspector, guid) { list -> list.any { it.id == projectId } } + } + + fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? { + connect(context, inspector) + if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null + return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } } + } + + fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? { + connect(context, inspector) + val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray + if (failed == null || failed.length() > 0) return null + return settle(context, inspector, guid) { list -> list.none { it.id == project.id } } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt new file mode 100644 index 0000000000..451c5c2f82 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt @@ -0,0 +1,102 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.R +import com.droiddeck.launcher.core.Downloader +import com.droiddeck.launcher.session.SessionState +import java.io.File +import org.json.JSONArray +import org.json.JSONObject + +object DeckyStore { + private const val TAG = "DeckyStore" + private const val LISTING = "https://plugins.deckbrew.xyz/plugins" + private const val ARTIFACTS = "https://cdn.tzatzikiweeb.moe/file/steam-deck-homebrew/versions/" + + data class Version(val name: String, val hash: String) + data class Plugin(val name: String, val author: String, val description: String, val tags: List<String>, val downloads: Long, val imageUrl: String, val versions: List<Version>) { + val latest: Version? get() = versions.firstOrNull() + } + data class Installed(val name: String, val folder: String, val author: String, val version: String) + + fun parseListing(body: String): List<Plugin> { + val array = JSONArray(body) + return (0 until array.length()).mapNotNull { i -> + val row = array.optJSONObject(i) ?: return@mapNotNull null + val name = row.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null + val versions = row.optJSONArray("versions")?.let { list -> + (0 until list.length()).mapNotNull { v -> + val version = list.optJSONObject(v) ?: return@mapNotNull null + val hash = version.optString("hash") + if (!hash.matches(Regex("(?i)[0-9a-f]{64}"))) null else Version(version.optString("name"), hash.lowercase()) + } + }.orEmpty() + if (versions.isEmpty()) return@mapNotNull null + val tags = row.optJSONArray("tags")?.let { list -> (0 until list.length()).map { list.optString(it) } }.orEmpty() + val downloads = row.optJSONArray("versions")?.let { list -> (0 until list.length()).sumOf { list.optJSONObject(it)?.optLong("downloads") ?: 0L } } ?: 0L + val image = row.optString("image_url").takeIf { it.startsWith("https://") }.orEmpty() + Plugin(name, row.optString("author"), row.optString("description"), tags, downloads, image, versions) + } + } + + fun fetch(): List<Plugin>? { + val body = Downloader.downloadString(LISTING) ?: return null + return runCatching { parseListing(body) }.onFailure { Log.w(TAG, "store listing", it) }.getOrNull() + } + + fun pluginsDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins") + + fun installed(context: Context): List<Installed> = + pluginsDir(context).listFiles().orEmpty() + .filter { it.isDirectory && !it.name.startsWith(".droiddeck-") } + .mapNotNull { folder -> + runCatching { + val meta = JSONObject(File(folder, "plugin.json").readText()) + val version = runCatching { JSONObject(File(folder, "package.json").readText()).optString("version") }.getOrDefault("") + Installed(meta.getString("name"), folder.name, meta.optString("author"), version) + }.getOrNull() + } + .sortedBy { it.name.lowercase() } + + fun updateAvailable(installed: Installed, plugin: Plugin?): Boolean { + val latest = plugin?.latest?.name ?: return false + return installed.version.isNotEmpty() && latest != installed.version + } + + fun install(context: Context, plugin: Plugin, version: Version, progress: (String, Int) -> Unit): String? { + if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin) + if (DeckyManager.installed(context) == null) return context.getString(R.string.deckymgr_loader_required) + val cache = File(context.cacheDir, "decky-store").apply { mkdirs() } + val zip = File(cache, "${version.hash}.zip") + try { + val label = context.getString(R.string.decky_store_downloading, plugin.name) + progress(label, -1) + val ok = Downloader.downloadFile("$ARTIFACTS${version.hash}.zip", zip, true, version.hash) { fraction -> + progress(label, if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100)) + } + if (!ok) return context.getString(R.string.decky_store_download_failed, plugin.name) + return DeckyManager.installPluginZip(context, zip, progress) + } finally { + zip.delete() + } + } + + fun remove(context: Context, plugin: Installed): String? { + if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin) + val plugins = pluginsDir(context) + val folder = File(plugins, plugin.folder) + if (folder.parentFile?.canonicalFile != plugins.canonicalFile) return context.getString(R.string.decky_store_remove_failed) + if (!folder.deleteRecursively()) return context.getString(R.string.decky_store_remove_failed) + val settings = File(plugins.parentFile, "settings/loader.json") + runCatching { + val json = JSONObject(settings.readText()) + for (key in listOf("pluginOrder", "frozenPlugins", "hiddenPlugins", "disabled_plugins")) { + val values = json.optJSONArray(key) ?: continue + json.put(key, JSONArray((0 until values.length()).map { values.get(it) }.filter { it != plugin.name })) + } + settings.writeText(json.toString(4)) + } + return null + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt index 83bfa6748a..3cd0c01e0e 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt @@ -32,6 +32,9 @@ object DesktopLanguage { internal fun baseUrl(desktopUrl: String) = desktopUrl.substringBeforeLast('/') + "/" + /** The index carries every pack's sha256, so it never goes through a download mirror. */ + internal fun fetchIndex(base: String): Map<String, Pack>? = Downloader.downloadDirect(base + INDEX)?.let(::parseIndex) + private fun marker(root: File, tag: String, name: String) = File(root, ".droiddeck-i18n-$tag-$name") /** Installs the desktop's translations for [locale]; false when a download failed and is worth retrying. */ @@ -44,7 +47,7 @@ object DesktopLanguage { val pending = candidates(locale).filterNot { marker(root, tag, it).isFile } if (pending.isEmpty()) return true val base = baseUrl(BuildConfig.DESKTOP_KDE_URL) - val index = parseIndex(Downloader.downloadString(base + INDEX) ?: return false) + val index = fetchIndex(base) ?: return false var complete = true for (name in pending) { val pack = index[name] diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt index 0f5c48ce21..e589c5c8b5 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt @@ -17,6 +17,9 @@ import android.provider.Settings import android.util.Log import com.droiddeck.launcher.core.SessionPart import com.droiddeck.launcher.R +import com.droiddeck.launcher.session.SessionHdr +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionState import java.io.File import java.nio.file.Files import java.nio.file.StandardCopyOption @@ -74,8 +77,10 @@ class DeviceControlsComponent(context: Context, root: File, private val activity val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128) write("backlight/droiddeck/brightness", "$value\n") write("backlight/droiddeck/actual_brightness", "$value\n") - val state = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0) - .put("brightnessWritable", Settings.System.canWrite(context)).toString() + val controls = JSONObject().put("brightness", (value.coerceIn(1, 255) - 1) / 254.0) + .put("brightnessWritable", Settings.System.canWrite(context)) + if (SessionState.hdrCapable) controls.put("hdr", SessionState.hdr) + val state = controls.toString() if (force || state != previous) { write("state.json", JSONObject(state).put("revision", ++revision).toString()) previous = state @@ -132,6 +137,9 @@ class DeviceControlsComponent(context: Context, root: File, private val activity audio.setStreamVolume(AudioManager.STREAM_MUSIC, it.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0) } + "hdr.request" -> if (text == "0" || text == "1") { + SessionHdr.set(context, SessionPrefs.prefMode(SessionState.mode), text == "1") + } "mute.request" -> if (text == "0" || text == "1") { audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, if (text == "1") AudioManager.ADJUST_MUTE else AudioManager.ADJUST_UNMUTE, 0) @@ -196,7 +204,7 @@ class DeviceControlsComponent(context: Context, root: File, private val activity private const val STREAM_MUTE_CHANGED_ACTION = "android.media.STREAM_MUTE_CHANGED_ACTION" private const val PERMISSION_CHANNEL = "brightness_permission" private const val PERMISSION_NOTIFICATION = 0x4442 - private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request") + private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request", "hdr.request") @JvmStatic fun directory(root: File) = File(root, "etc/droiddeck-device-controls") @JvmStatic fun prepareBacklight(context: Context, root: File): File { val base = File(directory(root), "backlight") diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt index 95ea5b13c9..2c5fbad51e 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt @@ -14,20 +14,22 @@ import java.util.concurrent.atomic.AtomicBoolean object GuestCommand { fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null, linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null, - onLine: (String) -> Unit): Int { + redact: Regex? = null, onLine: (String) -> Unit): Int { val log = logName?.let { try { File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter() } catch (e: Exception) { null } } - log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}") + log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}") try { - return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) } + return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) } } finally { log?.close() } } + internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "<redacted>") ?: text + private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?, fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int { val root = LinuxRuntime.rootDir(context) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt index 40cdd0e471..b76172edb1 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponent.kt @@ -275,12 +275,15 @@ class LinuxNetworkLinkComponent( * crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes. */ private fun replace(file: File, text: String) { - val staged = File(file.path + ".staged") - java.io.FileOutputStream(staged).use { out -> - out.write(text.toByteArray()) - out.fd.sync() + synchronized(WRITES) { + if (runCatching { file.isFile && file.readText() == text }.getOrDefault(false)) return + val staged = File(file.path + ".staged") + java.io.FileOutputStream(staged).use { out -> + out.write(text.toByteArray()) + out.fd.sync() + } + if (!staged.renameTo(file)) throw IOException("Could not replace $file") } - if (!staged.renameTo(file)) throw IOException("Could not replace $file") } private fun writeResolver(properties: LinkProperties?) { @@ -333,6 +336,8 @@ class LinuxNetworkLinkComponent( seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) } companion object { + private val WRITES = Any() + internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> = listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family -> properties?.routes.orEmpty() diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt index 3cd7d4370f..61f91598d5 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt @@ -73,10 +73,10 @@ object NativeGuest { fun libraryPath(root: File): String = LIB_DIRS.joinToString(":") { File(root, it).path } /** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */ - fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf( + fun environment(root: File, program: String, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf( "DDNATV_ROOT" to root.path, "DDNATV_EXEC" to execLoader.orEmpty(), - "LD_LIBRARY_PATH" to libraryPath(root), + "DDNATV_REAL_EXE" to hostProgram(root, program).path, "LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"), ).filterValues { it.isNotEmpty() } @@ -84,23 +84,25 @@ object NativeGuest { * The host command line for the guest program at [program] (an absolute guest path to a real * file, not a symlink). */ - fun command(root: File, program: String, args: List<String>): List<String> { + fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> { val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" } - val host = File(root, program.removePrefix("/")) - val launch = listOf(loader.path, "--argv0", host.name, host.path) + args + val host = hostProgram(root, program) + val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch) } + private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/")) + /** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */ - fun sessionEnvironment(root: File, binds: List<String>, hostname: String? = null): Map<String, String> { + fun sessionEnvironment(root: File, binds: List<String>, program: String, hostname: String? = null): Map<String, String> { val preload = preloadList(root) return linkedMapOf( "DDNATV_ROOT" to root.path, "DDNATV_EXEC" to execLoader.orEmpty(), + "DDNATV_REAL_EXE" to hostProgram(root, program).path, "DDNATV_HOSTNAME" to hostname.orEmpty(), "DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" }, "DDNATV_PRELOAD" to preload.joinToString(":"), - "LD_LIBRARY_PATH" to libraryPath(root), "LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"), ).filterValues { it.isNotEmpty() } } @@ -116,7 +118,7 @@ object NativeGuest { .also { builder -> builder.environment().apply { remove("LD_AUDIT") - putAll(sessionEnvironment(root, binds, SessionPrefs.guestHostname(context))) + putAll(sessionEnvironment(root, binds, guest.first(), SessionPrefs.guestHostname(context))) } } @@ -273,12 +275,14 @@ object NativeGuest { fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder { val program = argv.first() - val cmd = command(root, program, argv.drop(1)) + val callerDirs = env["LD_LIBRARY_PATH"]?.takeIf { it.isNotEmpty() }?.split(':').orEmpty() + val rootDirs = libraryPath(root).split(':').filterNot { it in callerDirs } + val cmd = command(root, program, argv.drop(1), (callerDirs + rootDirs).joinToString(":")) val builder = ProcessBuilder(cmd).redirectErrorStream(false) builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root) builder.environment().apply { clear() - putAll(environment(root, preload)) + putAll(environment(root, program, preload)) putAll(env) } return builder diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt b/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt index cd16d03b42..efc460ee04 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/UserApps.kt @@ -36,6 +36,7 @@ object UserApps { private const val GITHUB_TAG = "github-tag" private const val GITHUB_PUBLISHED = "github-published" private const val GITHUB_ASSET = "github-asset" + private const val FEED = "update-feed" enum class Kind { SCRIPT, APPIMAGE, FLATPAK } @@ -43,10 +44,15 @@ object UserApps { val key: String, val kind: Kind, val name: String, val icon: Any?, val detail: String?, val program: String, val args: List<String>, val copied: Boolean = false, val repo: String? = null, val version: String? = null, - val fex: String = LinuxFex.AUTO, val arch: String? = null, - ) + val fex: String = LinuxFex.AUTO, val arch: String? = null, val feed: String? = null, + ) { + val updatable get() = repo != null || feed != null + } - class Release(val tag: String, val published: String, val asset: String, val url: String, val sha256: String? = null) + class Release( + val tag: String, val published: String, val asset: String, val url: String, + val sha256: String? = null, val sha512: String? = null, + ) sealed class UpdateCheck { class Current(val tag: String) : UpdateCheck() @@ -58,6 +64,7 @@ object UserApps { class Script(val file: File) : Source() class AppImage(val file: File) : Source() class GitHub(val repo: String, val asset: String? = null) : Source() + class Feed(val url: String) : Source() class Flatpak(val id: String) : Source() class FlatpakBundle(val file: File) : Source() } @@ -91,6 +98,7 @@ object UserApps { "appimage:${item.id}", Kind.APPIMAGE, item.name, item.icon, item.comment, AppImageManager.LAUNCHER, listOf(item.guestDir), repo = FileUtils.readString(File(dir, GITHUB_REPO))?.trim(), version = FileUtils.readString(File(dir, GITHUB_TAG))?.trim(), fex = LinuxFex.mode(dir), arch = FileUtils.readString(File(dir, "arch"))?.trim()?.takeIf { it.isNotEmpty() }, + feed = FileUtils.readString(File(dir, FEED))?.trim()?.takeIf { it.isNotEmpty() }, ) } val flatpaks = FlatpakManager.installedApps(context).map { app -> @@ -115,6 +123,7 @@ object UserApps { is Source.Script -> addScript(context, s.file, name, icon, request.meta, onProgress) is Source.AppImage -> AppImageManager.import(context, s.file, name, icon, request.meta) { onProgress(it, -1) } is Source.GitHub -> addFromGitHub(context, s.repo, s.asset, name, icon, onProgress) + is Source.Feed -> addFromFeed(context, s.url, name, icon, onProgress) is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress) is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress) } @@ -346,11 +355,15 @@ object UserApps { } private fun withDownload(context: Context, release: Release, onProgress: (String, Int) -> Unit, use: (File) -> String?): String? { - val download = File(context.cacheDir, "github-${release.asset}") + val download = File(File(context.cacheDir, "user-apps").apply { mkdirs() }, release.asset) try { val label = context.getString(R.string.user_apps_downloading, release.asset) val ok = Downloader.downloadFile(release.url, download, false, release.sha256) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) } - return if (ok) use(download) else context.getString(R.string.user_apps_download_failed) + if (!ok) return context.getString(R.string.user_apps_download_failed) + if (release.sha512 != null && !Hashes.sha512(download).equals(release.sha512, ignoreCase = true)) { + return context.getString(R.string.selfinst_checksum_mismatch) + } + return use(download) } finally { download.delete() } @@ -392,20 +405,57 @@ object UserApps { return urls + listOfNotNull(avatar) } + internal fun parseFeed(feed: String, body: String): Release? { + val top = body.lineSequence().filter { it.isNotEmpty() && !it[0].isWhitespace() && ':' in it } + .associate { it.substringBefore(':').trim() to it.substringAfter(':').trim().trim('\'', '"') } + val version = top["version"]?.takeIf { it.isNotEmpty() } ?: return null + val path = top["path"]?.takeIf { it.endsWith(".AppImage", ignoreCase = true) && '/' !in it && ".." !in it } ?: return null + val sha512 = top["sha512"]?.let { runCatching { java.util.Base64.getDecoder().decode(it) }.getOrNull() } + ?.takeIf { it.size == 64 }?.joinToString("") { "%02x".format(it) } ?: return null + val base = feed.substringBeforeLast('/', "").takeIf { it.startsWith("https://") } ?: return null + return Release(version, top["releaseDate"].orEmpty(), path, "$base/$path", sha512 = sha512) + } + + private fun feedRelease(context: Context, feed: String): Release? = + Downloader.downloadString(feed)?.let { parseFeed(feed, it) } + + private fun feedMeta(feed: String, release: Release) = + mapOf(FEED to feed, GITHUB_TAG to release.tag, GITHUB_PUBLISHED to release.published, GITHUB_ASSET to release.asset) + + private fun addFromFeed(context: Context, feed: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? { + onProgress(context.getString(R.string.user_apps_github_checking, name ?: feed), -1) + val release = feedRelease(context, feed) ?: return context.getString(R.string.user_apps_update_failed) + return withDownload(context, release, onProgress) { file -> + AppImageManager.import(context, file, name ?: release.asset.substringBefore('-'), icon, feedMeta(feed, release)) { onProgress(it, -1) } + } + } + + internal fun isNewer(release: Release, published: String, installed: String?): Boolean = + if (published.isNotEmpty() && release.published.isNotEmpty()) { + val feed = runCatching { java.time.Instant.parse(release.published) }.getOrNull() + val have = runCatching { java.time.Instant.parse(published) }.getOrNull() + if (feed != null && have != null) feed > have else release.published > published + } else release.tag != installed + fun checkUpdate(context: Context, app: App): UpdateCheck { + app.feed?.let { feed -> + val release = feedRelease(context, feed) ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed)) + val published = FileUtils.readString(File(AppImageManager.dir(context, app.key.substringAfter(':')), GITHUB_PUBLISHED))?.trim().orEmpty() + return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag) + } val repo = app.repo ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed)) val dir = AppImageManager.dir(context, app.key.substringAfter(':')) val (release, problem) = latestRelease(context, repo, FileUtils.readString(File(dir, GITHUB_ASSET))?.trim()?.takeIf { it.isNotEmpty() }) if (release == null) return UpdateCheck.Failed(problem ?: context.getString(R.string.user_apps_update_failed)) val published = FileUtils.readString(File(dir, GITHUB_PUBLISHED))?.trim().orEmpty() - val newer = if (published.isNotEmpty() && release.published.isNotEmpty()) release.published > published else release.tag != app.version - return if (newer) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag) + return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag) } fun update(context: Context, app: App, release: Release, onProgress: (String, Int) -> Unit): String? { - val repo = app.repo ?: return context.getString(R.string.user_apps_update_failed) + val meta = app.feed?.let { feedMeta(it, release) } + ?: app.repo?.let { githubMeta(it, release) } ?: return context.getString(R.string.user_apps_update_failed) return withDownload(context, release, onProgress) { file -> - AppImageManager.replace(context, app.key.substringAfter(':'), file, githubMeta(repo, release)) { onProgress(it, -1) } + AppImageManager.replace(context, app.key.substringAfter(':'), file, meta) { onProgress(it, -1) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt index 63c1436f14..5a0cf0bb98 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt @@ -29,6 +29,7 @@ object WowAddonCatalog { val downloads: Long, val updated: Long, val thumb: String?, + val folders: List<String> = emptyList(), ) class Page(val items: List<Addon>, val more: Boolean) @@ -38,7 +39,6 @@ object WowAddonCatalog { internal class Cat(val id: String, val name: String, val parents: List<String>) private const val WOWI = "https://api.mmoui.com/v3/game/WOW/" - private const val CURSEFORGE = "https://www.curseforge.com/wow/search?class=addons" private const val WOWI_FILES = "wowi-filelist.json" internal const val FRESH_MS = 6L * 60 * 60 * 1000 @@ -94,8 +94,7 @@ object WowAddonCatalog { Client(folder, version?.let(::flavorOf) ?: folderFamily(folder)) fun client(target: WowAddons.Target): Client { - val dir = target.addOns.parentFile?.parentFile - return client(target.flavor, dir?.let(::clientVersion)) + return client(target.flavor, WowAddons.flavorDir(target)?.let(::clientVersion)) } internal fun flavorMatches(flavors: Set<String>?, family: String?): Boolean = @@ -116,9 +115,11 @@ object WowAddonCatalog { } val thumbs = o.optJSONArray("UIIMG_Thumbs") val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null + val dirs = o.optJSONArray("UIDir") + val folders = if (dirs == null) emptyList() else (0 until dirs.length()).map { dirs.optString(it).trim() }.filter { it.isNotEmpty() } val addon = Addon( id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"), - o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, + o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, folders, ) out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L)) } @@ -209,10 +210,12 @@ object WowAddonCatalog { fun categories(context: Context): List<Category> = wowiCategories(context).map { Category(it.id, it.name) } - internal fun parseWowiDetails(json: String): Pair<String, String?>? { + internal class Details(val url: String, val md5: String?, val version: String?) + + internal fun parseWowiDetails(json: String): Details? { val o = JSONArray(json).optJSONObject(0) ?: return null val url = o.optString("UIDownload").ifEmpty { return null } - return url to o.optString("UIMD5").ifEmpty { null } + return Details(url, o.optString("UIMD5").ifEmpty { null }, o.optString("UIVersion").trim().ifEmpty { null }) } internal fun isHttps(url: String) = url.startsWith("https://", ignoreCase = true) @@ -220,10 +223,11 @@ object WowAddonCatalog { internal fun md5Matches(file: File, expected: String?): Boolean = expected.isNullOrBlank() || Hashes.md5(file).equals(expected.trim(), ignoreCase = true) - fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): File { + fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): String? { val body = StoreNet.get(WOWI + "filedetails/${URLEncoder.encode(addon.id, "UTF-8")}.json", timeoutMs = 30_000) ?: throw unreachable(context) - val (url, md5) = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file)) + val details = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file)) + val url = details.url if (!isHttps(url)) throw IOException(context.getString(R.string.addons_no_file)) dest.parentFile?.mkdirs() dest.delete() @@ -232,14 +236,56 @@ object WowAddonCatalog { dest.delete() throw unreachable(context) } - if (!md5Matches(dest, md5)) { + if (!md5Matches(dest, details.md5)) { dest.delete() throw IOException(context.getString(R.string.selfinst_checksum_mismatch)) } progress(100) - return dest + return details.version } - internal fun curseForgeUrl(text: String): String = - text.trim().let { if (it.isEmpty()) CURSEFORGE else CURSEFORGE + "&search=" + URLEncoder.encode(it, "UTF-8") } + private fun normVersion(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase() + + internal fun sameVersion(a: String, b: String): Boolean = normVersion(a) == normVersion(b) + + private val NUMERIC_VERSION = Regex("""^(\d+(?:\.\d+)*)(.*)$""") + + private fun numericVersion(v: String): Pair<List<Long>, String>? { + val match = NUMERIC_VERSION.matchEntire(normVersion(v)) ?: return null + val parts = match.groupValues[1].split('.').map { it.toLongOrNull() ?: return null } + return parts to match.groupValues[2] + } + + internal fun newer(have: String, latest: String): Boolean? { + val (a, aRest) = numericVersion(have) ?: return null + val (b, bRest) = numericVersion(latest) ?: return null + for (i in 0 until maxOf(a.size, b.size)) { + val x = a.getOrElse(i) { 0L } + val y = b.getOrElse(i) { 0L } + if (x != y) return y > x + } + return if (aRest == bRest) false else null + } + + internal fun offersUpdate(have: String?, latest: String, sameSource: Boolean): Boolean { + if (have.isNullOrBlank() || latest.isBlank() || sameVersion(have, latest)) return false + return newer(have, latest) ?: sameSource + } + + internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> { + val byId = entries.associateBy { it.addon.id } + val seen = HashSet<String>() + return installed.mapNotNull { item -> + val id = item.wowiId ?: return@mapNotNull null + val version = item.version ?: return@mapNotNull null + val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null + if (!offersUpdate(version, latest.summary, sameSource = true) || !seen.add(id)) null else item.name to latest + }.toMap() + } + + fun updates(context: Context, installed: List<WowAddons.Installed>, target: WowAddons.Target): Map<String, Addon> { + if (installed.none { it.wowiId != null }) return emptyMap() + val family = client(target).family + return runCatching { findUpdates(wowiEntries(context).filter { flavorMatches(it.flavors, family) }, installed) }.getOrDefault(emptyMap()) + } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt index 60cfbf37c3..35536449ac 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt @@ -2,15 +2,25 @@ package com.droiddeck.launcher.runtime import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf +import android.content.Context import androidx.compose.runtime.setValue +import com.droiddeck.launcher.R import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreArchiveUnpacker import com.droiddeck.launcher.stores.StoreInstalls +import com.droiddeck.launcher.stores.itch.ItchArchives import org.apache.commons.compress.archivers.zip.ZipFile import java.io.File import java.io.IOException +import java.io.InputStream +import java.nio.file.FileVisitResult import java.nio.file.Files import java.nio.file.LinkOption +import java.nio.file.Path +import java.nio.file.SimpleFileVisitor +import java.nio.file.attribute.BasicFileAttributes +import java.util.concurrent.atomic.AtomicBoolean object WowAddons { var imports by mutableIntStateOf(0) @@ -18,10 +28,28 @@ object WowAddons { class TooLarge : IOException() + fun changed() { + imports++ + } + + fun flavorDir(target: Target): File? = target.addOns.parentFile?.parentFile + + fun root(target: Target): File? = flavorDir(target)?.parentFile + class Target(val flavor: String, val addOns: File) class Addon(val name: String, val root: String) + class Installed(val name: String, val version: String?, val wowiId: String?, val curseId: String? = null) + + class Origin(val id: String, val version: String) + + private const val ORIGINS = ".droiddeck-sources" + private const val TOC_VERSION = "Version" + private const val TOC_WOWI_ID = "X-WoWI-ID" + private const val TOC_CURSE_ID = "X-Curse-Project-ID" + private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID, TOC_CURSE_ID) + internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024 private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE) @@ -45,53 +73,168 @@ object WowAddons { target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") } .map { it.name }.sortedBy { it.lowercase() } + fun present(folders: List<String>, exists: (String) -> Boolean): Boolean = folders.isNotEmpty() && folders.all(exists) + + fun folder(addOns: File, name: String): File? { + val dirs = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") } + return dirs.firstOrNull { it.name == name } ?: dirs.firstOrNull { it.name.equals(name, ignoreCase = true) } + } + + fun details(target: Target): List<Installed> { + val origins = origins(target) + return installed(target).map { name -> + val toc = toc(File(target.addOns, name)) + val origin = origins[name] + Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID], toc[TOC_CURSE_ID]) + } + } + + internal fun tocFields(lines: Sequence<String>, keys: Set<String> = TOC_KEYS): Map<String, String> { + val out = LinkedHashMap<String, String>() + for (raw in lines) { + val line = raw.trim().removePrefix("\uFEFF") + if (!line.startsWith("##") || ':' !in line) continue + val key = line.removePrefix("##").substringBefore(':').trim() + if (key !in keys || key in out) continue + val value = line.substringAfter(':').trim() + if (value.isNotEmpty() && '@' !in value) out[key] = value + if (out.size == keys.size) break + } + return out + } + + private fun toc(folder: File): Map<String, String> { + val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }.sortedWith( + compareBy<File>( + { !it.name.dropLast(4).equals(folder.name, ignoreCase = true) }, + { !it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) }, + { it.name.length }, + { it.name }, + ), + ) + val out = LinkedHashMap<String, String>() + for (file in tocs) { + if (out.size == TOC_KEYS.size) break + val missing = TOC_KEYS - out.keys + runCatching { file.bufferedReader().useLines { tocFields(it, missing) } }.getOrNull()?.let(out::putAll) + } + return out + } + + internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line -> + val parts = line.split('\t') + if (parts.size != 3 || parts.any { it.isBlank() }) null else parts[0] to Origin(parts[1], parts[2]) + }.toMap() + + internal fun formatOrigins(origins: Map<String, Origin>): String = + origins.entries.sortedBy { it.key.lowercase() }.joinToString("") { (name, o) -> "$name\t${o.id}\t${o.version.replace(Regex("\\s+"), " ")}\n" } + + private fun originsFile(target: Target) = File(target.addOns, ORIGINS) + + private fun origins(target: Target): Map<String, Origin> = + runCatching { parseOrigins(originsFile(target).readText()) }.getOrDefault(emptyMap()) + + private val originsLock = Any() + + private fun keepOrigins(target: Target, names: List<String>, origin: Origin?) = synchronized(originsLock) { + val current = origins(target) + val next = current - names.toSet() + (origin?.let { o -> names.associateWith { o } } ?: emptyMap()) + if (next != current) { + val file = originsFile(target) + if (next.isEmpty()) file.delete() else { + val temp = File(target.addOns, "$ORIGINS.tmp") + temp.writeText(formatOrigins(next)) + if (!temp.renameTo(file)) { + temp.delete() + throw IOException("Cannot save $ORIGINS") + } + } + } + } + fun delete(target: Target, name: String) { val folder = target.addOns.listFiles()?.firstOrNull { it.name == name && !it.name.startsWith(".") } ?: throw IOException("Cannot find $name") StoreInstalls.deleteTree(folder) if (Files.exists(folder.toPath(), LinkOption.NOFOLLOW_LINKS)) throw IOException("Cannot delete $name") + runCatching { keepOrigins(target, listOf(name), null) } imports++ } - fun import(zipFile: File, target: Target): List<String> { + fun import(archive: File, target: Target, origin: Origin? = null, context: Context? = null): List<String> { + if (context == null || ItchArchives.kind(archive, archive.name) == "zip") return importZip(archive, target, origin) + val work = File(File(context.cacheDir, "wowaddons"), "unpack-${System.nanoTime()}") + try { + if (!work.mkdirs()) throw IOException("Cannot create ${work.path}") + val unpacker = StoreArchiveUnpacker(context, AtomicBoolean(), "Addons", R.string.stores_itch_archive, R.string.stores_itch_extract_failed, "addon-unpack") + unpacker.work = work + unpacker.limit = MAX_EXPANDED_BYTES + try { + unpacker.unpack(archive, archive.name, { _, _ -> }, {}) + } catch (_: StoreArchiveUnpacker.TooLarge) { + throw TooLarge() + } + return importFolder(work, target, origin) + } finally { + StoreInstalls.deleteTree(work) + } + } + + private class Entry(val path: String, val open: () -> InputStream) + + private fun importZip(zipFile: File, target: Target, origin: Origin?): List<String> = ZipFile.builder().setFile(zipFile).get().use { zip -> val all = zip.entries.toList() if (all.any { it.isUnixSymlink }) return emptyList() - val entries = all.filter { clean(it.name) != null } - val addons = addons(entries.filter { !it.isDirectory }.mapNotNull { clean(it.name) }) - if (addons.isEmpty()) return emptyList() - val addOns = target.addOns - if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}") - val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}") - try { - val fresh = File(stage, "new") - val buffer = ByteArray(64 * 1024) - var written = 0L - for (entry in entries) { - if (entry.isDirectory) continue - val path = clean(entry.name) ?: continue - val addon = addons.firstOrNull { path.startsWith(it.root) } ?: continue - val out = inside(fresh, addon.name + "/" + path.removePrefix(addon.root)) ?: continue - out.parentFile?.mkdirs() - zip.getInputStream(entry).use { input -> - out.outputStream().use { output -> - while (true) { - val read = input.read(buffer) - if (read < 0) break - written += read - if (written > MAX_EXPANDED_BYTES) throw TooLarge() - output.write(buffer, 0, read) - } + importEntries(all.filter { !it.isDirectory }.mapNotNull { entry -> clean(entry.name)?.let { Entry(it) { zip.getInputStream(entry) } } }, target, origin) + } + + internal fun importFolder(folder: File, target: Target, origin: Origin?): List<String> { + val entries = ArrayList<Entry>() + var links = false + Files.walkFileTree(folder.toPath(), object : SimpleFileVisitor<Path>() { + override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { + if (!attrs.isRegularFile) links = true + else clean(folder.toPath().relativize(file).joinToString("/"))?.let { entries.add(Entry(it) { Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS) }) } + return if (links) FileVisitResult.TERMINATE else FileVisitResult.CONTINUE + } + }) + return if (links) emptyList() else importEntries(entries, target, origin) + } + + private fun importEntries(entries: List<Entry>, target: Target, origin: Origin?): List<String> { + val addons = addons(entries.map { it.path }) + if (addons.isEmpty()) return emptyList() + val addOns = target.addOns + if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}") + val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}") + try { + val fresh = File(stage, "new") + val buffer = ByteArray(64 * 1024) + var written = 0L + for (entry in entries) { + val addon = addons.firstOrNull { entry.path.startsWith(it.root) } ?: continue + val out = inside(fresh, addon.name + "/" + entry.path.removePrefix(addon.root)) ?: continue + out.parentFile?.mkdirs() + entry.open().use { input -> + out.outputStream().use { output -> + while (true) { + val read = input.read(buffer) + if (read < 0) break + written += read + if (written > MAX_EXPANDED_BYTES) throw TooLarge() + output.write(buffer, 0, read) } } } - swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() }) - } finally { - StoreInstalls.deleteTree(stage) } - imports++ - return addons.map { it.name } + swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() }) + } finally { + StoreInstalls.deleteTree(stage) } + runCatching { keepOrigins(target, addons.map { it.name }, origin) } + imports++ + return addons.map { it.name } } internal fun addons(files: List<String>): List<Addon> { diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt index 5300b24720..b25ed487a2 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt @@ -328,7 +328,7 @@ object BottomDesktop { LinuxRuntime.commandWithBinds(context, current.root, binds, guest) } val environment = if (current.nativeUserland) { - com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, SessionPrefs.guestHostname(context)) + com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context)) .map { (k, v) -> "$k=$v" }.toTypedArray() } else current.hostEnvironment val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") } diff --git a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt index 749532cddf..fdc8e2bf51 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt @@ -238,6 +238,20 @@ object ComponentsManager { saveState(context, state) } + private val UNPINNED_FEX = Regex("""(?i)FEXCore-\d+(?:\.\d+)*-d2rfix\d+-linux\.wcp""") + + fun migrateBattleNetFex(context: Context) = synchronized(lock) { + val marker = File(dataDir(context), ".battlenet-fex-unpinned") + if (marker.isFile) return@synchronized + migratePlugin(context) + val scope = com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString() + if (gameComponents(context, scope)["fex"]?.let(UNPINNED_FEX::matches) == true) { + setGameComponent(context, scope, "fex", null) + Log.i(TAG, "Battle.net follows the selected FEX again") + } + marker.writeText("1\n") + } + private fun migratePlugin(context: Context) { val marker = File(dataDir(context), ".plugin-imported") if (marker.isFile) return @@ -487,6 +501,7 @@ object ComponentsManager { fun snapshotAll(context: Context) = synchronized(lock) { migratePlugin(context) + runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) } val state = loadState(context) for (p in protons(context)) for (comp in COMPONENTS) { runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) } @@ -497,6 +512,7 @@ object ComponentsManager { fun snapshot(context: Context): Snapshot = synchronized(lock) { migratePlugin(context) + runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) } val state = loadState(context) val reapplied = HashMap<String, Long>() runCatching { diff --git a/app/src/main/java/com/droiddeck/launcher/session/ContentCadence.kt b/app/src/main/java/com/droiddeck/launcher/session/ContentCadence.kt new file mode 100644 index 0000000000..a0a5fae498 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/ContentCadence.kt @@ -0,0 +1,65 @@ +package com.droiddeck.launcher.session + +class ContentCadence { + var rate = 0 + private set + private var candidate = 0 + private var streak = 0 + private var misses = 0 + private val reengage = HashMap<Int, Int>() + + fun note(fps: Int, panelRates: IntArray): Boolean { + val snapped = snap(fps, panelRates) + if (rate != 0) { + if (snapped == rate) { + misses = 0 + return false + } + if (++misses < RELEASE_SAMPLES) return false + reengage[rate] = minOf((reengage[rate] ?: ENGAGE_SAMPLES) * 2, MAX_ENGAGE_SAMPLES) + rate = 0 + misses = 0 + candidate = snapped + streak = if (snapped > 0) 1 else 0 + return true + } + if (snapped == 0 || snapped != candidate) { + candidate = snapped + streak = if (snapped > 0) 1 else 0 + return false + } + if (++streak < (reengage[snapped] ?: ENGAGE_SAMPLES)) return false + rate = snapped + misses = 0 + return true + } + + fun reset(): Boolean { + val engaged = rate != 0 + rate = 0 + candidate = 0 + streak = 0 + misses = 0 + return engaged + } + + companion object { + const val ENGAGE_SAMPLES = 3 + const val RELEASE_SAMPLES = 3 + const val MAX_ENGAGE_SAMPLES = 30 + private const val MIN_FPS = 20 + private const val MAX_DIVISOR = 6 + + fun snap(fps: Int, panelRates: IntArray): Int { + if (fps < MIN_FPS) return 0 + var best = 0 + for (hz in panelRates) for (divisor in 1..MAX_DIVISOR) { + if (hz % divisor != 0) continue + val step = hz / divisor + val miss = Math.abs(step - fps) + if (miss <= 1 && (best == 0 || miss < Math.abs(best - fps) || (miss == Math.abs(best - fps) && step > best))) best = step + } + return best + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt index b437f3ae4e..e1b38fe9ec 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt @@ -935,7 +935,7 @@ internal object EnhancedSessionLogShare { private fun category(entry: String): Category { val value = entry.lowercase(Locale.US) - if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || + if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") || value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) || listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS @@ -950,6 +950,7 @@ internal object EnhancedSessionLogShare { "frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json", "battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt", + "rpcs3", "RPCS3.log", ) private val KNOWN_COMPONENT_PATTERNS = listOf( Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"), diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt index e9ecb7443c..263860334c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt @@ -43,6 +43,17 @@ object GameStorage { } } + fun isFat32(path: String): Boolean = runCatching { isFat32(path, File("/proc/mounts").readText()) }.getOrDefault(false) + + /** Android mounts FAT32 as vfat and exFAT as exfat; /storage is a FUSE view, so the lookup uses the raw mount. */ + internal fun isFat32(path: String, mounts: String): Boolean { + val raw = UsbLink.rawPath(path) + return mounts.lineSequence().map { it.split(' ') } + .filter { it.size >= 3 } + .filter { val point = it[1].replace("\\040", " "); raw == point || raw.startsWith("${point.trimEnd('/')}/") } + .maxByOrNull { it[1].length }?.get(2) == "vfat" + } + fun effective(context: Context): Option? { val pref = SessionPrefs.gameStorage(context) return when { diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt b/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt index 0f2b2273f8..1a0449890e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt @@ -27,14 +27,14 @@ object GameThreadHints { private const val PACE_TOLERANCE = 0.08 private val NOT_GAMES = setOf("steam", "steamwebhelper") - private val SOCS = setOf("CQ8725S", "SM8750") + private val SOCS = setOf("CQ8725S", "SM8750", "SM8750P") private var worker: Thread? = null @Synchronized fun start(context: Context): String { if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off" - if (Build.VERSION.SDK_INT < 31 || !supported(Build.SOC_MODEL)) return "game thread hints: Snapdragon 8 Elite only" + if (Build.VERSION.SDK_INT < 31 || !supported(SocNames.model())) return "game thread hints: Snapdragon 8 Elite only" val hm = context.getSystemService(PerformanceHintManager::class.java) ?: return "game thread hints: no PerformanceHintManager" val pm = context.getSystemService(PowerManager::class.java) diff --git a/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt b/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt deleted file mode 100644 index 109f6d282a..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt +++ /dev/null @@ -1,120 +0,0 @@ -package com.droiddeck.launcher.session - -import android.app.Activity -import android.app.ActivityOptions -import android.content.Context -import android.content.Intent -import android.hardware.display.DisplayManager -import android.os.Bundle -import android.os.SystemClock -import android.util.Log -import android.view.Display -import android.view.MotionEvent -import android.view.WindowManager - -// While a session is on screen, sits invisibly on top of every other display, so that display's -// home launcher is not its top activity. lmkd kills the launcher first; restarted as a top activity -// it takes focus from the session, which then drops to adj 50 and is killed next. -// Android gives a translucent activity alone in its task an input sink that eats every touch on the -// display whatever its window flags say, so a touch makes the guard leave that display until the -// session is back on top. -class KeepTopActivity : Activity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - @Suppress("DEPRECATION") overridePendingTransition(0, 0) - if (intent.getBooleanExtra(EXTRA_BOUNCE, false)) { - bounces++ - finish() - return - } - if (intent.getIntExtra(EXTRA_GENERATION, -1) != generation) { - finishAndRemoveTask() - return - } - window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) - val id = display?.displayId ?: Display.INVALID_DISPLAY - starting.remove(id) - if (id in yielded) { - finishAndRemoveTask() - return - } - guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask() - guards[id] = this - } - - override fun dispatchTouchEvent(event: MotionEvent): Boolean { - if (event.actionMasked == MotionEvent.ACTION_DOWN && !isFinishing) { - val id = display?.displayId ?: Display.INVALID_DISPLAY - yielded.add(id) - Log.i(TAG, "display $id touched, leaving it to the app below") - finishAndRemoveTask() - onYield?.invoke() - } - return true - } - - override fun onDestroy() { - guards.values.remove(this) - super.onDestroy() - } - - companion object { - private const val TAG = "KeepTop" - private const val EXTRA_BOUNCE = "bounce" - private const val EXTRA_GENERATION = "generation" - private var generation = 0 - var bounces = 0 - private set - private val guards = HashMap<Int, KeepTopActivity>() - private const val START_TIMEOUT_MS = 2_000L - private val starting = HashMap<Int, Long>() - private val yielded = HashSet<Int>() - const val YIELD_GRACE_MS = 5_000L - var onYield: (() -> Unit)? = null - - fun rearm() = yielded.clear() - - fun guardOtherDisplays(context: Context, sessionDisplay: Int): Boolean { - val displays = context.getSystemService(DisplayManager::class.java)?.displays ?: return false - var started = false - for (display in displays) { - val id = display.displayId - if (id == sessionDisplay || id in yielded || display.state != Display.STATE_ON || guards[id]?.isFinishing == false || - starting[id]?.let { SystemClock.elapsedRealtime() - it < START_TIMEOUT_MS } == true) continue - runCatching { - launch(context, id, bounce = false) - starting[id] = SystemClock.elapsedRealtime() - started = true - Log.i(TAG, "guarding display $id from a home launcher restart") - }.onFailure { Log.w(TAG, "could not guard display $id", it) } - } - if (!started) return false - return runCatching { launch(context, sessionDisplay, bounce = true) } - .onFailure { Log.w(TAG, "could not return focus to display $sessionDisplay", it) }.isSuccess - } - - fun hasPendingStarts() = starting.isNotEmpty() - - const val RETRY_MS = START_TIMEOUT_MS + 250 - - fun stepAside() { - generation++ - guards.values.toList().forEach { it.finishAndRemoveTask() } - guards.clear() - starting.clear() - } - - fun release() { - stepAside() - yielded.clear() - } - - private fun launch(context: Context, displayId: Int, bounce: Boolean) { - val intent = Intent(context, KeepTopActivity::class.java) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION) - .putExtra(EXTRA_BOUNCE, bounce) - .putExtra(EXTRA_GENERATION, generation) - context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle()) - } - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/session/LaunchCoordinator.kt b/app/src/main/java/com/droiddeck/launcher/session/LaunchCoordinator.kt new file mode 100644 index 0000000000..d989f4bc88 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/LaunchCoordinator.kt @@ -0,0 +1,82 @@ +package com.droiddeck.launcher.session + +/** + * Orders launch attempts and at most one pending game link. + * + * This is main-thread state: call it from the UI thread. A ticket is an identity, + * not a counter comparison, so a stale callback can only act on its own request. + */ +internal class LaunchTicket internal constructor(val serial: Long) + +internal class LaunchCoordinator<O : Any, R : Any> { + internal class Link<O : Any, R : Any> internal constructor( + val ticket: LaunchTicket, + val owner: O, + val request: R?, + ) { + /** Only the activity intent that delivered this link may finish it by a refresh. */ + fun ownedBy(owner: O?): Boolean = this.owner === owner + } + + private var next = 0L + private var current: LaunchTicket? = null + private var pending: Link<O, R>? = null + private var handling: LaunchTicket? = null + + /** A launch that is allowed to proceed; it supersedes any pending link. */ + fun beginLaunch(): LaunchTicket { + val ticket = LaunchTicket(++next) + current = ticket + pending = null + handling = null + return ticket + } + + /** A game-link intent; it supersedes any earlier launch or link. */ + fun beginLink(owner: O): LaunchTicket { + val ticket = LaunchTicket(++next) + current = ticket + pending = Link(ticket, owner, null) + handling = null + return ticket + } + + /** The asynchronous link read returned; false means a newer request won. */ + fun resolve(ticket: LaunchTicket, request: R?): Boolean { + val link = pending ?: return false + if (link.ticket !== ticket) return false + pending = Link(ticket, link.owner, request) + return true + } + + fun beginHandling(ticket: LaunchTicket): Boolean { + val link = pending ?: return false + if (link.ticket !== ticket || link.request == null) return false + handling = ticket + return true + } + + fun releaseHandling(ticket: LaunchTicket) { + if (handling === ticket) handling = null + } + + fun isHandling(ticket: LaunchTicket): Boolean = handling === ticket + fun isCurrent(ticket: LaunchTicket): Boolean = current === ticket + fun hasPending(): Boolean = pending != null + fun pendingLink(): Link<O, R>? = pending + + fun consume(ticket: LaunchTicket): Boolean { + val link = pending ?: return false + if (link.ticket !== ticket) return false + pending = null + handling = null + return true + } + + fun cancelAll() { + next++ + current = null + pending = null + handling = null + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt b/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt deleted file mode 100644 index 6ac1eabf9f..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.droiddeck.launcher.session - -// Tracks a pause that skipped the session's departure cleanup for the keep-top focus bounce. -internal class LightPause { - private var pending = false - private var bouncesAtPause = 0 - - fun paused(bounces: Int) { - pending = true - bouncesAtPause = bounces - } - - // The bounce resumes the session within tens of milliseconds; still paused at the timeout means - // something else holds the pause. - fun timedOut(): Boolean = take() - - fun stopped(): Boolean = take() - - fun resumed(bounces: Int): Resume { - if (!pending) return Resume.NORMAL - pending = false - return if (bounces != bouncesAtPause) Resume.LIGHT else Resume.CLEANUP_FIRST - } - - private fun take(): Boolean { - val was = pending - pending = false - return was - } - - enum class Resume { NORMAL, LIGHT, CLEANUP_FIRST } -} diff --git a/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt b/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt index 7487b98798..453e2c4ecd 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/LoadingState.kt @@ -11,7 +11,15 @@ import java.io.RandomAccessFile import java.nio.charset.StandardCharsets class LoadingState(context: Context, private val steam: Boolean = true) { - var visible by mutableStateOf(true) + private val prefs = context.getSharedPreferences("loading", Context.MODE_PRIVATE) + private val firstRun = steam && !prefs.getBoolean(FIRST_DONE, false) + private var shown by mutableStateOf(true) + var visible: Boolean + get() = shown + set(value) { + shown = value + if (!value && steam) prefs.edit().putBoolean(FIRST_DONE, true).apply() + } var step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting)) private set var topic by mutableStateOf(Topic.SESSION) @@ -33,7 +41,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) { fun tick() { val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000 elapsed = res.getString(com.droiddeck.launcher.R.string.loadstate_elapsed, seconds / 60, seconds % 60) - hint = hints[((seconds / 8) % hints.size).toInt()] + hint = if (firstRun) res.getString(com.droiddeck.launcher.R.string.loading_first_run) else hints[((seconds / 8) % hints.size).toInt()] } fun say(line: String, topic: Topic, readable: Boolean) { @@ -59,6 +67,8 @@ class LoadingState(context: Context, private val steam: Boolean = true) { private class Line(val line: String, val percent: Int, val topic: Topic, val readable: Boolean) + private var scriptStep: Line? = null + private fun read(context: Context, log: File?): Line? { if (log == null || !log.isFile) return null val text = try { @@ -81,6 +91,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) { var clientDownloadAt = -1 var clientDownload: String? = null var clientPercent = -1 + var unknownAt = -1 var offset = 0 for (line in text.split('\n')) { val at = offset @@ -95,16 +106,34 @@ class LoadingState(context: Context, private val steam: Boolean = true) { } } else { val m = UPDATE_PROGRESS.find(line) + val p = if (m == null && steam) UPDATE_PERCENT.find(line) else null if (m != null) { downloadAt = at - val done = m.groupValues[1].toLong() - val total = maxOf(1L, m.groupValues[2].toLong()) + val done = m.groupValues[1].replace(",", "").toLong() + val total = maxOf(1L, m.groupValues[2].replace(",", "").toLong()) downloadPercent = (done * 100 / total).toInt() + } else if (p != null) { + val percent = p.groupValues[1].toIntOrNull() ?: continue + if (percent < 0) { + downloadAt = -1 + unknownAt = at + } else if (percent > 0 && applyingAt <= stepAt) { + downloadAt = at + downloadPercent = percent.coerceAtMost(100) + } } else if (steam && UPDATE_APPLYING.matches(line)) { applyingAt = at } } } + val stepLine = when { + clientDownloadAt == stepAt && clientDownload != null -> Line( + context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent, + Topic.STEAM, readable = true, + ) + stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText)) + else -> null + }?.also { scriptStep = it } return when { applyingAt > stepAt && applyingAt > downloadAt -> Line( context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update_applying), -1, @@ -114,11 +143,10 @@ class LoadingState(context: Context, private val steam: Boolean = true) { context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent, Topic.STEAM, readable = true, ) - clientDownloadAt == stepAt && clientDownload != null -> Line( - context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent, - Topic.STEAM, readable = true, + stepLine != null -> stepLine + unknownAt >= 0 -> scriptStep ?: Line( + context.getString(com.droiddeck.launcher.R.string.loadstate_starting), -1, Topic.SESSION, readable = false, ) - stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText)) else -> null } } @@ -126,6 +154,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) { enum class Topic { RUNTIME, SESSION, DESKTOP, STEAM, STEAM_STARTING, OTHER } companion object { + private const val FIRST_DONE = "first_done" internal fun topicOf(scriptStep: String, steam: Boolean): Topic { val t = scriptStep.lowercase() return when { @@ -157,7 +186,8 @@ class LoadingState(context: Context, private val steam: Boolean = true) { } private const val TAIL_BYTES = 48L * 1024 - private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""") + private val UPDATE_PROGRESS = Regex("""Downloading update \(([\d,]+) of ([\d,]+) KB\)""") + private val UPDATE_PERCENT = Regex("""^\[[^\]]+\] Set percent complete: (-?\d+)\s*$""") private val UPDATE_APPLYING = Regex("""^\s*(?:\[[^\]]+\]\s*)*(?:Extracting package|Installing update)\.\.\.\s*$""") private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""") private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""") diff --git a/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt b/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt new file mode 100644 index 0000000000..2d18a84a30 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/Onboarding.kt @@ -0,0 +1,157 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller +import com.droiddeck.launcher.runtime.RuntimeInstallService +import kotlinx.coroutines.flow.MutableStateFlow + +/** What first run installs by itself, in the order it is needed, and how far each part has got. */ +object Onboarding { + enum class Step { RUNTIME, PROTON, STEAM } + + data class Progress(val label: String, val percent: Int) + + data class Facts(val runtime: Boolean = true, val proton: Boolean = true, val steam: Boolean = true) + + enum class State { DONE, ACTIVE, WAITING, FAILED } + + data class Row(val step: Step, val state: State, val label: String?, val percent: Int) + + val active = MutableStateFlow<Map<Step, Progress>>(emptyMap()) + val failed = MutableStateFlow<Map<Step, String>>(emptyMap()) + val facts = MutableStateFlow(Facts()) + + @Volatile private var appContext: Context? = null + private var hold: (() -> Unit)? = null + + /** The setup screens belong to the first run; later runtime, Proton and Steam client updates keep the usual Play button. */ + val firstRun = MutableStateFlow(true) + + fun attach(context: Context) { + appContext = context.applicationContext + val prefs = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + var done = prefs.getBoolean(KEY_FIRST_RUN_DONE, false) + if (!done && runCatching { installedAndReady(context) }.getOrDefault(false)) { + done = true + prefs.edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply() + } + firstRun.value = !done + } + + /** Everything first run installs is in place, with the same Proton rule as [recheck]. */ + private fun installedAndReady(context: Context): Boolean { + val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN } + return LinuxRuntime.isInstalled(context) && !SteamClientPrefetch.pending(context) && + (ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty()) + } + + private const val PREFS = "onboarding" + private const val KEY_FIRST_RUN_DONE = "first_run_done" + + private fun markFirstRunDone() { + val context = appContext ?: return + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply() + firstRun.value = false + } + + /** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */ + @Synchronized private fun keepAlive() { + val context = appContext ?: return + val running = active.value + if (running.isNotEmpty() && !LinuxRuntimeInstaller.isBusy()) { + if (hold == null) hold = RuntimeInstallService.holdForPackage(context, context.getString(R.string.onboarding_title)) + val rows = rows(running, failed.value, facts.value) + RuntimeInstallService.packageProgress(running.values.first().label, overall(rows)) + } else { + hold?.invoke() + hold = null + } + } + + @Synchronized fun recheck(context: Context) { + val runtime = LinuxRuntime.isInstalled(context) + val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN } + facts.value = Facts( + runtime = runtime, + proton = ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty(), + steam = runtime && !SteamClientPrefetch.pending(context), + ) + settle() + } + + /** A new attempt starts from zero once everything is ready, whichever screen is showing. */ + @Synchronized fun settle() { + if (!pending(rows(active.value, failed.value, facts.value))) { + resetProgress() + markFirstRunDone() + } + } + + fun report(step: Step, label: String, percent: Int) { + failed.value = failed.value - step + active.value = active.value + (step to Progress(label, percent)) + keepAlive() + } + + fun finish(step: Step) { + active.value = active.value - step + failed.value = failed.value - step + keepAlive() + } + + fun fail(step: Step, message: String) { + active.value = active.value - step + failed.value = failed.value + (step to message) + keepAlive() + } + + fun rows(active: Map<Step, Progress>, failed: Map<Step, String>, facts: Facts): List<Row> = Step.entries.map { step -> + val ready = when (step) { Step.RUNTIME -> facts.runtime; Step.PROTON -> facts.proton; Step.STEAM -> facts.steam } + val progress = active[step] + when { + progress != null -> Row(step, State.ACTIVE, progress.label, progress.percent) + failed[step] != null -> Row(step, State.FAILED, failed[step], -1) + ready -> Row(step, State.DONE, null, 100) + else -> Row(step, State.WAITING, null, -1) + } + } + + fun pending(rows: List<Row>): Boolean = rows.any { it.state != State.DONE } + + /** Whether first-run downloads are under way, as the home screen decides it. */ + fun settling(): Boolean = firstRun.value && active.value.isNotEmpty() && pending(rows(active.value, failed.value, facts.value)) + + @Volatile private var highWater = 0 + + @Synchronized internal fun resetProgress() { highWater = 0 } + + /** + * The aggregate fraction of the whole first-run work, weighting each step by what it downloads: about 290 MB, 630 MB and 1,050 MB. + * Steps download first and install later, restarting their own percent, so the figure only moves forward until everything is done. + */ + @Synchronized fun overall(rows: List<Row>): Int { + val measured = measure(rows) + if (!pending(rows)) { + highWater = 0 + return measured + } + highWater = maxOf(highWater, measured) + return highWater + } + + internal fun measure(rows: List<Row>): Int { + val weights = mapOf(Step.RUNTIME to 20, Step.PROTON to 30, Step.STEAM to 50) + val total = weights.values.sum() + val got = rows.sumOf { row -> + val w = weights.getValue(row.step) + when (row.state) { + State.DONE -> w + State.ACTIVE -> if (row.percent >= 0) w * row.percent / 100 else 0 + else -> 0 + } + } + return got * 100 / total + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt b/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt index 531f5f4607..71e97a9fcc 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt @@ -13,15 +13,19 @@ object PerfMode { private const val TAG = "PerfMode" const val BFI_MIN_REFRESH_HZ = 100f - fun apply(a: Activity, fpsLimit: Int = 0, refreshLimit: Int = 0): String { + fun apply(a: Activity, fpsLimit: Int = 0, refreshLimit: Int = 0, requestedRefresh: Int = 0, held: Boolean = false): String { val parts = ArrayList<String>(2) parts += try { val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay - if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else { + if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else if (held) { + if (a.window.attributes.preferredDisplayModeId != 0) { + a.window.attributes = a.window.attributes.apply { preferredDisplayModeId = 0 } + } + "display ${display.mode.refreshRate.toInt()} Hz (set by the system)" + } else { val cur = display.mode - val cap = minOf(peakRefreshCap(a), refreshLimit.takeIf { it > 0 }?.toFloat() ?: Float.POSITIVE_INFINITY) - val best = selectMode(display.supportedModes, cur, fpsLimit, cap) + val best = selectMode(display.supportedModes, cur, fpsLimit, refreshCap(a, refreshLimit), requestedRefresh) if (best != null && needsChange(display.supportedModes, a.window.attributes.preferredDisplayModeId, best)) { a.window.attributes = a.window.attributes.apply { preferredDisplayModeId = best.modeId } "display ${cur.refreshRate.toInt()} → ${best.refreshRate.toInt()} Hz (mode ${best.modeId})" @@ -55,12 +59,64 @@ object PerfMode { return if (peak >= 1f) peak else Float.POSITIVE_INFINITY } - internal fun selectMode(modes: Array<Display.Mode>, current: Display.Mode, fpsLimit: Int, cap: Float): Display.Mode? { + private fun refreshCap(context: Context, refreshLimit: Int): Float = + minOf(peakRefreshCap(context), refreshLimit.takeIf { it > 0 }?.toFloat() ?: Float.POSITIVE_INFINITY) + + fun panelRates(a: Activity, refreshLimit: Int = 0, held: Boolean = false): IntArray = try { + val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay + if (display == null || Build.VERSION.SDK_INT < 23) IntArray(0) + else panelRates(display.supportedModes, display.mode, refreshCap(a, refreshLimit), held) + } catch (t: Throwable) { Log.w(TAG, "panel rates", t); IntArray(0) } + + internal fun panelRates(modes: Array<Display.Mode>, current: Display.Mode, cap: Float, held: Boolean = false): IntArray = + if (held) intArrayOf(Math.round(current.refreshRate)) + else allowedModes(modes, current, cap).map { Math.round(it.refreshRate) }.distinct().sorted().toIntArray() + + fun panelHeld(a: Activity): Boolean = try { + val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay + val wanted = a.window.attributes.preferredDisplayModeId + val requested = display?.supportedModes?.firstOrNull { wanted != 0 && it.modeId == wanted } + display != null && requested != null && panelHeld(requested.refreshRate, display.mode.refreshRate) + } catch (t: Throwable) { Log.w(TAG, "panel held", t); false } + + internal fun panelHeld(requestedHz: Float, activeHz: Float): Boolean = + requestedHz > 1f && activeHz > 1f && Math.abs(requestedHz - activeHz) > 0.5f + + fun pacedRate(ownLimit: Int, limiterRate: Int, limiterRefresh: Int, steadyRate: Int): Int = when { + ownLimit > 0 -> ownLimit + limiterRate <= 0 -> steadyRate + steadyRate <= 0 || limiterRate < limiterRefresh || limiterRefresh <= 0 -> limiterRate + cadenceFits(limiterRate.toFloat(), steadyRate) -> limiterRate + else -> steadyRate + } + + fun contentRate(fps: Int, frameGenFactor: Int, frameGenTarget: Int): Int = when { + frameGenFactor <= 1 -> fps + frameGenTarget > 0 -> frameGenTarget + else -> fps * frameGenFactor + } + + private fun allowedModes(modes: Array<Display.Mode>, current: Display.Mode, cap: Float): List<Display.Mode> = + modes.filter { + it.physicalWidth == current.physicalWidth && it.physicalHeight == current.physicalHeight && + it.refreshRate <= cap + 0.5f + } + + internal fun selectMode( + modes: Array<Display.Mode>, + current: Display.Mode, + fpsLimit: Int, + cap: Float, + requestedRefresh: Int = 0, + ): Display.Mode? { val sameSize = modes.filter { it.physicalWidth == current.physicalWidth && it.physicalHeight == current.physicalHeight } - val allowed = sameSize.filter { it.refreshRate <= cap + 0.5f } - return allowed.filter { cadenceFits(it.refreshRate, fpsLimit) }.maxByOrNull { it.refreshRate } + val allowed = allowedModes(modes, current, cap) + val requested = if (fpsLimit > 0 || requestedRefresh <= 0) null else allowed + .filter { it.refreshRate >= requestedRefresh - 0.5f }.minByOrNull { it.refreshRate } + return requested + ?: allowed.filter { cadenceFits(it.refreshRate, fpsLimit) }.maxByOrNull { it.refreshRate } ?: allowed.maxByOrNull { it.refreshRate } ?: sameSize.minByOrNull { it.refreshRate } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt index 0d0e20c41d..c68ecd3ba1 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -23,7 +23,12 @@ object ProtonExtras { const val CHECK_EVERY_MS = 60L * 60 * 1000 @Volatile var installInProgress = false + @Volatile var prefetching = false private set + @Volatile private var checkedArchive: Triple<String, Long, Long>? = null + @Volatile private var checkedDigest: String? = null + + private fun fingerprint(archive: File) = Triple(archive.path, archive.length(), archive.lastModified()) @Volatile private var replacing = false @@ -217,24 +222,12 @@ object ProtonExtras { @Synchronized fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { - if (installInProgress) return context.getString(R.string.pextra_busy) + if (installInProgress || prefetching) return context.getString(R.string.pextra_busy) installInProgress = true return try { installNow(context, tool, onProgress) } finally { installInProgress = false } } - private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { - if (SessionState.running) return context.getString(R.string.pextra_stop_session) - if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required) - - val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name) - val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() } - val archive = File(downloads, "${tool.id}-${asset.name}") - if (asset.size > 0 && archive.length() > asset.size) archive.delete() - val missing = (asset.size - archive.length()).coerceAtLeast(0L) - if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) { - return context.getString(R.string.pextra_no_space, tool.name) - } - + private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? { val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag) onProgress(downloading, 0) var downloaded = false @@ -252,6 +245,46 @@ object ProtonExtras { } } if (!downloaded) return context.getString(R.string.pextra_download_failed) + return null + } + + /** Downloads the newest build of [tool] ahead of the runtime it installs into; [install] verifies and unpacks it later. */ + @Synchronized + fun prefetch(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { + if (installInProgress) return context.getString(R.string.pextra_busy) + prefetching = true + try { return prefetchNow(context, tool, onProgress) } finally { prefetching = false } + } + + private fun prefetchNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { + val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name) + val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() } + val archive = File(downloads, "${tool.id}-${asset.name}") + if (asset.size > 0 && archive.length() > asset.size) archive.delete() + val missing = (asset.size - archive.length()).coerceAtLeast(0L) + if (StatFs(context.filesDir.path).availableBytes < NEED_BYTES + missing) return context.getString(R.string.pextra_no_space, tool.name) + val problem = fetchArchive(context, tool, asset, archive, onProgress) + checkedArchive = if (problem == null && asset.sha256 != null && asset.size > 0 && archive.length() == asset.size) fingerprint(archive) else null + checkedDigest = if (checkedArchive != null) asset.sha256 else null + return problem + } + + private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? { + if (SessionState.running) return context.getString(R.string.pextra_stop_session) + if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required) + + val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name) + val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() } + val archive = File(downloads, "${tool.id}-${asset.name}") + if (asset.size > 0 && archive.length() > asset.size) archive.delete() + val missing = (asset.size - archive.length()).coerceAtLeast(0L) + if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) { + return context.getString(R.string.pextra_no_space, tool.name) + } + + val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) && + checkedDigest.equals(asset.sha256, ignoreCase = true) + if (!checked) fetchArchive(context, tool, asset, archive, onProgress)?.let { return it } if (asset.size > 0 && archive.length() != asset.size) { if (archive.length() > asset.size) { archive.delete() @@ -262,6 +295,7 @@ object ProtonExtras { onProgress(context.getString(R.string.pextra_verifying), -1) val verified = when { + checked -> true asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true) asset.sha512 != null -> { val expected = Downloader.downloadDirect(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value } diff --git a/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunch.kt b/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunch.kt new file mode 100644 index 0000000000..b4d1f97054 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunch.kt @@ -0,0 +1,38 @@ +package com.droiddeck.launcher.session + +/** A launch the user asked for that waits for something else to finish first, and is forgotten if it waits too long. */ +class QueuedLaunch<T : Any>(private val lifetimeMs: Long = 15 * 60_000L) { + var launch: T? = null + private set + var queuedAt: Long = 0L + private set + + fun queue(launch: T, now: Long) { + this.launch = launch + queuedAt = now + } + + /** Takes back a saved launch with the time it was first queued; one without a valid time or past its lifetime is dropped. */ + fun restore(launch: T?, queuedAt: Long, now: Long) { + if (launch != null && fresh(queuedAt, now)) { + this.launch = launch + this.queuedAt = queuedAt + } else { + clear() + } + } + + /** The launch if it is still wanted; an expired one is cleared. */ + fun current(now: Long): T? { + val queued = launch ?: return null + if (fresh(queuedAt, now)) return queued + clear() + return null + } + + fun clear() { + launch = null + } + + private fun fresh(queuedAt: Long, now: Long) = now - queuedAt in 0..lifetimeMs +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunchRunner.kt b/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunchRunner.kt new file mode 100644 index 0000000000..ab2939a481 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/QueuedLaunchRunner.kt @@ -0,0 +1,51 @@ +package com.droiddeck.launcher.session + +/** + * Starts a queued launch once nothing stands in its way and retries until it can or it expires. One runner belongs to one + * activity: destroying it clears its queue and cancels its retry, so a restored activity is the only one that starts the launch. + */ +class QueuedLaunchRunner<T : Any>( + private val queue: QueuedLaunch<T>, + private val now: () -> Long, + private val blocked: () -> Boolean, + private val busy: () -> Boolean, + private val schedule: (delayMs: Long, task: Runnable) -> Unit, + private val unschedule: (Runnable) -> Unit, + private val start: (T) -> Unit, + private val retryMs: Long = 2_000L, +) { + private var posted = false + private var retry: Runnable? = null + private var destroyed = false + + /** Call whenever the blocking setting may have changed. */ + fun poke() { + if (destroyed || posted) return + val launch = queue.current(now()) ?: return + if (blocked()) return + posted = true + schedule(0L, Runnable { + posted = false + attempt(launch) + }) + } + + private fun attempt(launch: T) { + if (destroyed || queue.current(now()) !== launch) return + if (busy()) { + val again = Runnable { if (!destroyed && queue.launch === launch) poke() } + retry = again + schedule(retryMs, again) + return + } + queue.clear() + start(launch) + } + + fun destroy() { + destroyed = true + queue.clear() + retry?.let(unschedule) + retry = null + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt index 2b4744574f..03c9fddcae 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt @@ -75,6 +75,7 @@ object SessionArtifacts { LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context)) val record = Record(dir) copySteamLogs(context, dir, record, steamArch) + copyRpcs3Log(context, dir, record) VacDiagnostics.collect(context, dir) SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log")) SessionLogCapture.dumpMemoryPressure(File(dir, "memory-pressure.log")) @@ -321,6 +322,9 @@ object SessionArtifacts { runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" } private const val LOG_MARKS = "steam-log-marks.txt" + private const val RPCS3_LOG_MARKS = "rpcs3-log-marks.txt" + private const val RPCS3_LOGS = "root/.cache/rpcs3" + private const val RPCS3_LOG = "RPCS3.log" private const val MAX_STEAM_LOG = 8L * 1024 * 1024 private const val HEAD = 4096L @@ -328,11 +332,19 @@ object SessionArtifacts { private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean) fun markSteamLogs(dir: File, logs: File) { - val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f -> + logs.listFiles { f -> f.isFile }?.let { markLogs(dir, LOG_MARKS, it.toList()) } + } + + fun markRpcs3Log(dir: File, root: File) { + markLogs(dir, RPCS3_LOG_MARKS, listOf(File(root, "$RPCS3_LOGS/$RPCS3_LOG")).filter { it.isFile }) + } + + private fun markLogs(dir: File, marks: String, files: List<File>) { + val lines = files.mapNotNull { f -> val size = f.length() head(f, size)?.let { "$size\t$it\t${f.name}" } - } ?: return - runCatching { File(dir, LOG_MARKS).writeText(lines.joinToString("") { "$it\n" }) } + } + runCatching { File(dir, marks).writeText(lines.joinToString("") { "$it\n" }) } } private fun head(f: File, length: Long): String? = runCatching { @@ -348,8 +360,8 @@ object SessionArtifacts { java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) } }.getOrNull() - private fun steamLogMarks(dir: File): List<Mark>? = runCatching { - File(dir, LOG_MARKS).readLines().mapNotNull { line -> + private fun logMarks(dir: File, marks: String): List<Mark>? = runCatching { + File(dir, marks).readLines().mapNotNull { line -> val parts = line.split('\t', limit = 3) parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } } } @@ -371,11 +383,32 @@ object SessionArtifacts { val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs") if (!logs.isDirectory) return val out = File(dir, "steam").apply { mkdirs() } - val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running } + addCopied(record, copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }) + Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out") + } + + private fun copyRpcs3Log(context: Context, dir: File, record: Record, stopWhenSessionStarts: Boolean = false) { + val out = File(dir, "rpcs3") + val logs = File(LinuxRuntime.rootDir(context), RPCS3_LOGS) + val copied = copyRpcs3LogResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running } ?: return + addCopied(record, copied) + if (copied.files.isNotEmpty()) Log.i(TAG, "collected RPCS3's log, scrubbed, into $out") + } + + internal fun copyRpcs3Log(logs: File, dir: File, out: File): List<File> = copyRpcs3LogResult(logs, dir, out) { false }?.files.orEmpty() + + private fun copyRpcs3LogResult(logs: File, dir: File, out: File, shouldStop: () -> Boolean): CopyResult? { + if (!File(dir, RPCS3_LOG_MARKS).isFile || !File(logs, RPCS3_LOG).isFile) return null + out.mkdirs() + val result = copySessionLogsResult(logs, dir, out, marksName = RPCS3_LOG_MARKS, accept = { it.name == RPCS3_LOG }, shouldStop = shouldStop) + if (result.files.isEmpty()) out.delete() + return result + } + + private fun addCopied(record: Record, result: CopyResult) { result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) } record.failed = record.failed || result.failed record.deferred = record.deferred || result.deferred - Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out") } internal fun copySessionLogs( @@ -383,20 +416,22 @@ object SessionArtifacts { dir: File, out: File, openWriter: (File) -> Writer = { it.bufferedWriter() }, - ): List<File> = copySessionLogsResult(logs, dir, out, openWriter) { false }.files + ): List<File> = copySessionLogsResult(logs, dir, out, openWriter = openWriter) { false }.files private fun copySessionLogsResult( logs: File, dir: File, out: File, + marksName: String = LOG_MARKS, + accept: (File) -> Boolean = { true }, openWriter: (File) -> Writer = { it.bufferedWriter() }, shouldStop: () -> Boolean, ): CopyResult { - val marks = steamLogMarks(dir) + val marks = logMarks(dir, marksName) val copied = ArrayList<File>() var failed = false var deferred = false - val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false) + val sources = logs.listFiles { f -> f.isFile && accept(f) } ?: return CopyResult(copied, true, false) for (src in sources) { if (shouldStop()) { failed = true @@ -567,6 +602,7 @@ object SessionArtifacts { steamArch = recordedClient(dir), stopWhenSessionStarts = stopWhenSessionStarts, ) + copyRpcs3Log(context, dir, record, stopWhenSessionStarts) if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) { if (!record.failed && VacDiagnostics.collect(context, dir)) { try { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt index 9b253d88a7..919891fa45 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt @@ -12,6 +12,9 @@ object SessionDisplay { const val FOLLOW_SCALE_MAX = 8f private const val FOLLOW_SCALED_PREFIX = "follow/" + const val LINK_LANDSCAPE = "link/landscape" + const val LINK_PORTRAIT = "link/portrait" + const val DEFAULT_RESOLUTION = "720p" private val PRESET_HEIGHTS = listOf(720, 900, 1080) @@ -35,6 +38,23 @@ object SessionDisplay { else -> null } + fun isLink(choice: String): Boolean = choice == LINK_LANDSCAPE || choice == LINK_PORTRAIT + + fun orientCustom(choice: String, portrait: Boolean): String { + val parts = choice.split('x').map { it.toIntOrNull() } + if (parts.size != 2 || parts.any { it == null || it <= 0 }) return choice + val width = parts[0]!! + val height = parts[1]!! + return if ((portrait && width > height) || (!portrait && height > width)) "${height}x$width" else choice + } + + fun effectiveChoice(landscape: String, portrait: String, forPortrait: Boolean): String { + val own = if (forPortrait) portrait else landscape + if (!isLink(own)) return own + val other = if (forPortrait) landscape else portrait + return if (isLink(other)) DEFAULT_RESOLUTION else orientCustom(other, forPortrait) + } + fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> = (maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv()) @@ -69,8 +89,12 @@ object SessionDisplay { const val UNFOLDED_MIN_DP = 600 - fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0): Int = - (minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) - tabRow.coerceAtLeast(0)).coerceAtLeast(0) and 1.inv() + fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0, aspect: Float = 0f): Int { + val row = tabRow.coerceAtLeast(0) + val cap = (height * UNFOLDED_MAX_GAME_SHARE).toInt() + if (aspect > 0f && aspect < 16f / 9f) return minOf((width / aspect).toInt(), cap - row).coerceAtLeast(0) and 1.inv() + return (minOf(width * 9 / 16, cap) - row).coerceAtLeast(0) and 1.inv() + } fun unfoldedControlsWanted( enabled: Boolean, diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 53b54e9ca2..177774a4ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -39,6 +39,7 @@ object SessionFiles { private val SERVICE_PACKS = mapOf( AddonPack.UBISOFT to "usr/local/lib/droiddeck-ubisoft", AddonPack.ROCKSTAR to "usr/local/lib/droiddeck-rockstar", + AddonPack.EPIC to "usr/local/lib/droiddeck-epic", AddonPack.DIRT to "usr/local/lib/droiddeck-dirt", ) @@ -47,6 +48,8 @@ object SessionFiles { fun ensureRockstarService(context: Context) = ensureStoreService(context, AddonPack.ROCKSTAR) + fun ensureEpicParent(context: Context) = ensureStoreService(context, AddonPack.EPIC) + /** The DiRT 3 / DiRT Showdown ws2_32 stand-in; droiddeck-game-env applies it only when it is staged. */ fun ensureDirtStandIn(context: Context) = ensureStoreService(context, AddonPack.DIRT) @@ -92,7 +95,11 @@ object SessionFiles { return all } - fun stage(context: Context, root: File, startsSession: Boolean = false) { + private val STAGE_LOCK = Any() + + fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) } + + private fun stageNow(context: Context, root: File, startsSession: Boolean) { if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) } catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) } GameEnvironmentStore.publish(context) @@ -123,6 +130,7 @@ object SessionFiles { "usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard", "usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window", "usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install", + "usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply", "usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale", "usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language", "usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders", @@ -177,6 +185,8 @@ object SessionFiles { "usr/local/bin/droiddeck-flatpak-run" to "usr/local/bin/droiddeck-flatpak-run", "usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run", "usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec", + "usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge", + "usr/local/bin/droiddeck-headless" to "usr/local/bin/droiddeck-headless", "usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run", "usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open", "usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run", @@ -253,7 +263,9 @@ object SessionFiles { "usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json", "usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke", "usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime", + "usr/local/lib/droiddeck/dwarfsextract" to "usr/local/lib/droiddeck/dwarfsextract", "usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst", + "usr/local/share/licenses/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/LICENSE", "usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE", ) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) -> val dir = asset.substringBeforeLast('/') @@ -284,6 +296,7 @@ object SessionFiles { File(root, "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json").delete() LegacyNames.migrateRootfs(root) ComponentsManager.migrateLaunchDir(context) + runCatching { ComponentsManager.migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) } EsyncPacks.stageBundled(context, root) val directAudio = arrayOf( "aarch64-unix/winedirectaudio.so", @@ -654,6 +667,7 @@ object SessionFiles { private const val UI_STATE = "UIStoreLocalSteamUIState" private const val SORT_RECENT_OFF = "\\\"bSortedByRecent\\\":false" private const val SORT_RECENT_ON = "\\\"bSortedByRecent\\\":true" + private const val LIBRARY_BIG_ART = "LibraryHomeBigArt" private const val BATTERY_PERCENT_ON = "{\\\"bShowBatteryPercentage\\\":true}" /** @@ -703,7 +717,12 @@ object SessionFiles { val block = out.substring(web.keyStart, web.close + 1) out = out.replaceRange(web.keyStart, web.close + 1, setScalar(block, BATTERY_PREFERENCES, BATTERY_PERCENT_ON, newline)) } - return seedRecentSort(out, newline) + out = seedRecentSort(out, newline) + val last = findObject(out, "UserLocalConfigStore", 0, out.length) ?: return out + if (!hasKey(out.substring(last.open + 1, last.close), LIBRARY_BIG_ART)) { + out = insertInto(out, last, listOf("\"$LIBRARY_BIG_ART\"\t\t\"1\""), newline) + } + return out } // The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort, @@ -723,9 +742,11 @@ object SessionFiles { private fun insertInto(text: String, parent: VdfBlock, lines: List<String>, newline: String): String { val lineStart = text.lastIndexOf('\n', parent.close).let { if (it < 0) 0 else it + 1 } - val indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t" + val before = text.substring(lineStart, parent.close) + val indent = before.takeWhile { it == '\t' || it == ' ' } + "\t" val section = lines.joinToString(newline) { indent + it } + newline - return text.substring(0, lineStart) + section + text.substring(lineStart) + if (before.isBlank()) return text.substring(0, lineStart) + section + text.substring(lineStart) + return text.substring(0, parent.close) + newline + section + text.substring(parent.close) } private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds") diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionHdr.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionHdr.kt new file mode 100644 index 0000000000..e559ac4ff0 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionHdr.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.agent.AgentGuest +import com.droiddeck.launcher.wayland.CompositorHost +import com.droiddeck.launcher.wayland.WaylandCompositor +import java.util.concurrent.Executors + +object SessionHdr { + private const val RETRIES = 5 + private const val RETRY_MS = 2_000L + + private val requests = Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "session-hdr").apply { isDaemon = true } + } + @Volatile private var wanted = false + + fun set(context: Context, mode: String, on: Boolean) { + SessionPrefs.setHdr(context, mode, on) + if (!SessionState.running || !SessionState.hdrCapable || !CompositorHost.isStarted) return + if (SessionPrefs.prefMode(SessionState.mode) != mode) return + SessionState.hdr = on + wanted = on + WaylandCompositor.nativeSetHdrOutput(on) + WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode)) + val app = context.applicationContext + val session = SessionState.sessionId + requests.execute { + var tries = 0 + while (wanted == on && SessionState.running && SessionState.sessionId == session && + !AgentGuest.setGamescopeConvar(app, "hdr_enabled", if (on) 1 else 0) && tries++ < RETRIES) { + try { Thread.sleep(RETRY_MS) } catch (e: InterruptedException) { return@execute } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index a0208ec727..8889ccb261 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -63,6 +63,13 @@ object SessionPrefs { .takeIf { value -> orientationOptions.any { it.first == value } } ?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + /** The session menu's width in dp the user dragged it to; null keeps the default. */ + fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 } + + fun setDrawerWidthDp(context: Context, dp: Int) { + prefs(context).edit().putInt("drawerWidthDp", dp).apply() + } + fun setOrientation(context: Context, orientation: Int) { require(orientationOptions.any { it.first == orientation }) prefs(context).edit().putInt("orientation", orientation).apply() @@ -85,6 +92,12 @@ object SessionPrefs { prefs(context).edit().putBoolean("launcherFullscreen", on).apply() } + fun controllerHaptics(context: Context): Boolean = prefs(context).getBoolean("controllerHaptics", true) + + fun setControllerHaptics(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("controllerHaptics", on).apply() + } + fun blackFrameInsertion(context: Context): Boolean = prefs(context).getBoolean("blackFrameInsertion", false) fun setBlackFrameInsertion(context: Context, on: Boolean) { @@ -419,6 +432,18 @@ object SessionPrefs { e.remove("gameStoresEnabled").remove("soundtracksEnabled").remove("agentTab").putInt("navTabLayout", version).apply() } + fun drawerPageOrder(context: Context): List<String> = idList(prefs(context).getString("drawerPageOrder", null)) + + fun setDrawerPageOrder(context: Context, order: List<String>) { + prefs(context).edit().putString("drawerPageOrder", order.joinToString(",")).apply() + } + + fun drawerPageHidden(context: Context): Set<String> = idList(prefs(context).getString("drawerPageHidden", null)).toSet() + + fun setDrawerPageHidden(context: Context, keys: Set<String>) { + prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply() + } + fun setNavTabHidden(context: Context, keys: Set<String>) { prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply() } @@ -477,6 +502,13 @@ object SessionPrefs { fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), false) + fun hudOnlyDuringGame(context: Context): Boolean = + prefs(context).getBoolean("hudOnlyDuringGame", false) + + fun setHudOnlyDuringGame(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("hudOnlyDuringGame", on).apply() + } + fun setHudEnabled(context: Context, on: Boolean) { prefs(context).edit().putBoolean(hudKey(context), on).apply() } @@ -596,6 +628,12 @@ object SessionPrefs { prefs(context).edit().putBoolean("backHold", on).apply() } + fun dockedMenuController(context: Context): Boolean = prefs(context).getBoolean("dockedMenuController", false) + + fun setDockedMenuController(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("dockedMenuController", on).apply() + } + fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false) fun setBackActionsInverted(context: Context, inverted: Boolean) { @@ -664,12 +702,21 @@ object SessionPrefs { prefs(context).getString("shape", null) ?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO - fun oscMode(context: Context): String = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO + fun oscMode(context: Context, steamSession: Boolean = true): String { + val saved = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO + return if (!steamSession && saved == OSC_STEAM_QAM) OSC_AUTO else saved + } fun setOscMode(context: Context, mode: String) { prefs(context).edit().putString("osc", mode).apply() } + fun oscRearButtons(context: Context): Boolean = prefs(context).getBoolean("oscRearButtons", false) + fun setOscRearButtons(context: Context, shown: Boolean) { prefs(context).edit().putBoolean("oscRearButtons", shown).apply() } + + fun oscTrackpads(context: Context): Boolean = prefs(context).getBoolean("oscTrackpads", false) + fun setOscTrackpads(context: Context, shown: Boolean) { prefs(context).edit().putBoolean("oscTrackpads", shown).apply() } + fun linuxDriver(context: Context): String = prefs(context).getString("linuxDriver", null) ?: prefs(context).getString("linuxDriver.steam", null) @@ -767,6 +814,11 @@ object SessionPrefs { prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply() } + fun displayDriverFromAuto(context: Context): Boolean { + val id = androidDriver(context) + return id.isEmpty() || (gpuDriverMode(context) == GPU_DRIVERS_AUTO && id in gpuAutoInstalled(context)) + } + fun picturePosition(context: Context): String = prefs(context).getString("picturePosition", "center") @@ -826,6 +878,12 @@ object SessionPrefs { prefs(context).edit().putBoolean("stretch16x9", on).apply() } + fun avoidNotch(context: Context): Boolean = prefs(context).getBoolean("avoidNotch", false) + + fun setAvoidNotch(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("avoidNotch", on).apply() + } + fun directAudio(context: Context): Boolean = prefs(context).getBoolean("directAudio", true) @@ -972,7 +1030,7 @@ object SessionPrefs { prefs(context).edit().putBoolean("prootNoSeccomp", on).apply() } - fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", false) + fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true) fun setNativeUserland(context: Context, on: Boolean) { prefs(context).edit().putBoolean("nativeUserland", on).apply() @@ -1281,14 +1339,35 @@ object SessionPrefs { private fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", 720) - fun resolutionChosen(context: Context, mode: String): Boolean = + fun resolutionChosen(context: Context, mode: String, portrait: Boolean = false): Boolean = prefs(context).contains("displayResolution.$mode") || - prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null + prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null || + (portrait && prefs(context).contains("displayResolution.portrait.$mode")) - fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>): String { + fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean = false): String = + SessionDisplay.effectiveChoice( + resolutionStored(context, mode, panel, false), resolutionStored(context, mode, panel, true), portrait) + + fun followScales(context: Context, mode: String, panel: Pair<Int, Int>): Pair<Float?, Float?> = + SessionDisplay.followScale(resolutionChoice(context, mode, panel, false)) to + SessionDisplay.followScale(resolutionChoice(context, mode, panel, true)) + + fun resolutionStored(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean): String { + if (!portrait) return landscapeResolutionStored(context, mode, panel) + val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE + if (value == SessionDisplay.LINK_LANDSCAPE || value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) || + SessionDisplay.presetHeight(value) != null) return value + return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE + } + + fun parseOrientedResolution(text: String): Pair<Int, Int>? = + parseResolution(text) ?: text.trim().split('x', 'X', '×', '*').takeIf { it.size == 2 } + ?.let { parseResolution("${it[1]}x${it[0]}") }?.let { it.second to it.first } + + private fun landscapeResolutionStored(context: Context, mode: String, panel: Pair<Int, Int>): String { val saved = prefs(context) saved.getString("displayResolution.$mode", null)?.let { value -> - if (value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) || + if (value == SessionDisplay.MATCH_SCREEN || value == SessionDisplay.LINK_PORTRAIT || SessionDisplay.isFollow(value) || SessionDisplay.presetHeight(value) != null) return value parseResolution(value)?.let { return "${it.first}x${it.second}" } } @@ -1300,13 +1379,22 @@ object SessionPrefs { else "${legacy.first}x${legacy.second}" } - fun setResolutionChoice(context: Context, mode: String, choice: String) { - val value = if (choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(choice) || + fun setResolutionChoice(context: Context, mode: String, choice: String, portrait: Boolean = false) { + val link = if (portrait) SessionDisplay.LINK_LANDSCAPE else SessionDisplay.LINK_PORTRAIT + val value = if (choice == link || choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(choice) || SessionDisplay.presetHeight(choice) != null) choice else { - val size = requireNotNull(parseResolution(choice)) { "Invalid resolution" } + val size = requireNotNull(if (portrait) parseOrientedResolution(choice) else parseResolution(choice)) { "Invalid resolution" } "${size.first}x${size.second}" } - prefs(context).edit().putString("displayResolution.$mode", value).apply() + val panel = SessionDisplay.panelSize(context) + val landscapeStored = resolutionStored(context, mode, panel, false) + val portraitStored = resolutionStored(context, mode, panel, true) + val edit = prefs(context).edit() + if (value == link && SessionDisplay.isLink(if (portrait) landscapeStored else portraitStored)) { + val concrete = SessionDisplay.effectiveChoice(landscapeStored, portraitStored, !portrait) + edit.putString(if (portrait) "displayResolution.$mode" else "displayResolution.portrait.$mode", concrete) + } + edit.putString(if (portrait) "displayResolution.portrait.$mode" else "displayResolution.$mode", value).apply() } fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", DEFAULT_FEX_PRESET) ?: DEFAULT_FEX_PRESET @@ -1474,7 +1562,7 @@ object SessionPrefs { fun adoptAddedGameExe(context: Context, folderPath: String, expected: String, path: String, seen: Int): Boolean = synchronized(addedGameLock) { val unchanged = addedGameExe(context, folderPath) == expected - if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply() + if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putString("addedAdopted:Exe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply() unchanged } @@ -1617,10 +1705,18 @@ object SessionPrefs { return Pair(w and 1.inv(), h and 1.inv()) } - fun hdr(context: Context, mode: String): Boolean = prefs(context).getBoolean("hdr.$mode", false) + fun hdrKey(mode: String): String = "hdr.$mode" + + fun hdr(context: Context, mode: String): Boolean = prefs(context).getBoolean(hdrKey(mode), false) fun setHdr(context: Context, mode: String, on: Boolean) { - prefs(context).edit().putBoolean("hdr.$mode", on).apply() + prefs(context).edit().putBoolean(hdrKey(mode), on).apply() + } + + fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.$mode", true) + + fun setZeroCopy(context: Context, mode: String, on: Boolean) { + prefs(context).edit().putBoolean("zeroCopy.$mode", on).apply() } const val FPS_UNPACED = -1 @@ -1937,7 +2033,7 @@ object SessionPrefs { fun displayMode(context: Context, mode: String, program: String?): String = if (mode == SessionService.MODE_RUN && com.droiddeck.launcher.runtime.UserApps.launches(program) && - resolutionChosen(context, SessionService.MODE_DESKTOP)) SessionService.MODE_DESKTOP + (resolutionChosen(context, SessionService.MODE_DESKTOP) || resolutionChosen(context, SessionService.MODE_DESKTOP, true))) SessionService.MODE_DESKTOP else prefMode(mode) fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index e15fac1c64..f7af8ff9ae 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -589,7 +589,10 @@ class SessionService : Service() { val sessionDir = openSessionFolder() try { - SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) } + SessionEvents.step("game-environment") { + com.droiddeck.launcher.runtime.BattleNet.ensureDefaults(this, SessionState.program) + GameEnvironmentStore.publish(this) + } } catch (e: Exception) { Log.e(TAG, "could not publish the game environment", e) failSession(gen, "GAME_ENVIRONMENT_FAILED", getString(R.string.session_game_environment_failed), -1) @@ -781,7 +784,7 @@ class SessionService : Service() { if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back") val hostEnv = if (nativeUserland) HostEnvironment().also { env -> Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)") - com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, SessionPrefs.guestHostname(this)) + com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this)) .forEach { (k, v) -> env[k] = v } } else prootEnv @@ -1025,6 +1028,9 @@ class SessionService : Service() { if (!bridge && !venus && SystemVulkanDriver.usesDefault(linuxDriverId)) { SystemVulkanDriver.addEnvironment(this, guest) } + com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetDisplayBufferDriver( + !bridge && !venus && LinuxVulkanDriverManager(this).rendersToDisplayBuffers(linuxDriverId), + ) (if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)) ?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) } if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) { @@ -1064,6 +1070,7 @@ class SessionService : Service() { guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this))) guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216") if (SessionState.mode == MODE_STEAM) guest.add("DD_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0")) + SessionPaths.current()?.let { SessionArtifacts.markRpcs3Log(it, LinuxRuntime.rootDir(this)) } SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null SessionState.steamClientArch?.let { arch -> guest.add("DD_STEAM_CLIENT_ARCH=$arch") @@ -1613,6 +1620,11 @@ class SessionService : Service() { return } val accepted = gameId!! + if (pendingSteamGameId == null && SteamGameProcess.alreadyRunning(accepted, SessionState.gameId)) { + Log.i(TAG, "game $accepted is already running; resuming it instead of launching it again") + if (SessionState.suspended || SessionState.suspending) resumeSession() + return + } if (!pendingSteamPreviousGamePending) { pendingSteamPreviousGameId = SessionState.gameId pendingSteamPreviousGamePending = true @@ -1943,11 +1955,6 @@ class SessionService : Service() { } return } - if (path == com.droiddeck.launcher.runtime.BattleNet.FEX_REQUEST) { - File(dir, path).delete() - com.droiddeck.launcher.runtime.BattleNet.answerFexRequest(this@SessionService, dir) - return - } if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) { val request = File(dir, path) val text = runCatching { request.readText() }.getOrNull() ?: return @@ -2394,8 +2401,7 @@ class SessionService : Service() { override fun onTaskRemoved(rootIntent: Intent?) { if (rootIntent?.component?.className in setOf( com.droiddeck.launcher.ui.DualScreenActivity::class.java.name, - com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name, - KeepTopActivity::class.java.name)) return + com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return if (pipTask || xrActivityVisible) { Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy") activityVisible = false @@ -2700,6 +2706,7 @@ class SessionService : Service() { gameId: String? = null, displayId: Int = Display.DEFAULT_DISPLAY, ) { + SteamClientPrefetch.cancel() SessionState.activityDisplayId = displayId val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode) .putExtra(EXTRA_DISPLAY_ID, displayId) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index 6124947151..92255febec 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -115,6 +115,10 @@ object SessionState { @JvmStatic var hdr = false + @JvmStatic var hdrCapable = false + + @JvmStatic var hdrDisplay = false + @Volatile private var deckPadValue = false @JvmStatic var deckPad: Boolean get() = deckPadValue @@ -129,6 +133,7 @@ object SessionState { @Volatile var padBridge: com.droiddeck.launcher.input.PadBridge? = null @Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE + @Volatile var bottomMenu = false @Volatile var secondScreenDisplay = -1 @Volatile var secondScreenAutoOpened = false @Volatile var secondScreenProvisional = false @@ -143,6 +148,9 @@ object SessionState { @Volatile var outputSize: Pair<Int, Int> = Pair(1920, 1080) + @Volatile + var followScales: Pair<Float?, Float?> = null to null + @Volatile var followScreen = false var followScale = 1f diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index f85318b595..caa78440a0 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -12,13 +12,13 @@ object SettingsReset { private const val TAG = "SettingsReset" internal val SESSION_KEYS = setOf( - "orientation", "launcherFullscreen", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", - "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", + "orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", + "drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "storesInstallLanguage", - "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController", + "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", - "stretch16x9", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", + "stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt new file mode 100644 index 0000000000..8f96cf7a4e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamClientPrefetch.kt @@ -0,0 +1,103 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.runtime.LinuxRuntime +import java.io.File +import kotlinx.coroutines.flow.update + +/** + * Downloads Valve's Steam client while the session is stopped, so the first Play does not wait on it. + * It runs the same droiddeck-steam-install the session runs, which keeps what arrived when it is cut + * short and resumes from there. + */ +object SteamClientPrefetch { + private const val TAG = "SteamClientPrefetch" + private val DOWNLOADING = Regex("""downloading Steam: .*, (\d+) of (\d+) MB""") + + private const val CANCELLED = "cancelled" + private val lock = Any() + private var process: Process? = null + private var cancelled = false + @Volatile private var thread: Thread? = null + + internal fun parse(line: String): Pair<Int, Int>? { + val match = DOWNLOADING.find(line) ?: return null + val done = match.groupValues[1].toLongOrNull() ?: return null + val total = match.groupValues[2].toLongOrNull()?.takeIf { it > 0 } ?: return null + return (done * 100 / total).toInt().coerceIn(0, 100) to total.toInt() + } + + fun running(): Boolean = thread?.isAlive == true + + private const val CACHED = "root/.local/share/Steam/package/droiddeck-cached" + + fun installPending(context: Context): Boolean = SteamDownloadMonitor.clientInstallPending(LinuxRuntime.rootDir(context)) + + fun pending(context: Context): Boolean = + installPending(context) || !File(LinuxRuntime.rootDir(context), CACHED).isFile + + /** Stops a running download so a session can take over; the script resumes the partial files. */ + fun cancel() { + synchronized(lock) { + cancelled = true + process?.destroy() + } + } + + private fun isCancelled() = synchronized(lock) { cancelled } + + @Synchronized + fun start(context: Context, label: (Int) -> String, failedLabel: String) { + if (running() || SessionState.running || !LinuxRuntime.isInstalled(context) || !pending(context)) return + val app = context.applicationContext + synchronized(lock) { cancelled = false } + thread = Thread({ + Onboarding.report(Onboarding.Step.STEAM, label(-1), -1) + val problem = runCatching { run(app, label) }.getOrElse { it.message ?: it.javaClass.simpleName } + synchronized(lock) { process = null } + if (problem == null && !pending(app)) Onboarding.finish(Onboarding.Step.STEAM) + else if (SessionState.running || problem == CANCELLED || isCancelled()) Onboarding.finish(Onboarding.Step.STEAM) + else Onboarding.fail(Onboarding.Step.STEAM, problem ?: failedLabel) + val steamReady = !pending(app) + Onboarding.facts.update { it.copy(steam = steamReady) } + Onboarding.settle() + }, "steam-client-prefetch").also { it.start() } + } + + private fun run(context: Context, label: (Int) -> String): String? { + if (isCancelled()) return CANCELLED + val root = LinuxRuntime.rootDir(context) + LinuxRuntime.writeAccounts(context) + SessionFiles.stage(context, root) + val install = installPending(context) + val cacheProblem = script(context, listOf("--cache"), label, 0, if (install) 90 else 100) + if (cacheProblem == CANCELLED || !install) return cacheProblem + return script(context, emptyList(), label, 90, 100) + } + + private fun script(context: Context, args: List<String>, label: (Int) -> String, from: Int, to: Int): String? { + val guest = listOf( + "/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin", + "LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share", "/usr/local/bin/droiddeck-steam-install", + ) + args + if (isCancelled()) return CANCELLED + val child = ProtonExtras.guestProcess(context, guest).start() + synchronized(lock) { + if (cancelled) { + child.destroy() + return CANCELLED + } + process = child + } + child.inputStream.bufferedReader().useLines { lines -> + lines.forEach { line -> + Log.i(TAG, line) + val progress = parse(line) + if (progress != null) Onboarding.report(Onboarding.Step.STEAM, label(progress.second), from + progress.first * (to - from) / 100) + } + } + val status = child.waitFor() + return if (status == 0) null else "droiddeck-steam-install exited $status" + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt index 7a00553f3b..6b7ecda60c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt @@ -61,4 +61,11 @@ object SteamGameProcess { runCatching { File(p, "cmdline").readBytes() } .getOrNull()?.let { matches(it, gameId) } == true } == true + + // A front end that resumes a player by launching the same game again would otherwise have Steam + // start it a second time, which Steam answers with "Game already running". + fun alreadyRunning(requested: String, current: String?, proc: File = File("/proc")): Boolean { + val appId = steamAppIdForGameId(requested) ?: return false + return appId == steamAppIdForGameId(current.orEmpty()) && running(requested, proc) + } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt b/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt deleted file mode 100644 index 3c7a55adea..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.ComponentCallbacks2 - -internal object TopUnderPressure { - const val WINDOW_MS = 5_000L - - fun isPressure(level: Int) = - level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL || level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW - - fun shouldReclaim(nowMs: Long, pressureAtMs: Long, sessionRunning: Boolean, finishing: Boolean) = - sessionRunning && !finishing && pressureAtMs > 0 && nowMs - pressureAtMs in 0..WINDOW_MS -} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudPlan.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudPlan.kt index d3c63b203a..940d1eee71 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudPlan.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudPlan.kt @@ -36,13 +36,14 @@ object CloudPlan { return Plan(transfer, conflicts, same) } - fun up(local: Map<String, Local>, remote: Map<String, Remote>, baseline: Map<String, Entry>?): Plan { + fun up(local: Map<String, Local>, remote: Map<String, Remote>, baseline: Map<String, Entry>?, deleted: Set<String> = emptySet()): Plan { if (baseline == null) return Plan(emptyList(), emptyList(), emptyList(), refused = "no-baseline") val transfer = ArrayList<String>(); val conflicts = ArrayList<String>(); val same = ArrayList<String>() for ((name, l) in local) { val r = remote[name] val b = baseline[name] when { + r == null && name in deleted && !localChanged(l, b) -> Unit r == null -> transfer += name same(l, r) -> same += name localChanged(l, b) && cloudChanged(r, b) -> conflicts += name diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt index c2fd9890d5..5923cd6e44 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt @@ -430,17 +430,20 @@ object CloudSaves { internal fun md5(data: ByteArray): String = MessageDigest.getInstance("MD5").digest(data).joinToString("") { "%02x".format(it) } - private fun remote(cloud: CloudTransport, wanted: (String) -> Boolean): Map<String, CloudFile> { + private class Listing(val live: Map<String, CloudFile>, val deleted: Set<String>) + + private fun remote(cloud: CloudTransport, wanted: (String) -> Boolean): Listing { val files = cloud.list() val pool = Executors.newFixedThreadPool(PARALLEL, com.droiddeck.launcher.stores.download.DownloadQueue.workerFactory("cloud")) for (f in files) if (wanted(f.name)) pool.execute { runCatching { cloud.details(f) } } pool.shutdown(); pool.awaitTermination(2, TimeUnit.MINUTES) - return files.associateBy { it.name } + val (gone, live) = files.partition(cloud::deleted) + return Listing(live.associateBy { it.name }, gone.mapTo(HashSet()) { it.name }) } internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean, claim: () -> Boolean = { true }): Result { val files = localFiles(dir).filterKeys(cloud::wants) - val remote = remote(cloud) { it in files } + val remote = remote(cloud) { it in files }.live val local = files.mapValues { CloudPlan.Local(md5(it.value)) } val key = scope(store, id, dir) val base = baseline(context, store, key) @@ -498,9 +501,10 @@ object CloudSaves { val base = baseline(context, store, key) ?: return Result("skipped", 0, 0, "no-baseline") val files = localFiles(dir).filterKeys(cloud::wants).let { all -> if (cloud is UbisoftCloudTransport) all.filterValues(::markUbisoftSave) else all } if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local") - val remote = remote(cloud) { it in files } + val listing = remote(cloud) { it in files } + val remote = listing.live val local = files.mapValues { CloudPlan.Local(md5(it.value)) } - val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base) + val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base, listing.deleted) val alike = alike(cloud, planned.conflicts, local, remote) val plan = settled(planned, alike) val saved = savedConflicts(context, store, key).filter { it !in alike && it !in plan.same } @@ -547,7 +551,7 @@ object CloudSaves { send = send.filter { it in stamped } for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t) } - val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null } + val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null }.live for (name in send) { val r = cloud.committed(name) ?: after[name] next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt index 9e0ad99196..efb79d8543 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt @@ -31,6 +31,7 @@ interface CloudTransport { val contentDigests: Boolean get() = true fun committed(name: String): CloudFile? = null fun wants(name: String): Boolean = true + fun deleted(file: CloudFile): Boolean = false fun list(): List<CloudFile> fun details(file: CloudFile) {} fun get(file: CloudFile): Pair<ByteArray, Long> @@ -252,6 +253,8 @@ private fun gzipFile(src: File, dst: File): GzipFile { } } +internal const val GOG_DELETED_MD5 = "aadd86936a80ee8a369579c3926f1b3c" + internal const val GOG_CLOUD_UA = "GOGGalaxyCommunicationService/2.0.13.27 (Windows_32bit) dont_sync_marker/true installation_source/gog" /** GOG Galaxy parses `X-Object-Meta-LocalLastModified`; objects without it fail as "invalid data". */ @@ -276,8 +279,11 @@ class GogCloud( private fun cloudKey(name: String) = key((prefix ?: "") + name) + override fun deleted(file: CloudFile): Boolean = file.md5.equals(GOG_DELETED_MD5, ignoreCase = true) + override fun list(): List<CloudFile> { val c = open(base, "GET", token, ua) + c.setRequestProperty("Accept", "application/json") val code = c.responseCode if (code == 404) { c.disconnect(); return emptyList() } if (code !in 200..299) { @@ -300,7 +306,7 @@ class GogCloud( lm > 0 -> lm * 1000 iso > 0 -> iso else -> -1L - }) + }, o.optString("hash").trim().ifEmpty { null }) } } else { text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt index ef355cc038..a99991996e 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreArchiveUnpacker.kt @@ -28,20 +28,26 @@ internal class StoreArchiveUnpacker( private val logName: String, ) { var work: File = File("") + var limit = Long.MAX_VALUE - fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) { + class TooLarge : java.io.IOException() + + fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) = + unpack(archive, filename, { done, total -> handle.stageProgress(done, total) }, handle::log) + + fun unpack(archive: File, filename: String, progress: (Long, Long) -> Unit, log: (String) -> Unit) { when (val kind = ItchArchives.kind(archive, filename)) { - "zip" -> unzip(archive, handle) + "zip" -> unzip(archive, progress, log) "7z" -> try { - sevenZip(archive, handle) + sevenZip(archive, progress, log) } catch (e: MemoryLimitException) { - handle.log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime") - unrar(archive, handle, kind) + log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime") + unrar(archive, progress, log, kind) } - "rar" -> unrar(archive, handle, kind) + "rar" -> unrar(archive, progress, log, kind) "exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" })) - "tar" -> untar(archive, null, handle) - "gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle) + "tar" -> untar(archive, null, progress, log) + "gz", "bz2", "xz" -> untar(archive, kind, progress, log) ?: single(archive, kind, progress, log) else -> copy(archive, File(work, filename.ifBlank { "game" })) } } @@ -53,7 +59,7 @@ internal class StoreArchiveUnpacker( return if (path == root || path.startsWith(root + File.separator)) file else null } - private fun unrar(archive: File, handle: DownloadQueue.JobHandle, kind: String) { + private fun unrar(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit, kind: String) { if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(unsupported, kind)) val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null else listOf(work.absolutePath) @@ -62,23 +68,28 @@ internal class StoreArchiveUnpacker( if (!line.startsWith("proot ")) onLine(line) } var entries = 0L - bsdtar(listOf("-tf", archive.absolutePath)) { entries++ } + var size = 0L + bsdtar(listOf("-tvf", archive.absolutePath)) { line -> + entries++ + size += LISTED_SIZE.find(line)?.groupValues?.get(1)?.toLongOrNull() ?: 0L + } + if (size > limit) throw TooLarge() var done = 0L val tail = ArrayDeque<String>() val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line -> - if (line.startsWith("x ")) handle.stageProgress(++done, entries) else { + if (line.startsWith("x ")) progress(++done, entries) else { if (tail.size == 5) tail.removeFirst() tail.addLast(line) } } if (cancelled.get()) return if (code != 0) { - handle.log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}") + log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}") throw IllegalStateException(app.getString(extractFailed, code)) } } - private fun sevenZip(archive: File, handle: DownloadQueue.JobHandle) { + private fun sevenZip(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit) { val total = archive.length() var written = 0L val buffer = ByteArray(64 * 1024) @@ -90,7 +101,7 @@ internal class StoreArchiveUnpacker( val entry = seven.nextEntry ?: break val file = target(entry.name) if (file == null) { - handle.log("$label: skipped an entry outside the game folder") + log("$label: skipped an entry outside the game folder") continue } if (entry.isDirectory) { @@ -105,7 +116,8 @@ internal class StoreArchiveUnpacker( if (read < 0) break out.write(buffer, 0, read) written += read - handle.stageProgress(written, total) + if (written > limit) throw TooLarge() + progress(written, total) } } } @@ -113,7 +125,7 @@ internal class StoreArchiveUnpacker( } } - private fun untar(archive: File, codec: String?, handle: DownloadQueue.JobHandle): Unit? { + private fun untar(archive: File, codec: String?, progress: (Long, Long) -> Unit, log: (String) -> Unit): Unit? { val total = archive.length() var written = 0L var entries = 0 @@ -134,7 +146,7 @@ internal class StoreArchiveUnpacker( entries++ val file = target(entry.name) if (file == null) { - handle.log("$label: skipped an entry outside the game folder") + log("$label: skipped an entry outside the game folder") continue } if (entry.isDirectory) { @@ -149,7 +161,8 @@ internal class StoreArchiveUnpacker( if (read < 0) break out.write(buffer, 0, read) written += read - handle.stageProgress(written, total) + if (written > limit) throw TooLarge() + progress(written, total) } } } @@ -163,7 +176,7 @@ internal class StoreArchiveUnpacker( return null } - private fun single(archive: File, codec: String, handle: DownloadQueue.JobHandle) { + private fun single(archive: File, codec: String, progress: (Long, Long) -> Unit, log: (String) -> Unit) { val name = archive.name.substringBeforeLast('.') val file = target(name.ifBlank { "game" }) ?: throw IllegalStateException("archive") file.parentFile?.mkdirs() @@ -184,7 +197,8 @@ internal class StoreArchiveUnpacker( if (read < 0) break out.write(buffer, 0, read) written += read - handle.stageProgress(written, total) + if (written > limit) throw TooLarge() + progress(written, total) } } } @@ -196,7 +210,7 @@ internal class StoreArchiveUnpacker( FileInputStream(source).use { input -> FileOutputStream(target).use { out -> input.copyTo(out, 128 * 1024) } } } - private fun unzip(archive: File, handle: DownloadQueue.JobHandle) { + private fun unzip(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit) { val total = archive.length() var written = 0L val buffer = ByteArray(64 * 1024) @@ -205,7 +219,7 @@ internal class StoreArchiveUnpacker( if (cancelled.get()) return val target = target(entry.name) if (target == null) { - handle.log("$label: skipped an entry outside the game folder") + log("$label: skipped an entry outside the game folder") continue } if (entry.isDirectory) { @@ -221,11 +235,16 @@ internal class StoreArchiveUnpacker( if (read < 0) break out.write(buffer, 0, read) written += read - handle.stageProgress(written, total) + if (written > limit) throw TooLarge() + progress(written, total) } } } } } } + + private companion object { + val LISTED_SIZE = Regex("""^\S+\s+\d+\s+\S+\s+\S+\s+(\d+)\s""") + } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt index f45a23c654..e3b8c7932e 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt @@ -13,6 +13,15 @@ object StoreLaunch { const val EPIC_ARGS = ".droiddeck-epic-args" const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json" private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe" + const val EPIC_PARENT = "Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe" + /** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */ + const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT" + /** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */ + val EPIC_PARENT_TITLES = setOf( + "9d2d0eb64d5c44529cece33fe2a46482", "8769e24080ea413b8ebca3f1b8c50951", "Heather", + "c180bd9859624278aa20f1333918498a", "0828ecd4297c4f89bfcc45420e695b67", + "e5f031908d2e460b8757387d1a136e48", "afd9f29c1af44610b9e0f9b69742e257", + ) const val EA_ENV = ".droiddeck-ea-env" /** A sleeping stand-in that the launch hook installs; older EA SDKs require a running Origin process. */ const val EA_ORIGIN = "C:\\Program Files (x86)\\Origin\\Origin.exe" @@ -39,22 +48,29 @@ object StoreLaunch { val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) } val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "") if (sidecar.store == Store.EPIC) { + lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\"" + lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\"" + lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"0\" set \"$PARENT_VAR=\"" + lines += "if defined $PARENT_VAR set \"SteamAppId=\"" + lines += "if defined $PARENT_VAR if not exist \"$EPIC_PARENT\" set \"$PARENT_VAR=\"" + lines += "if defined $PARENT_VAR set $PARENT_VAR=\"$EPIC_PARENT\"" + val game = "%$PARENT_VAR% $run" lines += "if exist \"%~dp0$EPIC_ARGS\" goto client" lines += "set \"$CODE_VAR=\"" lines += "if exist \"%~dp0$EPIC_CODE\" set /p $CODE_VAR=<\"%~dp0$EPIC_CODE\"" lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\"" lines += "if defined $CODE_VAR goto signed" - lines += run + lines += "$game %*" lines += "goto :eof" lines += ":signed" - lines += "set \"$CODE_VAR=\" & $run -AUTH_LOGIN=unused -AUTH_PASSWORD=%$CODE_VAR% -AUTH_TYPE=exchangecode" + lines += "set \"$CODE_VAR=\" & $game -AUTH_LOGIN=unused -AUTH_PASSWORD=%$CODE_VAR% -AUTH_TYPE=exchangecode %*" lines += "goto :eof" lines += ":client" lines += "set \"$CLIENT_VAR=\"" lines += "set /p $CLIENT_VAR=<\"%~dp0$EPIC_ARGS\"" lines += "del \"%~dp0$EPIC_ARGS\"" lines += "if exist \"%~dp0$EPIC_CODE\" del \"%~dp0$EPIC_CODE\"" - lines += "set \"$CLIENT_VAR=\" & \"%~dp0$exe\" %$CLIENT_VAR%" + lines += "set \"$CLIENT_VAR=\" & %$PARENT_VAR% \"%~dp0$exe\" %$CLIENT_VAR% %*" } else if (sidecar.store == Store.ROCKSTAR) { lines += "if not exist \"C:\\Program Files\\Rockstar Games\\Launcher\\launch.json\" goto direct" lines += "\"C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe\"" @@ -107,6 +123,7 @@ object StoreLaunch { private const val CODE_VAR = "DD_X" private const val CLIENT_VAR = "DD_A" + private const val PARENT_VAR = "DD_P" fun installedGame(context: Context, store: Store, id: String): Library.SteamGame? { val folder = StoreInstallRoot.gameFolders(context).firstOrNull { folder -> diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt index 54571ab172..0efcedbe88 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt @@ -65,6 +65,7 @@ class StoreLoginActivity : ComponentActivity() { val readsPage: Boolean get() = false val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()" fun pageReady(result: String): Boolean = true + fun browserStep(page: String): String? = null fun forgetSignIn(done: () -> Unit) = done() fun pageFinished(view: WebView, url: String) {} } @@ -72,6 +73,7 @@ class StoreLoginActivity : ComponentActivity() { private var store: Store? = null private var clientUrl: String? = null private var flow: Flow? = null + private var pendingBrowserStep: String? = null private var webViewRef: WebView? = null private var popupWebView: WebView? = null private lateinit var contentHost: FrameLayout @@ -211,6 +213,7 @@ class StoreLoginActivity : ComponentActivity() { private fun reloadLogin() { dismissPopup(); clearError() + pendingBrowserStep = null captured.set(false) val fresh = generateState() oauthState = fresh @@ -332,9 +335,13 @@ class StoreLoginActivity : ComponentActivity() { private fun readPage(view: WebView, f: Flow, left: Int) { view.evaluateJavascript(f.pageScript) { json -> + if (flow !== f) return@evaluateJavascript val result = json ?: "" if (!f.pageReady(result) && left > 0) view.postDelayed({ readPage(view, f, left - 1) }, PAGE_RETRY_MS) - else Thread({ settle(f.finish(this, view, result)) }, "store-login").start() + else { + val step = f.browserStep(result) + if (step == null || !continueInBrowser(step)) Thread({ settle(f.finish(this, view, result)) }, "store-login").start() + } } } @@ -350,6 +357,21 @@ class StoreLoginActivity : ComponentActivity() { if (f.readsPage) readPage(view, f, PAGE_TRIES) else Thread({ settle(f.finish(this, view, url)) }, "store-login").start() } + private fun continueInBrowser(url: String): Boolean { + if (isFinishing || isDestroyed) return false + if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) { + pendingBrowserStep = url + return true + } + val opened = runCatching { startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url))) } + .onFailure { Log.w(TAG, "no browser took the sign-in step: ${it.javaClass.simpleName}") } + .isSuccess + if (!opened) return false + titleText.text = getString(R.string.stores_login_title, store?.label ?: "") + showError(getString(R.string.stores_login_continue_in_browser, store?.label ?: "")) + return true + } + private fun settle(problem: String?) { runOnUiThread { if (problem == null) { StoresState.refresh(this); finish(); return@runOnUiThread } @@ -367,6 +389,10 @@ class StoreLoginActivity : ComponentActivity() { override fun onStart() { super.onStart() + pendingBrowserStep?.let { step -> + pendingBrowserStep = null + if (!continueInBrowser(step)) reloadLogin() + } if (clientUrl != null && !isFinishing) com.droiddeck.launcher.session.SessionService.holdForSignIn(this, true) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt index ff804a85e3..f2ee5a26a6 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt @@ -5,8 +5,9 @@ import android.webkit.WebView import com.droiddeck.launcher.R import com.droiddeck.launcher.stores.StoreLoginActivity import org.json.JSONObject +import org.json.JSONTokener -internal class EpicLogin private constructor( +internal class EpicLogin internal constructor( override val startUrl: String, override val userAgent: String, private val redirectPrefix: String, @@ -15,6 +16,12 @@ internal class EpicLogin private constructor( override fun isRedirect(url: String): Boolean = url.startsWith(redirectPrefix) + override fun browserStep(page: String): String? { + val action = correctiveAction(page) ?: return null + Log.i(TAG, "the redirect page asks for a corrective action: $action") + return ACCOUNT_SIGN_IN_URL + } + override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? { val code = EpicNative.call("auth.codeFromPage", JSONObject().put("text", url))?.optString("code", "").orEmpty() if (code.isEmpty()) { @@ -38,6 +45,15 @@ internal class EpicLogin private constructor( companion object { private const val TAG = "EpicLogin" + private const val CORRECTIVE_ACTION_REQUIRED = "errors.com.epicgames.oauth.corrective_action_required" + internal const val ACCOUNT_SIGN_IN_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal" + + internal fun correctiveAction(page: String): String? { + val text = runCatching { JSONTokener(page).nextValue() }.getOrNull() as? String ?: page + val body = runCatching { JSONObject(text.trim()) }.getOrNull() ?: return null + if (body.optString("errorCode") != CORRECTIVE_ACTION_REQUIRED) return null + return body.optJSONObject("metadata")?.optString("correctiveAction").orEmpty().ifEmpty { "unknown" } + } fun create(): StoreLoginActivity.Flow? { val config = EpicNative.call("auth.config") ?: return null diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogContent.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogContent.kt index 8ab48333e7..bd6f7a42f6 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogContent.kt @@ -100,6 +100,7 @@ internal object GogContent { val manifest = metadata(build.link, token) onManifest(manifest) val files = JSONArray() + val overlayPositions = HashMap<String, Int>() val depots = if (build.generation == 1) manifest.optJSONObject("product")?.optJSONArray("depots") ?: manifest.optJSONArray("depot") else manifest.optJSONArray("depots") check(depots != null) { "GOG build has no depot list" } val resolvedLanguage = StoreLanguage.pick(StoreLanguage.codesFromDepots(depots), old.language) @@ -132,10 +133,15 @@ internal object GogContent { val directory = type == "DepotDirectory" || entry.has("directory") val chunks = entry.optJSONArray("chunks") ?: JSONArray() val size = if (build.generation == 2) chunks.objects().sumOf { it.optLong("size") } else entry.optLong("size") - files.put(JSONObject().put("path", path).put("size", size).put("directory", directory) + val file = JSONObject().put("path", path).put("size", size).put("directory", directory) .put("md5", entry.optString("md5").ifBlank { entry.optString("hash") }.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) }.orEmpty()) .put("sha256", entry.optString("sha256")).put("chunks", chunks).put("product", product) - .put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?'))) + .put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?')) + val position = if (build.generation == 2) overlayPositions.putIfAbsent(path, files.length()) else null + if (position == null) files.put(file) else { + require(files.getJSONObject(position).getBoolean("directory") == directory) + files.put(position, file) + } } } check(files.length() > 0) { "GOG build contains no matching files" } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java index a09629bc4c..8864bdaf75 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java @@ -330,7 +330,7 @@ public final class GogDownloadManager { rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList( "/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", guestDir, guestSetup), - false, "gog-innoextract", null, null, false, cancelled, + false, "gog-innoextract", null, null, false, cancelled, null, line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; }); } catch (Exception e) { throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName()); diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt index 85ea9fad69..fab04097d3 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt @@ -103,7 +103,9 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog XboxContent.complete(app, item, folder) return folder.path } - val exe = executable(folder) + val exe = runCatching { executable(folder) }.onFailure { + StoresState.logLine("Xbox: install folder holds ${folder.list().orEmpty().sorted().take(MAX_ERROR_LINES).joinToString()}") + }.getOrThrow() StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe, installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl, extra = item.extra + mapOf("contentId" to selected, "market" to market))) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt index d966dea1e8..b33d1d0d77 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt @@ -21,8 +21,9 @@ internal object XboxManifest { val files = folder.listFiles().orEmpty() val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile } val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile } - require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." } - val manifest = (config + legacy).single() + val manifests = config.ifEmpty { legacy } + require(manifests.size == 1) { "Missing or ambiguous game manifest." } + val manifest = manifests.single() val rootTag = if (config.isEmpty()) "Package" else "Game" require(manifest.length() <= 1_048_576) val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AdbTextField.kt b/app/src/main/java/com/droiddeck/launcher/ui/AdbTextField.kt new file mode 100644 index 0000000000..ad0efcec36 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AdbTextField.kt @@ -0,0 +1,239 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.R +import android.text.Editable +import android.text.InputType +import android.text.TextWatcher +import android.view.inputmethod.EditorInfo +import android.widget.EditText +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.ImeOptions +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.unit.dp +import androidx.compose.ui.viewinterop.AndroidView +import kotlin.math.min +import kotlin.math.roundToInt + +@Composable +internal fun AdbTextField( + value: String, + onValueChange: (String) -> Unit, + label: String, + keyboardType: KeyboardType, + imeAction: ImeAction, + modifier: Modifier = Modifier, + placeholder: String? = null, + compact: Boolean = false, + onFocusChange: (Boolean) -> Unit = {}, + clearFocus: Boolean = false, + onNext: (() -> Unit)? = null, + onDone: (() -> Unit)? = null, + focusOnShow: Boolean = false, + showLabel: Boolean = true, + focusAtTap: Int? = null, + onBack: (() -> Unit)? = null, +) { + val context = LocalContext.current + val onBackLatest = rememberUpdatedState(onBack) + val focusAsked = remember { booleanArrayOf(false) } + val focusTapAsked = remember { arrayOfNulls<Int>(1) } + val palette = LocalPalette.current + val onValueChangeLatest = rememberUpdatedState(onValueChange) + val onNextLatest = rememberUpdatedState(onNext) + val onDoneLatest = rememberUpdatedState(onDone) + val onFocusChangeLatest = rememberUpdatedState(onFocusChange) + var focused by remember { mutableStateOf(false) } + val shape = RoundedCornerShape(8.dp) + val inputHeight = if (compact) 44.dp else 52.dp + val colors = MaterialTheme.colorScheme + val bottomTyping = LocalBottomTyping.current + val bottomTypingLatest = rememberUpdatedState(bottomTyping) + val typingRequest = remember { arrayOfNulls<TypingRequest>(1) } + + fun typeOnBottom(editText: EditText): Boolean { + if (!bottomTypingLatest.value || !DualScreenPanel.attached) return false + val text = editText.text.toString() + lateinit var request: TypingRequest + request = TypingRequest( + TextFieldValue(text, TextRange(editText.selectionStart.coerceIn(0, text.length), editText.selectionEnd.coerceIn(0, text.length))), + ImeOptions(singleLine = true, keyboardType = keyboardType, imeAction = imeAction), + { next -> + if (editText.text.toString() != next.text) editText.setText(next.text) + editText.setSelection(next.selection.start.coerceIn(0, next.text.length), next.selection.end.coerceIn(0, next.text.length)) + }, + { action -> editText.onEditorAction(imeActionFlag(action)) }, + { editText.post { if (typingRequest[0] === request) onBackLatest.value?.invoke() ?: editText.clearFocus() } }, + ) + typingRequest[0] = request + DualScreenPanel.startTyping(request) + return true + } + + DisposableEffect(Unit) { + onDispose { typingRequest[0]?.let { DualScreenPanel.stopTyping(it) } } + } + + Column(modifier = modifier.fillMaxWidth()) { + if (showLabel) Text( + label, + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Medium, + color = colors.onSurfaceVariant, + maxLines = 1, + ) + Box( + modifier = Modifier + .fillMaxWidth() + .height(inputHeight) + .background(colors.surfaceVariant, shape) + .glideBorder(focused, shape, palette.signal, palette.line2) + .padding(horizontal = 10.dp), + contentAlignment = Alignment.CenterStart, + ) { + AndroidView( + modifier = Modifier.fillMaxSize(), + factory = { viewContext -> + EditText(viewContext).apply { + isSingleLine = true + setHorizontallyScrolling(true) + background = null + setPadding((2 * context.resources.displayMetrics.density).roundToInt(), 0, 0, 0) + setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, if (compact) 13f else 14f) + setTextColor(colors.onBackground.toArgb()) + setHintTextColor(colors.onSurfaceVariant.toArgb()) + contentDescription = label + inputType = if (keyboardType == KeyboardType.Number) { + InputType.TYPE_CLASS_NUMBER + } else { + InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS + } + imeOptions = imeActionFlag(imeAction) or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI + hint = placeholder + setOnEditorActionListener { _, actionId, event -> + val isEnter = event?.keyCode == android.view.KeyEvent.KEYCODE_ENTER + when { + imeAction == ImeAction.Next && (actionId == EditorInfo.IME_ACTION_NEXT || isEnter) -> { + onNextLatest.value?.invoke() + true + } + imeAction == ImeAction.Done && (actionId == EditorInfo.IME_ACTION_DONE || isEnter) -> { + onDoneLatest.value?.invoke() + true + } + // Search and Go are terminal: leaving them unhandled + // keeps focus in the field, so the keyboard would stay + // up over the results it was used to find. + imeAction in setOf(ImeAction.Search, ImeAction.Go) && + (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || isEnter) -> { + onDoneLatest.value?.invoke() + post { + clearFocus() + (context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) + as? android.view.inputmethod.InputMethodManager) + ?.hideSoftInputFromWindow(windowToken, 0) + } + true + } + else -> false + } + } + showSoftInputOnFocus = !bottomTyping + // B on a controller puts the keyboard away first; with no keyboard up it goes back as usual. + var hidingKeyboard = false + setOnKeyListener { view, keyCode, event -> + if (keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return@setOnKeyListener false + if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) { + hidingKeyboard = androidx.core.view.ViewCompat.getRootWindowInsets(view) + ?.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()) == true + if (hidingKeyboard) (view.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) + ?.hideSoftInputFromWindow(view.windowToken, 0) + onBackLatest.value?.let { hidingKeyboard = true; it() } + } + hidingKeyboard + } + setOnClickListener { if (hasFocus() && !typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) } + setOnFocusChangeListener { _, hasFocus -> + focused = hasFocus + if (hasFocus) { if (!typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) } + else typingRequest[0]?.let { DualScreenPanel.stopTyping(it) } + onFocusChangeLatest.value(hasFocus) + } + addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit + override fun afterTextChanged(s: Editable?) { + onValueChangeLatest.value(s?.toString().orEmpty()) + } + }) + } + }, + update = { editText -> + editText.showSoftInputOnFocus = !bottomTyping + // A new tap may ask again: a field still on screen while it closes can be opened once more. + val fresh = if (focusAtTap != null) focusTapAsked[0] != focusAtTap else !focusAsked[0] + if (focusOnShow && fresh) { + if (focusAtTap != null) focusTapAsked[0] = focusAtTap else focusAsked[0] = true + editText.post { + if (focusAtTap != null && focusAtTap != ScreenTaps.count) return@post + editText.requestFocus() + if (!bottomTypingLatest.value) (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) + ?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT) + } + } + if (clearFocus && editText.hasFocus()) { + editText.clearFocus() + (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) + ?.hideSoftInputFromWindow(editText.windowToken, 0) + } + editText.setTextColor(colors.onBackground.toArgb()) + editText.setHintTextColor(colors.onSurfaceVariant.toArgb()) + editText.hint = placeholder + editText.contentDescription = label + if (editText.text.toString() != value) { + val cursor = if (editText.hasFocus()) editText.selectionStart.coerceAtLeast(0) else value.length + editText.setText(value) + editText.setSelection(min(cursor, value.length)) + } + }, + ) + } + } +} + + +private fun showKeyboardHere(editText: EditText) { + (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) + ?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT) +} + +private fun imeActionFlag(action: ImeAction): Int = when (action) { + ImeAction.Next -> EditorInfo.IME_ACTION_NEXT + ImeAction.Done -> EditorInfo.IME_ACTION_DONE + ImeAction.Go -> EditorInfo.IME_ACTION_GO + ImeAction.Search -> EditorInfo.IME_ACTION_SEARCH + else -> EditorInfo.IME_ACTION_UNSPECIFIED +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt index 3acc241b17..df8bc0ed89 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt @@ -311,6 +311,7 @@ internal fun AppDialog( width: Dp? = null, fitContent: Boolean = false, back: (() -> Unit)? = null, scrollable: Boolean = true, + fillHeight: Boolean = false, scrollState: androidx.compose.foundation.ScrollState = rememberScrollState(), side: (@Composable () -> Unit)? = null, sideRoom: Dp = 0.dp, @@ -348,6 +349,7 @@ internal fun AppDialog( }, ) .heightIn(max = (LocalConfiguration.current.screenHeightDp - 24).dp) + .then(if (fillHeight) Modifier.fillMaxHeight() else Modifier) .shadow(24.dp, Shape16, ambientColor = Color.Black, spotColor = Color.Black) .clip(Shape16) .background(pal.surfaceVariant.copy(alpha = 0.97f)) @@ -358,7 +360,7 @@ internal fun AppDialog( .then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier) .padding(horizontal = 18.dp, vertical = 16.dp), ) { - content() + androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content() } if (side != null && !beside) side() } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index 89e84fe697..052241a8b9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -1,29 +1,33 @@ package com.droiddeck.launcher.ui import android.content.Context -import android.content.Intent -import android.net.Uri import android.widget.Toast -import androidx.compose.foundation.LocalIndication -import androidx.compose.foundation.clickable -import androidx.compose.foundation.hoverable +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan +import androidx.compose.foundation.lazy.grid.LazyGridState import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Check -import androidx.compose.material3.Icon +import androidx.compose.foundation.lazy.grid.rememberLazyGridState +import androidx.compose.foundation.rememberScrollState import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf @@ -33,26 +37,53 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.withFrameNanos import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip -import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.InputMode +import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import coil.compose.AsyncImage import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.AddedGames +import com.droiddeck.launcher.runtime.CurseForgeApp +import com.droiddeck.launcher.runtime.UserApps import com.droiddeck.launcher.runtime.WowAddonCatalog import com.droiddeck.launcher.runtime.WowAddons import com.droiddeck.launcher.session.SessionState +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File +import java.io.IOException +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference private class AddonResults { val items = mutableStateListOf<WowAddonCatalog.Addon>() @@ -62,8 +93,178 @@ private class AddonResults { var more by mutableStateOf(false) } +internal enum class AddonStatus { INSTALL, UPDATE, INSTALLED } + +private enum class AddonSource { WOWI, CURSE } + +internal class CurseState(val notice: Int? = null) : Exception() + +internal class CurseLink(val app: UserApps.App) { + class Linked(val inspector: String, val guid: String) + + private val lock = Object() + private val work = SupervisorJob() + @Volatile private var closed = false + @Volatile private var hold: AtomicBoolean? = null + @Volatile private var inspector: String? = null + private val guids = HashMap<String, String>() + private val scanLock = Object() + private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>() + private val settleLock = Object() + private val settled = HashMap<String, Pair<Int, List<CurseForgeApp.Project>>>() + private val turns = HashMap<String, Int>() + var generation by mutableIntStateOf(0) + private set + + fun refresh() { + generation++ + } + + fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk( + synchronized(scanLock) { + scans[target.addOns.path]?.takeIf { it.first == key }?.second + ?: (settledFor(target) ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }).also { + scans[target.addOns.path] = key to it + report(target, it) + } + }, + target.addOns, + ) + + fun marks(context: Context, target: WowAddons.Target, key: Any): Map<String, String?> = + runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) } + + private fun settledFor(target: WowAddons.Target): List<CurseForgeApp.Project>? = synchronized(settleLock) { + settled.remove(target.addOns.path)?.takeIf { it.first == generation }?.second + } + + fun change(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> List<CurseForgeApp.Project>?): Boolean { + val path = target.addOns.path + val turn = synchronized(settleLock) { + settled.remove(path) + ((turns[path] ?: 0) + 1).also { turns[path] = it } + } + val projects = call(context, target, launch, block) ?: return false + synchronized(settleLock) { + if (turns[path] == turn) { + settled[path] = generation to projects + report(target, projects) + } + } + return true + } + + fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T { + val linked = synchronized(lock) { link(context, target, launch) } + try { + return block(linked) + } catch (e: CurseForgeApp.Failure) { + if (e.gone) synchronized(lock) { + if (inspector == linked.inspector) { + inspector = null + guids.clear() + current.compareAndSet(this, null) + } + } + throw e + } + } + + private fun link(context: Context, target: WowAddons.Target, launch: Boolean): Linked { + if (closed) throw CurseState() + val url = inspector ?: run { + if (!launch) throw CurseState() + val hold = AtomicBoolean(false) + this.hold = hold + if (closed) throw CurseState() + val done = CurseForgeApp.start(context, app, hold) + when (done.state) { + CurseForgeApp.Start.READY -> { + inspector = done.inspector + if (!closed) current.set(this) + done.inspector ?: throw CurseState() + } + CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy) + else -> throw CurseState() + } + } + if (closed) throw CurseState() + guids[target.addOns.path]?.let { return Linked(url, it) } + val root = WowAddons.root(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState() + val flavor = WowAddons.flavorDir(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState() + val guid = CurseForgeApp.instance(context, url, root, flavor) + guids[target.addOns.path] = guid + return Linked(url, guid) + } + + fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = change(context, target, launch = false) { linked -> + val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns) + CurseForgeApp.owner(projects, folder)?.let { CurseForgeApp.uninstall(context, linked.inspector, linked.guid, it) ?: throw CurseState() } + } + + internal val stopped: Job get() = work + + fun close(context: Context): Job { + closed = true + current.compareAndSet(this, null) + val launch = hold + return CoroutineScope(work + Dispatchers.IO).launch { + if (launch != null) CurseForgeApp.stop(context, app, inspector, launch) + synchronized(lock) { + hold = null + inspector = null + } + }.also { work.complete() } + } + + companion object { + private val current = AtomicReference<CurseLink?>() + private val reported = ConcurrentHashMap<String, List<CurseForgeApp.Project>>() + + fun lastReported(target: WowAddons.Target, disk: () -> List<WowAddons.Installed> = { WowAddons.details(target) }): Map<String, String?> { + val last = reported[target.addOns.path] ?: return disk().mapNotNull { it.curseId }.associateWith { null } + return CurseForgeApp.onDisk(last, target.addOns).associate { it.id to null } + } + + internal fun report(target: WowAddons.Target, projects: List<CurseForgeApp.Project>) { + reported[target.addOns.path] = projects + } + + fun live(): CurseLink? = current.get() + } +} + +private const val PAGES_AHEAD = 8 +private const val CURSE_UPDATE = "update" +private const val UNINSTALLING = -1 + +private fun curseMark(project: CurseForgeApp.Project): String? = CURSE_UPDATE.takeIf { project.update } + +private class Present(val curse: Map<String, String?> = emptyMap(), val disk: Map<String, WowAddons.Installed> = emptyMap()) + @Composable -internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, onDismiss: () -> Unit) { +internal fun rememberCurseLink(app: UserApps.App?, sessionRunning: Boolean): CurseLink? { + val context = LocalContext.current.applicationContext + val owner = LocalLifecycleOwner.current + var visible by remember(owner) { mutableStateOf(owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) } + DisposableEffect(owner) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_START) visible = true + if (event == Lifecycle.Event.ON_STOP) visible = false + } + owner.lifecycle.addObserver(observer) + onDispose { owner.lifecycle.removeObserver(observer) } + } + val active = visible && !sessionRunning + val link = remember(app?.key, active) { app?.takeIf { active }?.let(::CurseLink) } + DisposableEffect(link) { + onDispose { link?.close(context) } + } + return link +} + +@Composable +internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, link: CurseLink?, onDismiss: () -> Unit) { val context = LocalContext.current.applicationContext val scope = rememberCoroutineScope() val shown = rememberShown(onDismiss) @@ -72,12 +273,34 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd var text by remember { mutableStateOf("") } var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) } var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) } - val results = remember(text, category, sort, target) { AddonResults() } + var source by remember { mutableStateOf(AddonSource.WOWI) } + val curse = if (source == AddonSource.CURSE && link != null) curseForge else null + LaunchedEffect(link) { link?.refresh() } + var notice by remember { mutableStateOf<Int?>(null) } + var curseInstalls by remember { mutableIntStateOf(0) } + val results = remember(text, category, sort, target, curse) { AddonResults() } val installing = remember { mutableStateMapOf<String, Int>() } - val installed = remember { mutableStateMapOf<String, Boolean>() } + val installed = remember { mutableStateMapOf<String, Pair<String, String>>() } val categories by produceState(emptyList<WowAddonCatalog.Category>()) { value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) } } + val presentKey = curse to target.addOns + val scanKey = link?.generation to WowAddons.imports + val snapshot by produceState(presentKey to Present(), target.addOns, scanKey, curse, curseInstalls, curse == null && results.items.isEmpty()) { + val into = target + val key = curse to into.addOns + if (curse != null && link != null && value.first != key) value = key to withContext(Dispatchers.IO) { Present(curse = CurseLink.lastReported(into)) } + value = key to withContext(Dispatchers.IO) { + if (curse != null && link != null) Present(curse = link.marks(context, into, scanKey)) + else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() }) + } + } + val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: Present() + fun status(addon: WowAddonCatalog.Addon): AddonStatus { + if (curse != null) return if (addon.id !in present.curse) AddonStatus.INSTALL else if (present.curse[addon.id] == CURSE_UPDATE) AddonStatus.UPDATE else AddonStatus.INSTALLED + val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary + return diskStatus(addon.folders, present.disk, latest, addon.id) + } fun load(page: Int) { if (results.loading) return results.loading = true @@ -86,10 +309,16 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd val words = text val cat = category?.id val order = sort + val via = link?.takeIf { curse != null } + notice = null scope.launch { val got = withContext(Dispatchers.IO) { - runCatching { WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page) } + runCatching { + if (via != null) via.call(context, into) { CurseForgeApp.search(context, it.inspector, it.guid, words, order, page) } + else WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page) + } } + if (results.items.isEmpty()) notice = (got.exceptionOrNull() as? CurseState)?.notice got.onSuccess { if (page == 0) results.items.clear() results.items.addAll(it.items.filter { addon -> results.items.none { seen -> seen.id == addon.id } }) @@ -106,6 +335,34 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd fun install(addon: WowAddonCatalog.Addon) { val key = installKey(addon, target) if (key in installing) return + val via = link?.takeIf { curse != null } + if (via != null) { + val into = target + val updating = status(addon) == AddonStatus.UPDATE + installing[key] = 0 + scope.launch { + val done = withContext(Dispatchers.IO) { + runCatching { + via.change(context, into) { + if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id) + else CurseForgeApp.install(context, it.inspector, it.guid, addon.id) + } + } + } + installing.remove(key) + val ok = done.getOrNull() == true + WowAddons.changed() + curseInstalls++ + val message = when { + ok && updating -> context.getString(R.string.user_apps_updated, addon.name) + ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor) + else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString) + ?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name) + } + Toast.makeText(context, message, Toast.LENGTH_LONG).show() + } + return + } if (SessionState.running) { Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show() return @@ -115,48 +372,131 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd scope.launch { val message = withContext(Dispatchers.IO) { installAddon(context, addon, into) { pct -> scope.launch { if (key in installing) installing[key] = pct } } } installing.remove(key) - if (message.second) installed[key] = true + message.second?.let { installed[key] = addon.summary to it } Toast.makeText(context, message.first, Toast.LENGTH_LONG).show() } } - val sourceName = stringResource(R.string.addons_source_wowi) - AppDialog(shown, close, "addonBrowser", wide = true, scrollable = false) { - DialogTitleRow(stringResource(R.string.addons_download), close) - ModeHeader(sourceName, text, { text = it }, stringResource(R.string.stores_search_catalog, sourceName)) { - BrowseChip(stringResource(R.string.addons_source_curse), false) { - runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(WowAddonCatalog.curseForgeUrl(text))).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } - } + fun uninstall(addon: WowAddonCatalog.Addon) { + val key = installKey(addon, target) + if (key in installing) return + if (SessionState.running) { + Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show() + return } - ChipRow { + val into = target + val via = link?.takeIf { curse != null } + installing[key] = UNINSTALLING + scope.launch { + val done = withContext(Dispatchers.IO) { + runCatching { + val folders = if (via != null) curseFolders(into, addon.id, via.call(context, into) { linked -> + CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty() + }) else addon.folders + deleteAddons(context, into, folders, link) + } + } + installing.remove(key) + installed.remove(key) + WowAddons.changed() + curseInstalls++ + if (done.isFailure) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_LONG).show() + } + } + val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi) + val grid = rememberLazyGridState() + LaunchedEffect(results, grid) { + snapshotFlow { grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index to grid.layoutInfo.totalItemsCount }.collect { (last, total) -> + if (last != null && results.more && results.failed == null && last >= total - PAGES_AHEAD) load(results.page + 1) + } + } + val firstAction = remember(results) { FocusRequester() } + val inputMode = LocalInputModeManager.current + var searching by remember { mutableStateOf(false) } + LaunchedEffect(results, results.items.isNotEmpty()) { + if (results.items.isNotEmpty() && !searching && inputMode.inputMode == InputMode.Keyboard) focusSoon { firstAction } + } + AppDialog(shown, close, "addonBrowser", wide = true, maxWidth = 980.dp, scrollable = false, fillHeight = true, modifier = Modifier.releaseTextFieldOnTap()) { + val sortChip: @Composable () -> Unit = { BrowseDropdown(sortLabel(sort)) { first, done -> WowAddonCatalog.Sort.entries.forEachIndexed { index, option -> MenuItem(sortLabel(option), sort == option, focusRequester = if (index == 0) first else null) { sort = option; done() } } } - if (categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done -> + } + val sourceChip: @Composable () -> Unit = { + if (curseForge != null) BrowseDropdown(sourceName) { first, done -> + MenuItem(stringResource(R.string.addons_source_wowi), source == AddonSource.WOWI, focusRequester = first) { source = AddonSource.WOWI; done() } + MenuItem(stringResource(R.string.addons_source_curse), source == AddonSource.CURSE) { source = AddonSource.CURSE; done() } + } + } + val categoryChip: @Composable () -> Unit = { + if (curse == null && categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done -> MenuItem(stringResource(R.string.addons_category_all), category == null, focusRequester = first) { category = null; done() } categories.forEach { option -> MenuItem(option.name, category?.id == option.id) { category = option; done() } } } + } + val flavorChip: @Composable () -> Unit = { if (targets.size > 1) BrowseDropdown(target.flavor) { first, done -> targets.forEachIndexed { index, option -> MenuItem(option.flavor, option.addOns == target.addOns, focusRequester = if (index == 0) first else null) { target = option; done() } } } } - val height = (LocalConfiguration.current.screenHeightDp * 0.62f).dp + val search: @Composable (Modifier) -> Unit = { modifier -> + AdbTextField( + value = text, onValueChange = { text = it }, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, + placeholder = stringResource(R.string.stores_search_catalog, sourceName), compact = true, showLabel = false, modifier = modifier, onFocusChange = { searching = it }, + ) + } + val closeButton: @Composable () -> Unit = { + SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.error, onClick = close) + } + BoxWithConstraints(Modifier.fillMaxWidth()) { + if (maxWidth >= 640.dp) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + search(Modifier.weight(1f)) + sourceChip() + sortChip() + categoryChip() + flavorChip() + closeButton() + } else Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + search(Modifier.weight(1f)) + closeButton() + } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.horizontalScroll(rememberScrollState()), + ) { + sourceChip() + sortChip() + categoryChip() + flavorChip() + } + } + } + val thumb = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) LazyVerticalGrid( - GridCells.Adaptive(libraryTileWidth() + 40.dp), Modifier.fillMaxWidth().height(height), - horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp), + GridCells.Adaptive(400.dp), Modifier.fillMaxWidth().weight(1f).scrollThumb(grid, thumb), state = grid, + contentPadding = PaddingValues(end = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { items(results.items, key = { it.id }) { addon -> - AddonCard(addon, installing[installKey(addon, target)], installed[installKey(addon, target)] == true) { install(addon) } + val key = installKey(addon, target) + AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier, { uninstall(addon) }) { install(addon) } } - item(key = "tail", span = { GridItemSpan(maxLineSpan) }) { - Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) { + item(span = { GridItemSpan(maxLineSpan) }) { + Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { when { results.loading -> LinearProgressIndicator(Modifier.fillMaxWidth()) - results.failed != null -> BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) } - results.more -> BrowseChip(stringResource(R.string.stores_itch_load_more), false) { load(results.page + 1) } + results.failed != null && notice != null -> { + Text(stringResource(notice!!), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(0) } + } + results.failed != null -> { + Text(stringResource(R.string.addons_unreachable, sourceName), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) } + } results.items.isEmpty() -> Text(stringResource(R.string.addons_none_found), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) } } @@ -166,27 +506,69 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd } @Composable -private fun AddonCard(addon: WowAddonCatalog.Addon, progress: Int?, done: Boolean, onInstall: () -> Unit) { - val pal = LocalPalette.current - val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() } - val hot = rememberHot(src) - val shape = androidx.compose.foundation.shape.RoundedCornerShape(10.dp) - Column( - Modifier.fillMaxWidth().clip(shape).glideBorder(hot, shape, pal.signal, pal.line) - .hoverable(src) - .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onInstall) - .controllerConfirm(onClick = onInstall), - ) { - ArtCard(addon.name, addon.thumb, null, null, hot, capsule = false, chip = progress?.let { "$it%" }) { - if (done) Icon(Icons.Filled.Check, stringResource(R.string.stores_installed_chip), tint = pal.good, modifier = Modifier.height(11.dp)) - else Text(stringResource(if (progress != null) R.string.store_installing else R.string.store_install), fontSize = 10.sp, color = pal.signal, maxLines = 1) - } - Text( - listOf(addon.author, formatCount(addon.downloads)).filter { it.isNotEmpty() }.joinToString(" · "), - fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp), - ) +internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onUninstall: () -> Unit, onInstall: () -> Unit) { + var asking by remember(addon.id) { mutableStateOf(false) } + val first = remember(addon.id) { FocusRequester() } + var refocus by remember(addon.id) { mutableStateOf(false) } + val inputMode = LocalInputModeManager.current + LaunchedEffect(status, progress) { + if (!refocus) return@LaunchedEffect + withFrameNanos { } + runCatching { first.requestFocus() } + if (progress == null) refocus = false } + fun act(block: () -> Unit) { + refocus = inputMode.inputMode == InputMode.Keyboard + block() + } + val lead = action.focusRequester(first) + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface.copy(alpha = 0.6f)).border(1.dp, pal.line, Shape12) + .padding(start = 8.dp, end = 8.dp, top = 6.dp, bottom = 6.dp), + ) { + Box(Modifier.size(44.dp).clip(Shape12).background(artBrush(hueOf(addon.name)))) { + if (addon.thumb != null) AsyncImage(model = addon.thumb, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize()) + } + Column(Modifier.weight(1f)) { + Text(addon.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + listOf(addon.author, addon.summary, formatCount(addon.downloads)).filter { it.isNotEmpty() }.joinToString(" · "), + fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } + val uninstall = stringResource(R.string.common_uninstall) + when { + progress == UNINSTALLING -> SecondaryButton(stringResource(R.string.stores_uninstalling), compact = true, modifier = lead) {} + progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = lead, progress = progress / 100f, onClick = onInstall) + status == AddonStatus.INSTALL -> PrimaryButton(stringResource(R.string.store_install), compact = true, modifier = lead) { act(onInstall) } + else -> { + if (status == AddonStatus.UPDATE) PrimaryButton(stringResource(R.string.common_update), compact = true, modifier = lead) { act(onInstall) } + SecondaryButton(uninstall, compact = true, modifier = if (status == AddonStatus.UPDATE) Modifier else lead) { asking = true } + } + } + } + if (asking) ConfirmDialog( + title = stringResource(R.string.stores_uninstall_title, addon.name), + text = stringResource(R.string.games_delete_addon_body), + confirm = stringResource(R.string.common_uninstall), + onConfirm = { asking = false; act(onUninstall) }, + onDismiss = { asking = false }, + ) +} + +private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent { + drawContent() + val info = state.layoutInfo + val visible = info.visibleItemsInfo + if (visible.isEmpty() || visible.size >= info.totalItemsCount) return@drawWithContent + val total = info.totalItemsCount.toFloat() + val length = (size.height * visible.size / total).coerceAtLeast(24.dp.toPx()) + val top = (size.height - length) * (visible.first().index / (total - visible.size).coerceAtLeast(1f)).coerceIn(0f, 1f) + val width = 3.dp.toPx() + drawRoundRect(color, Offset(size.width - width, top), Size(width, length), CornerRadius(width / 2)) } @Composable @@ -206,21 +588,42 @@ private fun formatCount(count: Long): String = when { else -> count.toString() } -private fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target: WowAddons.Target, progress: (Int) -> Unit): Pair<String, Boolean> { +internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target: WowAddons.Target, progress: (Int) -> Unit): Pair<String, String?> { val zip = File(File(context.cacheDir, "wowaddons"), "download-wowi-${addon.id.filter(Char::isLetterOrDigit)}-${java.util.UUID.randomUUID()}.zip") return try { - WowAddonCatalog.download(context, addon, zip, progress) - if (SessionState.running) return context.getString(R.string.main_addons_close_session) to false - val names = WowAddons.import(zip, target) - if (names.isEmpty()) context.getString(R.string.main_addons_none, addon.name) to false - else context.resources.getQuantityString(R.plurals.main_addons_imported, names.size, names.size, target.flavor) to true + val version = WowAddonCatalog.download(context, addon, zip, progress) ?: addon.summary + if (SessionState.running) return context.getString(R.string.main_addons_close_session) to null + val names = WowAddons.import(zip, target, WowAddons.Origin(addon.id, version).takeIf { version.isNotBlank() }, context) + if (names.isEmpty()) context.getString(R.string.main_addons_none, addon.name) to null + else context.resources.getQuantityString(R.plurals.main_addons_imported, names.size, names.size, target.flavor) to version } catch (_: WowAddons.TooLarge) { - context.getString(R.string.main_addons_too_large, addon.name) to false + context.getString(R.string.main_addons_too_large, addon.name) to null } catch (e: Exception) { - context.getString(R.string.stores_dl_failed_reason, e.message ?: e.javaClass.simpleName) to false + context.getString(R.string.stores_dl_failed_reason, e.message ?: e.javaClass.simpleName) to null } finally { zip.delete() } } +internal fun diskStatus(folders: List<String>, onDisk: Map<String, WowAddons.Installed>, latest: String, id: String): AddonStatus { + if (!WowAddons.present(folders) { it.lowercase() in onDisk }) return AddonStatus.INSTALL + val have = onDisk.getValue(folders.first().lowercase()) + return if (WowAddonCatalog.offersUpdate(have.version, latest, sameSource = have.wowiId == id)) AddonStatus.UPDATE else AddonStatus.INSTALLED +} + +internal fun curseFolders(target: WowAddons.Target, id: String, listed: List<String>): List<String> = + listed.ifEmpty { WowAddons.details(target).filter { it.curseId == id }.map { it.name } } + +internal fun deleteAddons(context: Context, target: WowAddons.Target, folders: List<String>, link: CurseLink?) { + val found = folders.mapNotNull { WowAddons.folder(target.addOns, it) } + if (found.isEmpty()) throw IOException("No addon folder to delete") + found.forEach { deleteAddon(context, target, it.name, link) } +} + +internal fun deleteAddon(context: Context, target: WowAddons.Target, folder: String, link: CurseLink? = CurseLink.live()) { + val managed = link?.let { runCatching { it.uninstall(context, target, folder) }.getOrDefault(false) } == true + val left = WowAddons.folder(target.addOns, folder) + if (managed || left == null) WowAddons.changed() else WowAddons.delete(target, left.name) +} + private fun installKey(addon: WowAddonCatalog.Addon, target: WowAddons.Target) = addon.id + "|" + target.addOns.path diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index 225b81444a..429db30258 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.ui import android.app.Activity import android.content.ContextWrapper +import android.os.Build import android.view.KeyEvent import android.view.WindowManager import androidx.activity.compose.LocalActivityResultRegistryOwner @@ -10,6 +11,7 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.shrinkHorizontally +import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.expandHorizontally import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically @@ -184,7 +186,11 @@ private fun AgentPageContent( ?: generateSequence(view.context) { (it as? ContextWrapper)?.baseContext } .filterIsInstance<Activity>().firstOrNull()?.window val previousMode = window?.attributes?.softInputMode + // A window fitted to the system bars with ADJUST_NOTHING reports no keyboard height to Compose. + // It stays unfitted after the page leaves: fitting it again insets the other pages twice. + val edgeToEdge = visible && hidesPet && !drawer && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R if (visible) window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING) + if (edgeToEdge) window?.setDecorFitsSystemWindows(false) onDispose { if (visible && previousMode != null) window?.setSoftInputMode(previousMode) } @@ -223,8 +229,14 @@ private fun AgentPageContent( } val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) } val inlineControls: (@Composable () -> Unit)? = if (inline) ({ - ModelChip(panel, togglePanel, inputModifier, compact = true) - ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) }) + // The open menu needs the row's width for its own buttons. + androidx.compose.animation.AnimatedVisibility(!menuOpen, enter = expandHorizontally(expandFrom = Alignment.Start) + fadeIn(), + exit = shrinkHorizontally(shrinkTowards = Alignment.Start) + fadeOut()) { + Row(verticalAlignment = Alignment.CenterVertically) { + ModelChip(panel, togglePanel, inputModifier, compact = true) + ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) }) + } + } menu() }) else null // A host with a title bar shows the top bar there. @@ -240,8 +252,11 @@ private fun AgentPageContent( LaunchedEffect(AgentHost.approvals.size, panel) { if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE } + androidx.compose.foundation.layout.BoxWithConstraints(modifier.fillMaxSize()) { + // On a short page the picker would take it all and leave no conversation, so it scrolls within a share of the page. + val panelMax = maxHeight * 0.5f Column( - modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e -> + Modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e -> val k = e.nativeKeyEvent if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false if (k.action == KeyEvent.ACTION_UP) composer.open() @@ -264,8 +279,8 @@ private fun AgentPageContent( else -> { if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() } when (panel) { - AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() } - AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() } + AgentPanel.MODEL -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentModelPicker() } + AgentPanel.USAGE -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentUsage() } else -> Unit } val list = rememberLazyListState() @@ -317,11 +332,12 @@ private fun AgentPageContent( } } androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { - AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest) + AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest, hideAttach = inline && menuOpen) } } } } + } } /** Whether the editor has the cursor; [open] puts it there. */ @@ -392,10 +408,12 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val working = AgentHost.state == AgentHost.State.WORKING + // Closed, the outline sits flush against the lone button. + val shape = if (open) Shape16 else Shape12 Row( verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.clip(Shape16).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f)) - .border(1.dp, pal.line, Shape16).padding(end = 2.dp), + modifier = Modifier.clip(shape).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f)) + .border(1.dp, pal.line, shape).then(if (open) Modifier.padding(top = 3.dp, bottom = 3.dp, end = 4.dp) else Modifier), ) { androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(), exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) { @@ -418,7 +436,7 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP } } } - HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu") { onOpen(!open) } + HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu", startPadding = if (open) null else 0.dp) { onOpen(!open) } } } @@ -432,12 +450,13 @@ private fun AgentPanelBar(title: String, onClose: () -> Unit) { @Composable internal fun HeaderAction( - icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, onClick: () -> Unit, + icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, + startPadding: Dp? = null, onClick: () -> Unit, ) { val pal = LocalPalette.current Box( contentAlignment = Alignment.Center, - modifier = Modifier.padding(start = if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12) + modifier = Modifier.padding(start = startPadding ?: if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12) .background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant) .clickable(enabled = enabled, onClick = onClick) .then(if (tag != null) Modifier.testTag(tag) else Modifier), @@ -710,7 +729,7 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit. @Composable private fun AgentComposer( composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, - onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, + onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, hideAttach: Boolean = false, ) { val context = LocalContext.current var draft by draftState @@ -742,13 +761,13 @@ private fun AgentComposer( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), ) { AgentActivity(labOpen) { labOpen = !labOpen } } - AgentEditor(composer, draftState, visible, controls, send) + AgentEditor(composer, draftState, visible, controls, send, hideAttach) } } /** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */ @Composable -private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit) { +private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit, hideAttach: Boolean = false) { val context = LocalContext.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -847,14 +866,14 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String if (stacked) Column { text(Modifier.fillMaxWidth()) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { - if (attach) AttachButton() - if (AgentAttachments.gameFrame != null) GameFrameButton() - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp)) { if (controls != null && !focused) controls() } + AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() } + AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() } + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() } actions() } } else Row(verticalAlignment = Alignment.Bottom) { - if (attach) AttachButton() - if (AgentAttachments.gameFrame != null) GameFrameButton() + AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() } + AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() } text(Modifier.weight(1f)) if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() } actions() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt index 8904f2c2d4..4d4ac7adc0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt @@ -117,6 +117,7 @@ import com.droiddeck.launcher.IconPack import android.content.pm.ShortcutInfo import android.graphics.Bitmap import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.drop import kotlinx.coroutines.withContext import com.droiddeck.launcher.HomeWidgets @@ -388,21 +389,49 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod } val front = LocalFrontFocus.current val steer = rememberCoroutineScope() - // Down goes to the tile straight below. The grid's own search only sees the tiles laid out so far, so above a short or + // The tile a move is heading to, by its id so that a list update cannot shift it, and the number of the latest move. + val aim = remember { arrayOfNulls<String>(1) } + val moves = remember { intArrayOf(0) } + val move = remember { arrayOfNulls<Job>(1) } + // Up and Down go to the tile straight above or below. The grid's own search works from where the tiles are drawn at that + // moment, so while a scroll is still catching up with fast presses it skips a row or drifts a column, and above a short or // unseen last row it lands on a tile further left; above a gap in a short last row the row's last tile takes it. + // Presses aim from the tile a move is already heading to, so none is lost before the focus lands. Box(Modifier.weight(1f).fillMaxWidth().onPreviewKeyEvent { event -> val k = event.nativeKeyEvent - if (k.keyCode != KeyEvent.KEYCODE_DPAD_DOWN || front == null) return@onPreviewKeyEvent false - val from = entries.indexOfFirst { tileId(it) == front.last } + val down = k.keyCode == KeyEvent.KEYCODE_DPAD_DOWN + if ((!down && k.keyCode != KeyEvent.KEYCODE_DPAD_UP) || front == null) return@onPreviewKeyEvent false + val aimed = aim[0]?.let { id -> entries.indexOfFirst { tileId(it) == id } } ?: -1 + if (aim[0] != null && aimed < 0) { + // The tile a move was heading to has left the list: that move is dropped and the press aims from the focus. + move[0]?.cancel() + aim[0] = null + } + val from = aimed.takeIf { it >= 0 } ?: entries.indexOfFirst { tileId(it) == front.last } val columns = (grid.layoutInfo.visibleItemsInfo.maxOfOrNull { it.column } ?: 0) + 1 - if (from < 0 || from / columns == entries.lastIndex / columns) return@onPreviewKeyEvent false + if (from < 0) return@onPreviewKeyEvent false + // At the first or last row the press leaves the grid, unless a move has not landed yet: then it waits for it. + val edge = if (down) from / columns == entries.lastIndex / columns else from < columns + if (edge) return@onPreviewKeyEvent aim[0] != null if (k.action == KeyEvent.ACTION_DOWN) { - val id = tileId(entries[minOf(from + columns, entries.lastIndex)]) - val shown = (front.attached[id] ?: 0) > 0 - if (!shown || runCatching { front.items.getValue(id).requestFocus() }.isFailure) steer.launch { - // The row below is not laid out yet: bring it in, then take it. - if (!shown) grid.scrollBy((grid.layoutInfo.visibleItemsInfo.firstOrNull { it.index == from + leadItems }?.size?.height ?: 0).toFloat()) - focusSoon { front.items.getValue(id) } + val to = if (down) minOf(from + columns, entries.lastIndex) else from - columns + val id = tileId(entries[to]) + aim[0] = id + val mine = ++moves[0] + // A newer move replaces the one still on its way, so an older target cannot take focus after it lands. + move[0]?.cancel() + move[0] = steer.launch { + try { + // Show the row before it takes focus. The grid composes rows ahead of the view without placing them, and a + // tile focused there neither scrolls in nor has a place for the next search to start from. + grid.reveal(to + leadItems) + if (moves[0] != mine) return@launch + focusSoon { front.items.getValue(id) } + } finally { + // Also when a touch scroll cancels the reveal, so the edge rows do not keep waiting for a move that ended. + // Only the latest move clears it: a cancelled one finishing late must not clear a newer move's target. + if (moves[0] == mine) aim[0] = null + } } } true @@ -558,6 +587,26 @@ private fun HeaderChoiceButton( } } +/** Scrolls the least that shows item [index] whole inside the padding, a row at a time while it is still outside the laid out items. */ +private suspend fun LazyGridState.reveal(index: Int) { + repeat(4) { + val info = layoutInfo + val shown = info.visibleItemsInfo + val item = shown.firstOrNull { it.index == index } + val by = when { + item != null -> { + val bottom = item.offset.y + item.size.height - (info.viewportEndOffset - info.afterContentPadding) + if (item.offset.y < 0) item.offset.y else maxOf(bottom, 0) + } + index > (shown.lastOrNull() ?: return).index -> shown.last().size.height + index < shown.first().index -> -shown.first().size.height + else -> return + } + if (by == 0) return + scrollBy(by.toFloat()) + } +} + @Composable private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) { val colors = MaterialTheme.colorScheme diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt b/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt index 2db14a9d74..077ba8a2cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt @@ -117,7 +117,7 @@ private fun rememberMovies(refresh: Int, onSelectionChanged: () -> Unit): MovieS } @Composable -private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { +internal fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { val pal = LocalPalette.current val src = remember { MutableInteractionSource() } val hot = rememberHot(src) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt index 0fbbcf3f3e..b6509b332d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt @@ -230,6 +230,7 @@ internal fun BarButton( internal val SecondScreenMode.icon: ImageVector get() = when (this) { SecondScreenMode.NONE -> Icons.Outlined.DesktopAccessDisabled + SecondScreenMode.MENU -> Icons.Outlined.MoreHoriz SecondScreenMode.KEYBOARD_TRACKPAD -> Icons.Outlined.Keyboard SecondScreenMode.TERMINAL -> Icons.Outlined.Terminal SecondScreenMode.DECK_CONTROLS -> Icons.Outlined.SportsEsports @@ -290,17 +291,11 @@ private fun ScreenPickerMenu(picker: ScreenPicker, open: Boolean, dismiss: () -> leading = { Icon(painterResource(R.drawable.ic_stat_session), contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) }, focusRequester = first.takeIf { target == null }, modifier = Modifier.testTag("screen-picker-menu"), ) { dismiss(); menu() } - Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(pal.line)) - Text( - stringResource(R.string.drawer_second_screen).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, - color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 4.dp), - ) } picker.modes.forEach { mode -> val current = mode == picker.current MenuItem( stringResource(mode.label), checked = current && !picker.menuShown, - detail = if (current && picker.menuShown) stringResource(R.string.screen_picker_last_used) else null, leading = { Icon(mode.icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) }, focusRequester = first.takeIf { mode == target }, modifier = Modifier.testTag("screen-picker:${mode.id}"), ) { dismiss(); picker.onPick(mode) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index 908f229e3a..73073cdf8f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -1495,22 +1495,26 @@ private fun ChoiceLine( if (progress != null) ProgressBit(progress) } if (!removable) Spacer(Modifier.padding(end = 6.dp).size(44.dp)) - else { - val delSrc = remember { MutableInteractionSource() } - val delHot = rememberHot(delSrc) - Box( - contentAlignment = Alignment.Center, - modifier = Modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE) - .background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent) - .glideBorder(delHot, ROW_SHAPE, colors.error) - .hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete) - .controllerConfirm(onClick = onDelete), - ) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) } - } + else DeleteButton(name, onDelete = onDelete) } Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) } +@Composable +internal fun DeleteButton(name: String, modifier: Modifier = Modifier, enabled: Boolean = true, onDelete: () -> Unit) { + val colors = MaterialTheme.colorScheme + val delSrc = remember { MutableInteractionSource() } + val delHot = rememberHot(delSrc) && enabled + Box( + contentAlignment = Alignment.Center, + modifier = modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE) + .background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent) + .glideBorder(delHot, ROW_SHAPE, colors.error) + .hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, enabled = enabled, onClick = onDelete) + .controllerConfirm(enabled = enabled, onClick = onDelete), + ) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) } +} + @Composable private fun GetLine( name: String, detail: String, progress: Int?, enabled: Boolean, @@ -1625,7 +1629,7 @@ private fun DeviceChip(s: GpuDriversState) { Box( contentAlignment = Alignment.Center, modifier = Modifier.onGloballyPositioned { at = it.boundsInRoot() }.heightIn(min = 44.dp).paneItem("gpu-device").clip(shape) - .background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface) + .background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier) .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = open) .controllerConfirm(onClick = open) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt new file mode 100644 index 0000000000..da1d8d4bb4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ControllerHaptics.kt @@ -0,0 +1,42 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.os.Build +import android.os.VibrationEffect +import android.os.Vibrator +import android.os.VibratorManager +import android.view.InputDevice +import android.view.KeyEvent + +object ControllerHaptics { + private val navKeys = setOf( + KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, + KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1, + KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2, + ) + + fun onKey(context: Context, event: KeyEvent) { + if (event.action != KeyEvent.ACTION_DOWN || event.keyCode !in navKeys) return + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A && event.repeatCount > 0) return + val fromController = event.isFromSource(InputDevice.SOURCE_GAMEPAD) || + event.isFromSource(InputDevice.SOURCE_DPAD) || event.isFromSource(InputDevice.SOURCE_JOYSTICK) + if (!fromController) return + tick(context) + } + + fun tick(context: Context) { + val vibrator = if (Build.VERSION.SDK_INT >= 31) { + context.getSystemService(VibratorManager::class.java)?.defaultVibrator + } else { + @Suppress("DEPRECATION") context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator + } ?: return + if (!vibrator.hasVibrator()) return + if (Build.VERSION.SDK_INT >= 29) { + vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK)) + } else if (Build.VERSION.SDK_INT >= 26) { + vibrator.vibrate(VibrationEffect.createOneShot(10, VibrationEffect.DEFAULT_AMPLITUDE)) + } else { + @Suppress("DEPRECATION") vibrator.vibrate(10) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt new file mode 100644 index 0000000000..aaa36f8ad0 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt @@ -0,0 +1,16 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.unit.dp + +internal val DeckyIcon: ImageVector = ImageVector.Builder("Decky", 24.dp, 24.dp, 24f, 24f).apply { + for (d in listOf( + "M8,2h2v6H8Z", + "M14,2h2v6h-2Z", + "M5,8h14v3a7,7 0 0 1 -5,6.7V19h-4v-1.3A7,7 0 0 1 5,11Z", + "M11,19h2v3h-2Z", + )) addPath(addPathNodes(d), fill = SolidColor(Color.Black)) +}.build() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt new file mode 100644 index 0000000000..0535e4a8eb --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt @@ -0,0 +1,245 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import coil.compose.AsyncImage +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Search +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.DeckyManager +import com.droiddeck.launcher.runtime.DeckyStore + +private enum class DeckyTab { INSTALLED, STORE, ZIP } + +private const val STORE_PAGE = 30 + +internal fun deckyStoreMatches(plugins: List<DeckyStore.Plugin>, query: String): List<DeckyStore.Plugin> { + val words = query.trim().lowercase().split(Regex("\\s+")).filter { it.isNotEmpty() } + return plugins.filter { p -> + val haystack = (p.name + " " + p.author + " " + p.description + " " + p.tags.joinToString(" ")).lowercase() + words.all { it in haystack } + }.sortedByDescending { it.downloads } +} + +@Composable +internal fun DeckyGroups(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) { + val idle = s.deckyStage == null && !s.deckySessionRunning + SettingsGroup(stringResource(R.string.mode_decky_loader)) { + val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null && + s.deckyInstalled != s.deckyLatestRelease.tag + val status = when { + s.deckyStage != null -> s.deckyStage + s.deckyChecking -> stringResource(R.string.mode_decky_checking) + s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_ready, s.deckyLatestRelease.tag) + s.deckyInstalled == null -> stringResource(R.string.mode_decky_none) + s.deckyLatestRelease == null -> stringResource(R.string.mode_decky_installed, s.deckyInstalled) + updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag) + else -> stringResource(R.string.mode_decky_current, s.deckyInstalled) + } + SettingsRow(stringResource(R.string.decky_status), status) { + val action = when { + s.deckyStage != null -> stringResource(R.string.common_working) + s.deckyChecking -> stringResource(R.string.common_checking) + s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_install_latest) + s.deckyInstalled != null && updateAvailable -> stringResource(R.string.common_update) + else -> stringResource(R.string.common_check) + } + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + SecondaryButton(action, enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning) { + if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck() + else s.deckyLatestRelease?.let(a.onDeckyInstall) + } + if (s.deckyInstalled != null) DeckyUninstall(enabled = idle, onUninstall = a.onDeckyUninstall) + } + } + if (s.deckyInstalled != null) ToggleRow( + host, "decky-enabled", stringResource(R.string.decky_enable), + null, + s.deckyEnabled, + enabled = idle, + onChange = a.onDeckyEnabled, + ) + ChoiceRow( + host, "decky-channel", stringResource(R.string.decky_release_channel), + null, + listOf( + DeckyManager.BRANCH_STABLE to stringResource(R.string.decky_channel_stable), + DeckyManager.BRANCH_PRERELEASE to stringResource(R.string.decky_channel_prerelease), + ) + if (s.deckyBranch == DeckyManager.BRANCH_TESTING) listOf( + DeckyManager.BRANCH_TESTING to stringResource(R.string.decky_channel_testing), + ) else emptyList(), + s.deckyBranch, + enabled = idle, + onPick = a.onDeckyBranch, + ) + if (s.deckyStage != null && s.deckyPercent >= 0) { + LinearProgressIndicator( + progress = { s.deckyPercent / 100f }, + modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp), + ) + } + } + if (s.deckyInstalled == null) return + var tab by rememberSaveable { mutableStateOf(DeckyTab.INSTALLED) } + SettingsGroup(stringResource(R.string.mode_decky_plugins)) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp)) { + TabChip(stringResource(R.string.decky_tab_installed, s.deckyPlugins.size), tab == DeckyTab.INSTALLED, Modifier.weight(1f)) { tab = DeckyTab.INSTALLED } + TabChip(stringResource(R.string.decky_tab_store), tab == DeckyTab.STORE, Modifier.weight(1f)) { tab = DeckyTab.STORE } + TabChip(stringResource(R.string.decky_tab_zip), tab == DeckyTab.ZIP, Modifier.weight(1f)) { tab = DeckyTab.ZIP } + } + LaunchedEffect(tab) { if (tab != DeckyTab.ZIP && s.deckyStore == null && !s.deckyStoreFailed) a.onDeckyStoreRefresh() } + when (tab) { + DeckyTab.INSTALLED -> InstalledPlugins(s, a, idle) + DeckyTab.STORE -> PluginStore(s, a, idle) + DeckyTab.ZIP -> SettingsRow( + stringResource(R.string.decky_tab_zip), + stringResource(R.string.mode_decky_plugins_hint), + ) { + SecondaryButton( + if (s.deckyStage != null && s.deckyDownloadingBinary) stringResource(R.string.mode_decky_plugin_downloading) else stringResource(R.string.mode_decky_plugin_install_zip), + enabled = idle, + modifier = Modifier.testTag("decky-install-zip"), + onClick = a.onPickDeckyPluginZip, + ) + } + } + } +} + +@Composable +private fun InstalledPlugins(s: ModeSettings, a: ModeSettingsActions, idle: Boolean) { + var removing by remember { mutableStateOf<DeckyStore.Installed?>(null) } + if (s.deckyPlugins.isEmpty()) { + Text(stringResource(R.string.decky_none_installed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp)) + } + for (plugin in s.deckyPlugins) { + val listed = s.deckyStore?.firstOrNull { it.name == plugin.name } + val update = listed?.takeIf { DeckyStore.updateAvailable(plugin, it) } + PluginRow( + plugin.name, + listOf(plugin.version, plugin.author).filter { it.isNotBlank() }.joinToString(" · ") + + (update?.latest?.let { " · " + stringResource(R.string.decky_update_to, it.name) } ?: ""), + listed?.imageUrl.orEmpty(), + ) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (update != null) SecondaryButton(stringResource(R.string.common_update), enabled = idle, compact = true) { a.onDeckyStoreInstall(update) } + SecondaryButton(stringResource(R.string.decky_remove), enabled = idle, compact = true, modifier = Modifier.testTag("decky-remove-${plugin.folder}")) { removing = plugin } + } + } + } + if (s.deckyPlugins.isNotEmpty()) Text(stringResource(R.string.decky_changes_next_session), fontSize = 12.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) + removing?.let { plugin -> + androidx.compose.material3.AlertDialog( + onDismissRequest = { removing = null }, + title = { Text(stringResource(R.string.decky_remove_confirm, plugin.name)) }, + text = { Text(stringResource(R.string.decky_remove_confirm_body)) }, + confirmButton = { androidx.compose.material3.TextButton(onClick = { removing = null; a.onDeckyRemove(plugin) }) { Text(stringResource(R.string.decky_remove)) } }, + dismissButton = { androidx.compose.material3.TextButton(onClick = { removing = null }) { Text(stringResource(R.string.common_cancel)) } }, + ) + } +} + +@Composable +private fun PluginStore(s: ModeSettings, a: ModeSettingsActions, idle: Boolean) { + var query by rememberSaveable { mutableStateOf("") } + var searching by remember { mutableStateOf(false) } + var shown by rememberSaveable { mutableIntStateOf(STORE_PAGE) } + val plugins = s.deckyStore + Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp).padding(bottom = 12.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + Box(Modifier.weight(1f)) { + ListRow(tall = true, onClick = { searching = true }) { + androidx.compose.material3.Icon(Icons.Filled.Search, contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp)) + Text( + query.ifEmpty { stringResource(R.string.decky_store_search) }, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, + color = if (query.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onBackground, + modifier = Modifier.weight(1f), + ) + } + } + if (query.isNotEmpty()) SecondaryButton(stringResource(R.string.boot_movie_repo_clear), compact = true) { query = ""; shown = STORE_PAGE } + } + when { + plugins == null -> Text(stringResource(R.string.common_working), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp)) + s.deckyStoreFailed -> Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(stringResource(R.string.decky_store_failed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f)) + SecondaryButton(stringResource(R.string.boot_movie_repo_retry), compact = true) { a.onDeckyStoreRefresh() } + } + else -> { + val matches = remember(plugins, query) { deckyStoreMatches(plugins, query) } + if (matches.isEmpty()) Text(stringResource(R.string.decky_store_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp)) + for (plugin in matches.take(shown)) { + val have = s.deckyPlugins.firstOrNull { it.name == plugin.name } + val current = have != null && !DeckyStore.updateAvailable(have, plugin) + PluginRow( + plugin.name, + listOf(plugin.latest?.name.orEmpty(), plugin.author, plugin.description).filter { it.isNotBlank() }.joinToString(" · "), + plugin.imageUrl, + ) { + SecondaryButton( + stringResource(when { current -> R.string.setup_installed; have != null -> R.string.common_update; else -> R.string.boot_movie_repo_install }), + enabled = idle && !current, compact = true, + modifier = Modifier.testTag("decky-store-${plugin.name}"), + ) { a.onDeckyStoreInstall(plugin) } + } + } + if (matches.size > shown) SecondaryButton(stringResource(R.string.decky_store_more, matches.size - shown), compact = true) { shown += STORE_PAGE } + } + } + } + if (searching) TextEntryDialog( + stringResource(R.string.decky_store_search), query, number = false, confirm = stringResource(R.string.stores_search_open), + onSubmit = { query = it; shown = STORE_PAGE; searching = false }, onDismiss = { searching = false }, id = "decky-store-entry", + ) +} + +@Composable +private fun PluginRow(name: String, detail: String, imageUrl: String, actions: @Composable () -> Unit) { + val colors = MaterialTheme.colorScheme + Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) { + val shape = RoundedCornerShape(8.dp) + Box(Modifier.width(96.dp).aspectRatio(16f / 9f).clip(shape).background(Color(0xFF0E1218))) { + if (imageUrl.isNotEmpty()) AsyncImage(model = imageUrl, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) + } + Column(Modifier.weight(1f)) { + Text(name, fontSize = 15.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } + Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) { actions() } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt index 9d3a84e7a5..523dfb5d65 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt @@ -309,7 +309,7 @@ private fun DesktopCard( Column( Modifier.width(width).paneItem("tile:desktop:$key").then(if (first) Modifier.firstTile() else Modifier) .graphicsLayer { scaleX = scale; scaleY = scale } - .clip(shape).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface) + .clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier) .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onClick(artAt) } .controllerConfirm { onClick(artAt) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt index 21057d1dea..46ea147324 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt @@ -175,7 +175,7 @@ internal fun SessionDrawerPreview(secondScreens: List<SecondScreenDisplay>) { val code = e.nativeKeyEvent.keyCode if (code != android.view.KeyEvent.KEYCODE_BUTTON_L1 && code != android.view.KeyEvent.KEYCODE_BUTTON_R1) return@onPreviewKeyEvent false if (e.type == KeyEventType.KeyDown && e.nativeKeyEvent.repeatCount == 0) { - page = sessionDrawerPages().step(page, if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) + page = sessionDrawerPages().let { it.strip().step(it.tabFor(page), if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) } } true } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt index 5e86cf489e..d14086ffc5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DroidDeckHudSettings.kt @@ -21,11 +21,21 @@ import com.droiddeck.launcher.session.StripMetric @Composable internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { val cfg = a.hudConfig + val context = LocalContext.current + var onlyDuringGame by remember { mutableStateOf(SessionPrefs.hudOnlyDuringGame(context)) } fun on(key: String) = cfg[key] == "1" fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback SettingsGroup(stringResource(R.string.drawer_hud)) { ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud) + if (a.hudOn) ToggleRow( + host, "hud-only-during-game", stringResource(R.string.hud_only_during_game), + stringResource(R.string.hud_only_during_game_hint), onlyDuringGame, + chipModifier = track("hud-only-during-game") + ) { on -> + onlyDuringGame = on + a.onHudOnlyDuringGame(on) + } if (!a.hudOn) return@SettingsGroup val size = DroidDeckHudSize.from(cfg["hudSize"]) ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt index 3ea7950600..43b50251b0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt @@ -148,7 +148,61 @@ object DualScreenPanel { }.onFailure { launching = false; displayId = -1 } } + /** + * The panel on a presentation window sits above every activity on its screen, so an app launched there stays hidden behind it. + * Swapping the panel for a task of its own puts the app above it, and closing the app shows the panel again. + * Launches requested while the swap is under way wait for it and run in the order they were asked for. + */ + fun makeRoomForApp(context: Context, display: Int, launch: () -> Unit) { + pendingLaunches?.let { it.add(launch); return } + val shown = presentation + if (shown == null || displayId != display) { launch(); return } + pendingLaunches = mutableListOf(launch) + val generation = ++handoffGeneration + handoffWaited = 0 + presentation = null + shown.dismiss() + launching = true + val intent = Intent(context, DualScreenActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION) + .putExtra(EXTRA_HANDOFF, generation) + val started = runCatching { + context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle()) + }.isSuccess + if (!started) { launching = false; displayId = -1; releaseLaunches(); return } + handoffPoll.run() + } + + private var pendingLaunches: MutableList<() -> Unit>? = null + private var handoffWaited = 0 + private var handoffGeneration = 0 + internal const val EXTRA_HANDOFF = "handoff" + private val handoffHandler = android.os.Handler(android.os.Looper.getMainLooper()) + private val handoffPoll = object : Runnable { + override fun run() { + if (pendingLaunches == null) return + if (activity != null || handoffWaited >= APP_WAIT_MS) releaseLaunches() + else { handoffWaited += APP_POLL_MS; handoffHandler.postDelayed(this, APP_POLL_MS.toLong()) } + } + } + + private fun releaseLaunches() { + val waiting = pendingLaunches ?: return + pendingLaunches = null + handoffHandler.removeCallbacks(handoffPoll) + waiting.forEach { it() } + } + + private fun dropLaunches() { + pendingLaunches = null + handoffHandler.removeCallbacks(handoffPoll) + } + + private const val APP_POLL_MS = 100 + private const val APP_WAIT_MS = 2000 + fun hide() { + dropLaunches() stopTyping() launching = false displayId = -1 @@ -169,6 +223,9 @@ object DualScreenPanel { if (activity !== host) activity?.finishAndRemoveTask() activity = host launching = false + val waiting = pendingLaunches + val generation = host.intent?.getIntExtra(EXTRA_HANDOFF, -1) ?: -1 + handoffHandler.post { if (pendingLaunches === waiting && generation == handoffGeneration) releaseLaunches() } return true } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/EmptyLibrary.kt b/app/src/main/java/com/droiddeck/launcher/ui/EmptyLibrary.kt index 4b8de6520f..192afbece1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/EmptyLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/EmptyLibrary.kt @@ -33,7 +33,9 @@ import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.lerp import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.unit.dp @@ -47,21 +49,30 @@ import kotlin.math.sin @Composable internal fun EmptyLibrary(avoid: Rect?, wall: (@Composable () -> Unit)? = null, fade: @Composable () -> Unit) { - val clock = rememberMarkClock(avoid) - Box(Modifier.fillMaxSize().onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) }) { + var origin by remember { mutableStateOf(Offset.Zero) } + val clock = rememberMarkClock(avoid?.translate(-origin.x, -origin.y)) + Box( + Modifier.fillMaxSize() + .onGloballyPositioned { origin = it.positionInRoot() } + .onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) }, + ) { if (wall != null) wall() else EmptyWall(clock) fade() Mark(clock) } } -private const val TRACE_MS = 1250f -private const val FILL_FROM = 450f private const val POP_FROM = 900f private const val IMPACT = 2200f private const val RIPPLE_MS = 1250f private const val HIT_MS = 900f private const val END = 3600f +private const val REVEAL_MS = 2300f +private const val TRACE_DRAW_MS = 900f +private const val TRACE_FADE_MS = 500f +private const val REVEAL_FILL_FROM = 600f +private const val REVEAL_FILL_MS = 450f +private const val REVEAL_FADE_FROM = 1700f private const val POKE = 880f private const val DRIFT_MS = 75_000f @@ -82,8 +93,7 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock { val haptics = LocalHapticFeedback.current val keepOff by rememberUpdatedState(avoid) val speed = with(LocalDensity.current) { 64.dp.toPx() } - val inset = with(LocalDensity.current) { 10.dp.toPx() } - val clearance = with(LocalDensity.current) { 16.dp.toPx() } + val clearance = with(LocalDensity.current) { 4.dp.toPx() } LaunchedEffect(clock) { var last = -1L var vx = speed * 0.8f @@ -109,16 +119,28 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock { var x = clock.at.x + vx * dt / 1000f var y = clock.at.y + vy * dt / 1000f - val hw = f.halfWidth - val hh = f.halfHeight - if (x - hw < inset) { x = inset + hw; vx = abs(vx) } - if (x + hw > clock.page.width - inset) { x = clock.page.width - inset - hw; vx = -abs(vx) } - if (y - hh < inset) { y = inset + hh; vy = abs(vy) } - if (y + hh > clock.page.height - inset) { y = clock.page.height - inset - hh; vy = -abs(vy) } + val hw = f.ball + val hh = f.ball + if (x - hw < 0f) { x = hw; vx = abs(vx) } + if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) } + if (y - hh < 0f) { y = hh; vy = abs(vy) } + if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) } keepOff?.inflate(clearance)?.let { r -> - if (x + hw > r.left && x - hw < r.right && y + hh > r.top && y - hh < r.bottom) { - val outX = if (x < r.center.x) r.left - (x + hw) else r.right - (x - hw) - val outY = if (y < r.center.y) r.top - (y + hh) else r.bottom - (y - hh) + val nearX = x.coerceIn(r.left, r.right) + val nearY = y.coerceIn(r.top, r.bottom) + val gapX = x - nearX + val gapY = y - nearY + val gap = hypot(gapX, gapY) + if (gap in 0.0001f..f.ball) { + val nx = gapX / gap + val ny = gapY / gap + x = nearX + nx * f.ball + y = nearY + ny * f.ball + val into = vx * nx + vy * ny + if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny } + } else if (gap <= 0.0001f) { + val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x + val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) } else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) } } @@ -294,30 +316,33 @@ private fun Mark(clock: MarkClock) { } else 0f translate(0f, shake) { - val fill = Out.transform(clamp01((intro - FILL_FROM) / 450f)) - if (fill > 0f) { - val lift = 8f * k * (1f - fill) - val edge = 5f * f.s - LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) } - LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) } - drawPath(left, slabEdge.copy(alpha = fill)) - drawPath(right, slabEdge.copy(alpha = fill)) - LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) } - LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) } - drawPath(left, ink.copy(alpha = fill)) - drawPath(right, ink.copy(alpha = fill)) - } - - if (intro < TRACE_MS) { - val drawn = TraceEase.transform(clamp01(intro / 775f)) - val alpha = if (intro < 775f) 1f else 1f - (intro - 775f) / 475f - LogoShape.left(left, 0f, f::px) - LogoShape.right(right, f::px) - for (half in listOf(left, right)) { - measure.setPath(half, false) - piece.reset() - measure.getSegment(0f, measure.length * drawn, piece, true) - drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(2f * f.s)) + val since = t - IMPACT + if (since in 0f..REVEAL_MS) { + val fade = 1f - clamp01((since - REVEAL_FADE_FROM) / (REVEAL_MS - REVEAL_FADE_FROM)) + val fill = Out.transform(clamp01((since - REVEAL_FILL_FROM) / REVEAL_FILL_MS)) * fade + if (fill > 0f) { + val lift = 8f * k * (1f - fill / fade) + val edge = 5f * f.s + LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) } + LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) } + drawPath(left, slabEdge.copy(alpha = fill)) + drawPath(right, slabEdge.copy(alpha = fill)) + LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) } + LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) } + drawPath(left, ink.copy(alpha = fill)) + drawPath(right, ink.copy(alpha = fill)) + } + val drawn = TraceEase.transform(clamp01(since / TRACE_DRAW_MS)) + val alpha = (if (since < TRACE_DRAW_MS) 1f else 1f - (since - TRACE_DRAW_MS) / TRACE_FADE_MS).coerceIn(0f, 1f) * fade + if (alpha > 0f) { + LogoShape.left(left, 0f, f::px) + LogoShape.right(right, f::px) + for (half in listOf(left, right)) { + measure.setPath(half, false) + piece.reset() + measure.getSegment(0f, measure.length * drawn, piece, true) + drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(3f * f.s)) + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt index 9fd3631553..5a1363a65e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt @@ -60,7 +60,8 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.R -import com.droiddeck.launcher.session.GameStorage +import com.droiddeck.launcher.files.StorageRoot +import com.droiddeck.launcher.files.StorageRoots import com.droiddeck.launcher.stores.formatBytes import java.io.File @@ -74,10 +75,16 @@ internal class PickVolume(val root: File, val label: String, val removable: Bool } internal fun pickVolumes(context: Context): List<PickVolume> = - listOf(PickVolume(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), removable = false)) + - GameStorage.options(context).mapNotNull { o -> - File(o.path.substringBefore("/Android/")).takeIf { it.isDirectory }?.let { PickVolume(it, o.name, removable = true) } - }.distinctBy { it.root.absolutePath } + pickVolumes(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), StorageRoots.list(context)) + +internal fun pickVolumes(internal: File, internalLabel: String, roots: List<StorageRoot>): List<PickVolume> { + val internalPath = internal.absolutePath.trimEnd('/') + fun overlapsInternal(path: String) = path == internalPath || path.startsWith("$internalPath/") || internalPath.startsWith("$path/") + return listOf(PickVolume(internal, internalLabel, removable = false)) + + roots.filter { it.readable && !overlapsInternal(it.dir.absolutePath.trimEnd('/')) } + .map { PickVolume(it.dir, it.label, removable = true) } + .distinctBy { it.root.absolutePath } +} internal class PickFolder(val dir: File, val readable: Boolean) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt index 92a6d0b365..c45baa29f1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt @@ -33,6 +33,8 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.geometry.RoundRect import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity @@ -109,13 +111,21 @@ internal fun VeilRing() { } } -private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float = +private fun cornersOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): FloatArray = when (val o = shape.createOutline(size, dir, density)) { - is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x - is Outline.Rectangle -> 0f - is Outline.Generic -> minOf(size.width, size.height) / 2f + is Outline.Rounded -> o.roundRect.run { + floatArrayOf(topLeftCornerRadius.x, topRightCornerRadius.x, bottomRightCornerRadius.x, bottomLeftCornerRadius.x) + } + is Outline.Rectangle -> FloatArray(4) + is Outline.Generic -> FloatArray(4) { minOf(size.width, size.height) / 2f } } +private fun ringRect(l: Float, t: Float, w: Float, h: Float, radii: FloatArray, inset: Float): Path { + // Radii are not capped one by one: the path scales corners whose neighbours overlap, as the outline does. + fun r(i: Int) = CornerRadius((radii[i] - inset).coerceAtLeast(0f)) + return Path().apply { addRoundRect(RoundRect(Rect(l, t, l + w, t + h), r(0), r(1), r(2), r(3))) } +} + @Composable internal fun Modifier.glideBorder( hot: Boolean, @@ -190,7 +200,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { val density = LocalDensity.current val dir = LocalLayoutDirection.current val edges = remember { List(4) { Animatable(0f) } } - val corner = remember { Animatable(0f) } + val corners = remember { List(4) { Animatable(0f) } } val solid = remember { Animatable(0f) } val alpha = remember { Animatable(0f) } val scope = rememberCoroutineScope() @@ -259,14 +269,14 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { fun droplet(s: GlideSource, b: Rect) { jobs.forEach { it?.cancel() } val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size - val endCorner = cornerOf(s.shape, size, dir, density) + val endCorners = cornersOf(s.shape, size, dir, density) jobs[5] = scope.launch { val r = with(density) { 6.dp.toPx() } fun dot(c: Offset) = listOf(c.x - r, c.y - r, c.x + r, c.y + r) val here = Offset((edges[0].value + edges[2].value) / 2f, (edges[1].value + edges[3].value) / 2f) coroutineScope { launch { solid.animateTo(1f, Motion.tw(80)) } - launch { corner.animateTo(r, Motion.tw(90)) } + corners.forEach { c -> launch { c.animateTo(r, Motion.tw(90)) } } dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } } } val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density @@ -281,7 +291,9 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { flight.cancel() val at = glide.boundsOf(s) ?: b launch { solid.animateTo(0f, Motion.tw(150)) } - launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) } + // The droplet job is cancelled by the next move, so the shape settles on the corner job instead. + jobs[4]?.cancel() + jobs[4] = scope.launch { corners.forEachIndexed { i, c -> launch { c.animateTo(endCorners[i], Motion.sp(0.8f, 600f)) } } } listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v -> jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) } } @@ -289,9 +301,11 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { } fun cornerTo(s: GlideSource, b: Rect, snap: Boolean) { val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size - val r = cornerOf(s.shape, size, dir, density) + val r = cornersOf(s.shape, size, dir, density) jobs[4]?.cancel() - jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) } + jobs[4] = scope.launch { + corners.forEachIndexed { i, c -> launch { if (snap) c.snapTo(r[i]) else c.animateTo(r[i], Motion.sp(0.8f, 500f)) } } + } } snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) -> if (Motion.scale == 0f) { @@ -302,7 +316,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { else { listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> edges[i].snapTo(v) } val size = src.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size - corner.snapTo(cornerOf(src.shape, size, dir, density)) + cornersOf(src.shape, size, dir, density).forEachIndexed { i, v -> corners[i].snapTo(v) } alpha.snapTo(1f) } shown = src @@ -343,10 +357,11 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { val out = with(density) { 3.dp.toPx() } val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out) jobs.forEach { it?.cancel() } + // Set before the join: a move of the target restarts this block there, after shown is already set. + cornerTo(src, b, snap = true) scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join() dirSpecs = List(4) { Edge(0.6f, 700f) } delays = LongArray(4) - cornerTo(src, b, snap = true) scope.launch { alpha.animateTo(1f, Motion.tw(140)) } } else { val dx = b.center.x - (edges[0].value + edges[2].value) / 2f @@ -394,21 +409,13 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { val l = edges[0].value; val t = edges[1].value; val r = edges[2].value; val b = edges[3].value val sw = (r - l - w).coerceAtLeast(0f) val sh = (b - t - w).coerceAtLeast(0f) - val rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f) + val radii = FloatArray(4) { corners[it].value } val f = solid.value - if (f > 0.01f) drawRoundRect( - color, topLeft = Offset(l, t), size = Size(r - l, b - t), - cornerRadius = CornerRadius(corner.value), alpha = a * f, - ) + if (f > 0.01f) drawPath(ringRect(l, t, r - l, b - t, radii, 0f), color, alpha = a * f) if (f < 0.99f) { - drawRoundRect( - color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh), - cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha, - ) - drawRoundRect( - color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh), - cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a, - ) + val inner = ringRect(l + w / 2f, t + w / 2f, sw, sh, radii, w / 2f) + drawPath(inner, color, alpha = a * (1f - f) * fillAlpha) + drawPath(inner, color, style = Stroke(w), alpha = a) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index adf55c4b1b..bc55af594e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -263,6 +263,10 @@ private fun Content( SyncTabPage(s, modifier.padding(horizontal = padH).padding(top = padV)) return } + if (selected == "decky" || selected == "boot-movies") { + SteamTabPage(selected, a, modifier.padding(horizontal = padH).padding(top = padV)) + return + } if (selected == "updates") { UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV)) return @@ -477,7 +481,7 @@ private fun UserAppIcon(app: UserApps.App, size: Int) { } @Composable -private fun UserAppsProgress() { +internal fun UserAppsProgress() { val colors = MaterialTheme.colorScheme val working = UserAppsState.working Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) { @@ -514,7 +518,9 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions, Column { Text(app.name, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) Text( - (app.repo?.let { stringResource(R.string.user_apps_github_version, it, app.version.orEmpty()) } ?: stringResource(app.kind.label())) + + (app.repo?.let { stringResource(R.string.user_apps_github_version, it, app.version.orEmpty()) } + ?: app.version?.takeIf { app.feed != null }?.let { stringResource(R.string.user_apps_github_version, stringResource(app.kind.label()), it) } + ?: stringResource(app.kind.label())) + (if (app.arch == "x86_64" || app.arch == "i386") " · " + stringResource(R.string.app_fex_x86, app.arch) else ""), fontSize = 14.sp, color = colors.onSurfaceVariant, ) @@ -526,7 +532,7 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions, PrimaryButton(stringResource(R.string.user_apps_open, app.name), enabled = !s.busy, main = true) { a.onUserApp(app) } BusyChip(s) SecondaryButton(stringResource(R.string.user_apps_edit), enabled = UserAppsState.working == null) { editing = true } - if (app.repo != null) UpdateButton(app, s) + if (app.updatable) UpdateButton(app, s) RemoveAppButton(app, enabled = !s.busy && !s.sessionRunning && UserAppsState.working == null) { UserAppsState.remove(ctx, app); onSelect("desktop") } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index 5503ef22a1..2322e93827 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -56,9 +56,9 @@ import androidx.compose.material.icons.filled.Terminal import androidx.compose.material.icons.filled.Apps import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.SdStorage +import androidx.compose.material.icons.filled.Movie import androidx.compose.material.icons.filled.Sync import androidx.compose.material.icons.filled.MoreHoriz -import androidx.compose.material.icons.filled.SystemUpdate import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.material3.Icon @@ -207,8 +207,10 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) { "setup" -> R.string.rail_setup to Icons.Filled.Settings "storage" -> R.string.rail_storage to Icons.Filled.SdStorage "sync" -> R.string.rail_sync to Icons.Filled.Sync + "decky" -> R.string.rail_decky to DeckyIcon + "boot-movies" -> R.string.rail_boot_movies to Icons.Filled.Movie NavTabs.MORE -> R.string.rail_more to Icons.Filled.MoreHoriz - else -> R.string.rail_updates to Icons.Filled.SystemUpdate + else -> R.string.rail_updates to updatesIcon(RunningBuild.kind()) } internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) || diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 2267bef930..74bd115145 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -143,6 +143,7 @@ class FrontEndState( val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null, val androidApps: List<HomeApp.LaunchableApp> = emptyList(), val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(), + val ownScreen: SecondScreenDisplay? = null, val dualScreen: Boolean = false, val dualScreenDevice: Boolean = false, val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO, @@ -174,6 +175,7 @@ class FrontEndState( val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER, val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM, val launcherFullscreen: Boolean = true, + val controllerHaptics: Boolean = true, val downloadSource: String = DownloadSource.MODE_AUTO, val downloadMirror: String = "", val downloadPrefix: String = "", @@ -279,6 +281,7 @@ class FrontEndActions( val onLauncherOrientation: (Int) -> Unit = {}, val onHomePage: (String) -> Unit = {}, val onLauncherFullscreen: (Boolean) -> Unit = {}, + val onControllerHaptics: (Boolean) -> Unit = {}, val onAnimationsEnabled: (Boolean) -> Unit = {}, val onLowStorageWarning: (Boolean) -> Unit = {}, val onDualScreenMode: (String) -> Unit = {}, @@ -311,16 +314,14 @@ class FrontEndActions( val onBackActionsInverted: (Boolean) -> Unit = {}, val onRefreshPhantomStatus: () -> Unit = {}, val onOpenDeveloperOptions: (Int?) -> Unit = {}, - val onWirelessAdbPair: (String, Int, String, (String?) -> Unit) -> Unit, - val onFindWirelessAdbPort: (String, (Int?) -> Unit) -> Unit = { _, done -> done(null) }, - val onWirelessAdbApply: (String, Int, Boolean, (String?) -> Unit) -> Unit, val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit, val onCopyPhantomCommand: (Boolean) -> Unit = {}, val onDismissPhantomGate: () -> Unit = {}, - val onStartWirelessAdbPairing: () -> Unit = {}, + val onStartWirelessAdbPairing: (Boolean) -> Unit = {}, val onStartPairingGuide: (Int?, Boolean) -> Boolean = { _, _ -> false }, val onShowPhantomGate: () -> Unit = {}, - val onOpenNotificationSettings: () -> Unit = {}, + val onQueuePlaySteam: () -> Unit = {}, + val onEnsureNotifications: ((Boolean) -> Unit) -> Unit = { it(true) }, val controller: ControllerActions? = null, val updates: UpdatesActions = UpdatesActions(), ) @@ -452,6 +453,7 @@ internal suspend fun focusSoon(target: () -> FocusRequester) { @Composable fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) { val frontFocus = remember { FrontFocus() } + androidx.compose.runtime.SideEffect { RunningBuild.channel = s.updates.follow.channel } val textInput = androidx.compose.ui.platform.LocalTextInputService.current val bottomTextInput = remember(textInput) { textInput?.let { androidx.compose.ui.text.input.TextInputService(BottomScreenTextInput(it)) } } androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize().pointerInput(Unit) { @@ -505,17 +507,16 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com LaunchedEffect(com.droiddeck.launcher.stores.StoresState.openGameRequest) { if (com.droiddeck.launcher.stores.StoresState.openGameRequest != null) selected = "stores" } - var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) } var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) } var developerChoiceGuided by rememberSaveable { mutableStateOf(false) } var developerChoiceToggle by rememberSaveable { mutableStateOf(false) } - var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) } + var guidedLimitEnabled by rememberSaveable { mutableStateOf(false) } var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) } val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val ctx = LocalContext.current val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) - val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice + val processSettingsPageVisible = phantomGateVisible || showDeveloperDisplayChoice val requestDeveloperOptions = { developerChoiceGuided = false developerChoiceToggle = false @@ -523,7 +524,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com else showDeveloperDisplayChoice = true } val openDeveloperOptionsOn: (Int?) -> Unit = { displayId -> - if (developerChoiceGuided) a.onStartWirelessAdbPairing() + if (developerChoiceGuided) a.onStartWirelessAdbPairing(guidedLimitEnabled) val guided = developerChoiceGuided || developerChoiceToggle if (!guided || !a.onStartPairingGuide(displayId, developerChoiceToggle)) a.onOpenDeveloperOptions(displayId) developerChoiceGuided = false @@ -539,31 +540,35 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com else showDeveloperDisplayChoice = true } } - val startGuidedPairing = { - if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) { - wirelessAdbDesiredEnabled = false - showWirelessAdbFix = true - } else { - developerChoiceGuided = true - if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null) - else showDeveloperDisplayChoice = true + val startGuidedPairing: (Boolean) -> Unit = { enabled -> + a.onEnsureNotifications { granted -> + if (granted) { + guidedLimitEnabled = enabled + developerChoiceGuided = true + if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null) + else showDeveloperDisplayChoice = true + } } } + val childProcessRequest = androidx.compose.runtime.rememberUpdatedState { + if (PhantomProcessLimit.hasDeveloperToggle()) requestChildProcessToggle() else a.onShowPhantomGate() + } + DisposableEffect(Unit) { + val handler: () -> Unit = { childProcessRequest.value() } + ChildProcessSetup.request = handler + onDispose { if (ChildProcessSetup.request === handler) ChildProcessSetup.request = null } + } var applyingSavedPairing by remember { mutableStateOf(false) } val fixPhantomLimit = { - if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing() + if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing(false) else if (!applyingSavedPairing) { applyingSavedPairing = true a.onSetPhantomProcessLimit(false) { error -> applyingSavedPairing = false - if (error != null) startGuidedPairing() + if (error != null) startGuidedPairing(false) } } } - val requestWirelessAdbFix: (Boolean) -> Unit = { enabled -> - wirelessAdbDesiredEnabled = enabled - showWirelessAdbFix = true - } LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) { if (phantomGateVisible) { while (true) { @@ -759,24 +764,28 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com focusManager.clearFocus(force = true) onRailSelect(key) }, a) + val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int -> + if (!processSettingsPageVisible) { + val keys = navigationKeys(s) + keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key -> + PageSwipe.direction = step + onRailSelect(key) + } + } + } + DisposableEffect(Unit) { + val handler: (Int) -> Unit = { tabStep.value(it) } + MainTabSteps.handler = handler + onDispose { if (MainTabSteps.handler === handler) MainTabSteps.handler = null } + } CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) { + val swipeContext = androidx.compose.ui.platform.LocalContext.current + remember { com.droiddeck.launcher.core.AppUiPrefs.pageSwipe(swipeContext).also { PageSwipe.on = it } } val agentKeyboardOpen = openTab == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0 LauncherLayout( bottomNavigation && !s.dualScreen, pal.line, Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() } - .then(if (openTab == "agent") Modifier.imePadding() else Modifier) - .then(if (s.dualScreen) Modifier.onKeyEvent { event -> - val step = dualPageStep(event.nativeKeyEvent) ?: return@onKeyEvent false - if (event.type == KeyEventType.KeyDown && !processSettingsPageVisible) { - val keys = navigationKeys(s) - val at = keys.indexOf(railSelectionNow.value) - keys.getOrNull(at + step)?.let { key -> - PageSwipe.direction = step - onRailSelect(key) - } - } - true - } else Modifier), + .then(if (openTab == "agent") Modifier.imePadding() else Modifier), navigation = { if (s.dualScreen || (bottomNavigation && agentKeyboardOpen)) Unit else if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus) @@ -785,7 +794,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com ) { Pane( s, selected, a, page, - Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }) { dir -> + Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }, edgeGuard = { !bottomNavigation }) { dir -> val keys = navigationKeys(s) val at = keys.indexOf(railSelectionNow.value) if (at >= 0) keys.getOrNull(at + dir)?.let { key -> @@ -795,12 +804,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com }, { selected = it }, onAndroidAppClick = { app -> - if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null) + if (s.secondScreenDisplays.isEmpty() && s.ownScreen == null) a.onAndroidApp(app, null) else appToChooseDisplay = app }, onOpenDeveloperOptions = requestChildProcessToggle, - onRequestWirelessAdb = requestWirelessAdbFix, - onPairWirelessDebugging = startGuidedPairing, + onPairWirelessDebugging = { startGuidedPairing(false) }, + onRequestWirelessAdb = startGuidedPairing, ) } @@ -816,7 +825,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com SessionDrawerPreview(s.secondScreenDisplays) appToChooseDisplay?.let { app -> - val secondaryDisplay = s.secondScreenDisplays.firstOrNull() + val secondaryDisplay = s.secondScreenDisplays.firstOrNull() ?: s.ownScreen ChooseAppDisplayDialog( app = app, secondaryDisplay = secondaryDisplay, @@ -831,7 +840,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com onDismiss = { appToChooseDisplay = null }, ) } - if (phantomGateVisible && !showWirelessAdbFix) { + if (phantomGateVisible) { Box(Modifier.fillMaxSize().background(colors.background)) { PhantomProcessGatePage( status = s.phantomProcessStatus, @@ -839,21 +848,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com onOpenDeveloperOptions = requestChildProcessToggle, applyingSavedPairing = applyingSavedPairing, onFixWithWirelessDebugging = fixPhantomLimit, - onEnterAddressManually = { requestWirelessAdbFix(false) }, onCopyCommand = { a.onCopyPhantomCommand(false) }, - onOpenNotificationSettings = a.onOpenNotificationSettings, - ) - } - } - if (showWirelessAdbFix) { - Box(Modifier.fillMaxSize().background(colors.background)) { - WirelessAdbFixPage( - onBack = { showWirelessAdbFix = false }, - desiredEnabled = wirelessAdbDesiredEnabled, - onOpenDeveloperOptions = requestDeveloperOptions, - onPair = a.onWirelessAdbPair, - onFindConnectPort = a.onFindWirelessAdbPort, - onApply = a.onWirelessAdbApply, ) } } @@ -898,3 +893,11 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com } } } + +internal object ChildProcessSetup { + @Volatile var request: (() -> Unit)? = null +} + +internal object MainTabSteps { + @Volatile var handler: ((Int) -> Unit)? = null +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index b7976c89dd..543c5f6857 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -51,6 +51,7 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -248,6 +249,7 @@ internal fun SetupPanel( if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) } else when (tab) { OVERVIEW_TAB -> { + OnboardingCard(limitBlocks, a.onShowPhantomGate) // Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here. val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable() val gpuCheck: @Composable (Boolean) -> Unit = { divider -> @@ -516,6 +518,18 @@ internal fun SetupPanel( if (s.launcherFullscreen) stringResource(R.string.setup_fullscreen_on) else stringResource(R.string.setup_fullscreen_off), s.launcherFullscreen, ) { a.onLauncherFullscreen(it) } + ToggleRow( + host, "page-swipe", stringResource(R.string.setup_page_swipe), + stringResource(R.string.setup_page_swipe_hint), PageSwipe.on, + ) { on -> + PageSwipe.on = on + com.droiddeck.launcher.core.AppUiPrefs.setPageSwipe(ctx, on) + } + ToggleRow( + host, "controller-haptics", stringResource(R.string.setup_controller_haptics), + stringResource(R.string.setup_controller_haptics_hint), + s.controllerHaptics, + ) { a.onControllerHaptics(it) } if (s.dualScreenDevice) { val dualModes = listOf( com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto), @@ -528,7 +542,7 @@ internal fun SetupPanel( ) ChoiceRow( host, "dual-screen-sessions", stringResource(R.string.setup_dual_screen_sessions), stringResource(R.string.setup_dual_screen_sessions_hint), - dualModes, s.dualScreenSessions, onPick = a.onDualScreenSessions, + dualModes.take(2) + (com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED to stringResource(R.string.setup_dual_screen_swapped)) + dualModes.drop(2), s.dualScreenSessions, onPick = a.onDualScreenSessions, ) if (s.dualScreenSessions != com.droiddeck.launcher.input.DualScreen.MODE_OFF) { ToggleRow(host, "dual-screen-controls", stringResource(R.string.setup_dual_screen_controls), @@ -1084,8 +1098,6 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron internal const val GAME_SETTINGS_MENU = "game-settings" -private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal" - @Composable private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) { val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext @@ -1135,7 +1147,7 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro MenuItem(stringResource(R.string.epic_resolve), checked = false) { host.open = null runCatching { - appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(EPIC_RESOLVE_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) + appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(com.droiddeck.launcher.stores.epic.EpicLogin.ACCOUNT_SIGN_IN_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) } } } @@ -1154,7 +1166,7 @@ private fun SettingCard(label: String, value: String, id: String, modifier: Modi verticalArrangement = Arrangement.spacedBy(3.dp), modifier = modifier.paneItem(id) .graphicsLayer { scaleX = scale; scaleY = scale } - .then(if (LocalGlass.current != null) Modifier.glass(Shape14, if (hot) 0.04f else 0f) else Modifier.clip(Shape14).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)) + .then(if (LocalGlass.current != null) Modifier.glass(Shape14, if (hot) 0.04f else 0f) else Modifier.clip(Shape14).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)) .glideBorder(hot, Shape14, pal.signal, if (LocalGlass.current != null) Color.Transparent else pal.line2) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) .controllerConfirm(onClick = onClick) @@ -1261,3 +1273,66 @@ private fun CustomColorRows() { } } } + +@Composable +internal fun OnboardingCard(limitBlocks: Boolean = false, onSetUpLimit: () -> Unit = {}) { + val active by com.droiddeck.launcher.session.Onboarding.active.collectAsState() + val failed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState() + val facts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState() + val rows = com.droiddeck.launcher.session.Onboarding.rows(active, failed, facts) + val firstRun by com.droiddeck.launcher.session.Onboarding.firstRun.collectAsState() + val settling = firstRun && com.droiddeck.launcher.session.Onboarding.pending(rows) + if (!settling) return + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val overall = com.droiddeck.launcher.session.Onboarding.overall(rows) + Column(Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) { + Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 12.dp)) { + Text(stringResource(R.string.onboarding_title), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) + Text(stringResource(R.string.onboarding_summary, overall), fontSize = 13.sp, color = colors.onSurfaceVariant) + LinearProgressIndicator(progress = { overall / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(4.dp)) + } + rows.forEach { row -> + Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp), + ) { + Column(Modifier.weight(1f)) { + Text( + stringResource(when (row.step) { + com.droiddeck.launcher.session.Onboarding.Step.RUNTIME -> R.string.onboarding_step_runtime + com.droiddeck.launcher.session.Onboarding.Step.PROTON -> R.string.onboarding_step_proton + com.droiddeck.launcher.session.Onboarding.Step.STEAM -> R.string.onboarding_step_steam + }), + fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, + ) + val detail = when (row.state) { + com.droiddeck.launcher.session.Onboarding.State.ACTIVE -> row.label.orEmpty() + com.droiddeck.launcher.session.Onboarding.State.FAILED -> stringResource(R.string.onboarding_failed) + com.droiddeck.launcher.session.Onboarding.State.WAITING -> stringResource(R.string.onboarding_waiting) + com.droiddeck.launcher.session.Onboarding.State.DONE -> stringResource(R.string.onboarding_done) + } + Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + if (row.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE) { + if (row.percent >= 0) LinearProgressIndicator(progress = { row.percent / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp)) + else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp)) + } + } + } + } + if (limitBlocks) { + Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp), + ) { + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.setup_limit), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + Text(stringResource(R.string.onboarding_limit_reason), fontSize = 13.sp, color = colors.onSurfaceVariant) + } + PrimaryButton(stringResource(R.string.onboarding_limit_action), compact = true, onClick = onSetUpLimit) + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt index 6bc4fd2149..4245236747 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -205,12 +205,15 @@ internal fun PrimaryButton( large: Boolean = false, icon: ImageVector? = null, fill: Boolean = false, + progress: Float? = null, onClick: () -> Unit, ) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current + val shownProgress by animateFloatAsState(progress?.coerceIn(0f, 1f) ?: 0f, Motion.tw(300), label = "btnProgress") val pillMode = LocalPillButtons.current val btnShape = if (pillMode) CircleShape else Shape12 + val outlined = LocalGradientOutline.current && enabled val frontFocus = if (main) LocalFrontFocus.current else null if (frontFocus != null) DisposableEffect(Unit) { frontFocus.primaryAttached++ @@ -233,7 +236,13 @@ internal fun PrimaryButton( .graphicsLayer { alpha = if (LaunchOrigin.flooding === placed) 0f else 1f; scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = btnShape; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal } .clip(btnShape) .background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant))) + .then(if (progress != null) Modifier.drawBehind { + val done = size.width * shownProgress + if (enabled) drawRect(Color.Black.copy(alpha = 0.32f), topLeft = androidx.compose.ui.geometry.Offset(done, 0f), size = androidx.compose.ui.geometry.Size(size.width - done, size.height)) + else drawRect(pal.signal.copy(alpha = 0.4f), size = androidx.compose.ui.geometry.Size(done, size.height)) + } else Modifier) .then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, btnShape)) + .then(if (outlined) Modifier.border(2.dp, Brush.linearGradient(listOf(pal.primary2, colors.primary)), btnShape) else Modifier) .glideBorder(hot, btnShape, pal.signal, hotFillAlpha = 0f) .hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) { placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index 3b93f06527..bb4cc867cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -42,6 +42,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.outlined.Download import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.outlined.Edit import androidx.compose.material.icons.outlined.VideogameAsset @@ -54,6 +55,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember @@ -73,6 +75,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.boundsInRoot import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.platform.LocalDensity @@ -94,7 +97,11 @@ import coil.compose.AsyncImage import com.droiddeck.launcher.R import com.droiddeck.launcher.frontend.GameRemoval import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.runtime.CurseForgeApp +import com.droiddeck.launcher.runtime.UserApps +import com.droiddeck.launcher.runtime.WowAddonCatalog import com.droiddeck.launcher.runtime.WowAddons +import com.droiddeck.launcher.store.UserAppsState import com.droiddeck.launcher.session.GameSaves import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.stores.CatalogItem @@ -125,6 +132,9 @@ import kotlinx.coroutines.withContext import java.io.File import androidx.compose.runtime.setValue import androidx.compose.runtime.getValue +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.foundation.layout.offset internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) { fun game(games: List<Library.SteamGame>): Library.SteamGame? = when { @@ -248,12 +258,18 @@ internal fun GameDetail( color = MaterialTheme.colorScheme.error, maxLines = 3, overflow = TextOverflow.Ellipsis, ) Spacer(Modifier.height(2.dp)) - GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore) } + Column { + CompositionLocalProvider(LocalPillButtons provides true, LocalGradientOutline provides true) { + GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore, part = ActionPart.LEAD) + } + Spacer(Modifier.height(LeadGap - ActionGap)) + GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier, compactMenu = stacked, inStore = inStore, part = ActionPart.REST) } + } } } if (StoresMotion.heroLands) header() else Rise(1) { header() } if (tab != null) Rise(2) { - Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Column(Modifier.fillMaxWidth().padding(top = ActionGap), verticalArrangement = Arrangement.spacedBy(ActionGap)) { val labels = tabs.map { t -> when (t) { GameTab.ABOUT -> stringResource(R.string.game_tab_about) @@ -271,15 +287,17 @@ internal fun GameDetail( focusRequesters = tabs.map { tabFocus.getValue(it) }, bumpers = tabs.size > 1, compact = stacked, ) Box(Modifier.fillMaxWidth().onFocusChanged { if (inPanel && !it.hasFocus) dropped++; inPanel = it.hasFocus }.testTag("game-tab-${tab.name.lowercase()}")) { - when (tab) { - GameTab.ABOUT -> AboutTab(developer, publisher, releaseDate, description, scores, stacked) { - if (!s.shortcutPicker) GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game) + CompositionLocalProvider(LocalRevealChecked provides false) { + when (tab) { + GameTab.ABOUT -> AboutTab(developer, publisher, releaseDate, description, scores, stacked) { + if (!s.shortcutPicker) GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game) + } + GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) } + GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail) + GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a) + GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, s.sessionRunning, a) + GameTab.INSTALL -> InstallTab(game, installed, item, store) } - GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) } - GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail) - GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a) - GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a) - GameTab.INSTALL -> InstallTab(game, installed, item, store) } } } @@ -342,14 +360,22 @@ private fun StatusChip(text: String, icon: androidx.compose.ui.graphics.vector.I } } +private val ActionGap = 12.dp +private val LeadGap = 20.dp + @Composable private fun GameCapsule(scores: GameScores?, actions: @Composable () -> Unit) { + var noActions by remember { mutableStateOf(false) } + val shown = scores?.takeIf { it.metacritic != Lookup.None || it.hltb != Lookup.None } + val empty = noActions && shown == null Row( verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth().glass(RoundedCornerShape(30.dp)).padding(6.dp), + modifier = Modifier.fillMaxWidth().then(if (empty) Modifier else Modifier.padding(top = ActionGap).glass(RoundedCornerShape(30.dp)).padding(6.dp)), ) { - CompositionLocalProvider(LocalPillButtons provides true) { Box(Modifier.weight(1f)) { actions() } } - if (scores != null) CapsuleScores(scores, Modifier.padding(start = 8.dp, end = 10.dp)) + CompositionLocalProvider(LocalPillButtons provides true) { + Box(Modifier.weight(1f).onSizeChanged { noActions = it.height == 0 }) { actions() } + } + shown?.let { CapsuleScores(it, Modifier.padding(start = 8.dp, end = 10.dp)) } } } @@ -361,41 +387,95 @@ private fun GameTabBar( ) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current + val scroll = rememberScrollState() + val spans = remember(tabs.size) { androidx.compose.runtime.mutableStateListOf<IntRange?>(*arrayOfNulls<IntRange>(tabs.size)) } + var tabHeight by remember { mutableStateOf(0) } + var viewport by remember { mutableStateOf(0) } + LaunchedEffect(selected, viewport) { + val span = spans.getOrNull(selected) ?: return@LaunchedEffect + if (viewport > 0) scroll.animateScrollTo((span.first + span.last) / 2 - viewport / 2) + } Row(modifier.fillMaxWidth().glass(CircleShape).padding(4.dp), verticalAlignment = Alignment.CenterVertically) { if (bumpers) TabBarBumper("LB", stringResource(R.string.widgets_prev_tab), leading = true) { onSelect((selected + tabs.size - 1) % tabs.size) } - tabs.forEachIndexed { i, label -> - val on = i == selected - val src = remember { MutableInteractionSource() } - val hot = rememberHot(src) - val pick = { onSelect(i) } - Box( - contentAlignment = Alignment.Center, - modifier = Modifier.weight(1f) - .testTag("tab-$i") - .then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier) - .clip(CircleShape) - .background(if (on) pal.signal.copy(alpha = 0.3f) else if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) - .glideBorder(hot, CircleShape, pal.signal, if (on) pal.signal.copy(alpha = 0.5f) else Color.Transparent) - .hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick) - .controllerConfirm(onClick = pick) - .padding(horizontal = 6.dp, vertical = if (compact) 8.dp else 10.dp), - ) { - Text( - label, fontSize = if (compact) 13.sp else 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, - color = if (on || hot) colors.onBackground else colors.onSurfaceVariant, - ) + androidx.compose.foundation.layout.BoxWithConstraints(Modifier.weight(1f).clip(if (bumpers) RoundedCornerShape(BumperFlat) else CircleShape).onSizeChanged { viewport = it.width }) { + val share = maxWidth / tabs.size.coerceAtLeast(1) + Box(Modifier.horizontalScroll(scroll)) { + spans.getOrNull(selected)?.takeIf { tabHeight > 0 }?.let { span -> + TabHighlight(span, tabHeight, flatStart = bumpers && selected == 0, flatEnd = bumpers && selected == tabs.lastIndex) + } + Row(verticalAlignment = Alignment.CenterVertically) { + tabs.forEachIndexed { i, label -> + val on = i == selected + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val pick = { onSelect(i) } + val shape = tabShape(flatStart = bumpers && i == 0, flatEnd = bumpers && i == tabs.lastIndex) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.widthIn(min = share) + .onGloballyPositioned { c -> val x = c.positionInParent().x.toInt(); val r = x..(x + c.size.width); if (spans[i] != r) spans[i] = r; tabHeight = c.size.height } + .testTag("tab-$i") + .then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier) + .clip(shape) + .background(if (hot && !on) pal.signal.copy(alpha = 0.14f) else Color.Transparent) + .glideBorder(hot, shape, pal.signal) + .hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick) + .controllerConfirm(onClick = pick) + .padding(horizontal = 12.dp, vertical = if (compact) 8.dp else 10.dp), + ) { + Text( + label, fontSize = if (compact) 13.sp else 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis, + color = if (on || hot) colors.onBackground else colors.onSurfaceVariant, + ) + } + } + } } } if (bumpers) TabBarBumper("RB", stringResource(R.string.widgets_next_tab), leading = false) { onSelect((selected + 1) % tabs.size) } } } +private val BumperFlat = 7.dp + +@Composable +private fun TabHighlight(span: IntRange, height: Int, flatStart: Boolean, flatEnd: Boolean) { + val pal = LocalPalette.current + val density = LocalDensity.current + val spring = Motion.sp<Float>(0.8f, Spring.StiffnessMediumLow) + val x by animateFloatAsState(span.first.toFloat(), spring, label = "tabX") + val width by animateFloatAsState((span.last - span.first).toFloat(), spring, label = "tabWidth") + val start by animateFloatAsState(if (flatStart) 1f else 0f, spring, label = "tabFlatStart") + val end by animateFloatAsState(if (flatEnd) 1f else 0f, spring, label = "tabFlatEnd") + with(density) { + val round = (height / 2f).toDp() + val shape = RoundedCornerShape( + topStart = androidx.compose.ui.unit.lerp(round, BumperFlat, start), topEnd = androidx.compose.ui.unit.lerp(round, BumperFlat, end), + bottomEnd = androidx.compose.ui.unit.lerp(round, BumperFlat, end), bottomStart = androidx.compose.ui.unit.lerp(round, BumperFlat, start), + ) + Box( + Modifier.offset { androidx.compose.ui.unit.IntOffset(x.toInt(), 0) } + .size(width.toDp(), height.toDp()) + .clip(shape).background(pal.signal.copy(alpha = 0.3f)).border(1.dp, pal.signal.copy(alpha = 0.5f), shape), + ) + } +} + +private fun tabShape(flatStart: Boolean, flatEnd: Boolean): androidx.compose.ui.graphics.Shape { + if (!flatStart && !flatEnd) return CircleShape + val flat = androidx.compose.foundation.shape.CornerSize(BumperFlat) + val round = androidx.compose.foundation.shape.CornerSize(50) + val start = if (flatStart) flat else round + val end = if (flatEnd) flat else round + return RoundedCornerShape(topStart = start, topEnd = end, bottomEnd = end, bottomStart = start) +} + @Composable private fun TabBarBumper(label: String, description: String, leading: Boolean, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val round = 22.dp - val flat = 7.dp + val flat = BumperFlat val cap = if (leading) RoundedCornerShape(round, flat, flat, round) else RoundedCornerShape(flat, round, round, flat) Box( contentAlignment = Alignment.Center, @@ -427,12 +507,17 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) { ) } +internal enum class ActionPart { ALL, LEAD, REST } + @Composable internal fun GameActions( store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?, s: FrontEndState, a: FrontEndActions, leadOn: Modifier, compactMenu: Boolean = false, inStore: Boolean = false, + part: ActionPart = ActionPart.ALL, ) { val ctx = LocalContext.current + val lead = part != ActionPart.REST + val rest = part != ActionPart.LEAD val storeKey = if (store != null && id != null) "${store.id}:$id" else null val rawDownload = storeKey?.let { StoresState.download(it) } val download = rawDownload?.takeIf { it.isActive } @@ -442,127 +527,133 @@ internal fun GameActions( Actions { when { s.shortcutPicker && game != null -> { - PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) } - FileButtons(game, a) + if (lead) PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) } + if (rest) FileButtons(game, a) } !cloud && (game != null || installed != null) -> { val gone = storeKey?.let { StoresState.uninstalling[it] } val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id) val preparing = (game?.launchKey ?: storeKey)?.let { it in s.preparingGames } == true - PrimaryButton( + if (lead) PrimaryButton( stringResource(if (preparing) R.string.store_starting else R.string.stores_play), enabled = !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false), main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn, ) { if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(store, id, s, a) } - if (game != null) { - if (compactMenu) GameMoreMenu(game, a) else { - FileButtons(game, a) - GameShortcutMenu(game, a) - } - } - if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null) - if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null) - if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null) - if (inStore && store == Store.GAMEJOLT && installed != null) { - SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) { - openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) }) - } - } - if (store == Store.EA && installed != null) EaUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null) - if (store == Store.GOG && installed != null) GogMaintenanceActions(installed) - if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item) - if (store == Store.XBOX && installed != null && id != null) { - SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) { - runCatching { XboxBackend.update(ctx, installed) } - .onFailure { StoresState.problems[Store.XBOX] = it.message ?: ctx.getString(R.string.stores_xbox_close_first) } - } - SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) } - } - if (store == Store.BATTLENET) { - if (installed != null && id != null) { - LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) } - if (download != null) { - SteadyDownloadChip(download) - if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) } - else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) } - } else if (BattleNetInstall.updates[id] == true) { - SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) } + if (rest) { + if (game != null) { + if (compactMenu) GameMoreMenu(game, a) else { + FileButtons(game, a) + GameShortcutMenu(game, a) } } - SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() } - } - if (game != null && !compactMenu) { - HideButton(hideKey(game), game) - EditArtButton(game) + if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null) + if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null) + if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null) + if (inStore && store == Store.GAMEJOLT && installed != null) { + SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) { + openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) }) + } + } + if (store == Store.EA && installed != null) EaUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null) + if (store == Store.GOG && installed != null) GogMaintenanceActions(installed) + if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item) + if (store == Store.XBOX && installed != null && id != null) { + SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) { + runCatching { XboxBackend.update(ctx, installed) } + .onFailure { StoresState.problems[Store.XBOX] = it.message ?: ctx.getString(R.string.stores_xbox_close_first) } + } + SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) } + } + if (store == Store.BATTLENET) { + if (installed != null && id != null) { + LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) } + if (download != null) { + SteadyDownloadChip(download) + if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) } + else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) } + } else if (BattleNetInstall.updates[id] == true) { + SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) } + } + } + SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() } + } + if (game != null && !compactMenu) { + HideButton(hideKey(game), game) + EditArtButton(game) + } } } download != null -> { - SteadyDownloadChip(download) - if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) } - else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) } - ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) } + if (rest) SteadyDownloadChip(download) + if (lead) { + if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) } + else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) } + } + if (rest) ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) } } failed != null -> { - ActionChip(stringResource(R.string.stores_dl_failed), ok = false) - PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { + if (rest) ActionChip(stringResource(R.string.stores_dl_failed), ok = false) + if (lead) PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { if (item != null) StoresState.requestInstall(ctx, item) else DownloadQueue.retry(ctx, failed.key) } - ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) } + if (rest) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) } } cloud -> { val cloudId = game.storeId.orEmpty() - XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn) - if (item?.installable == true && item.xboxPc) { + if (lead) XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn) + if (rest && item?.installable == true && item.xboxPc) { SecondaryButton( if (StoresState.isUnfinished(item)) stringResource(R.string.stores_resume_install) else if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes)) else stringResource(R.string.stores_install), ) { StoresState.requestInstall(ctx, item) } } - if (item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) } - XboxLibraryButton(cloudId, item) + if (rest && item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) } + if (rest) XboxLibraryButton(cloudId, item) } - store == Store.BATTLENET && item != null -> InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } + store == Store.BATTLENET && item != null -> if (lead) InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> { - XboxStreamButton(item.id, item.title, main = true, modifier = leadOn) - XboxLibraryButton(item.id, item) + if (lead) XboxStreamButton(item.id, item.title, main = true, modifier = leadOn) + if (rest) XboxLibraryButton(item.id, item) } item?.installable == true && StoresState.isUnfinished(item) -> { - InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) } - ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) } + if (lead) InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) } + if (rest) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) } } item?.installable == true -> { - InstallButton( + if (lead) InstallButton( if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes)) else stringResource(R.string.stores_install), leadOn, ) { StoresState.requestInstall(ctx, item) } - if (store == Store.XBOX && item.xboxCloud) { + if (rest && store == Store.XBOX && item.xboxCloud) { XboxStreamButton(item.id, item.title) XboxLibraryButton(item.id, item) } - if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) } + if (rest && !item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) } } item != null && (item.store == Store.ITCH || item.store == Store.GAMEJOLT) && item.isFree -> { - InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } - SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) } + if (lead) InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) } + if (rest) SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) } } - item != null && item.isFree -> { + item != null && item.isFree -> if (lead) { val adding = StoresState.claiming[item.key] == true PrimaryButton(stringResource(if (adding) R.string.stores_claiming else R.string.stores_get_free), enabled = !adding, main = true, modifier = leadOn) { if (StoresState.canClaim(item)) StoresState.claim(ctx, item) { openStoreUrl(ctx, item) } else openStoreUrl(ctx, item) } } - item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } + item != null -> if (lead) PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } } - val entryKey = game?.let(::hideKey) ?: storeKey - if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game) - if (cloud && (download != null || failed != null)) { - XboxStreamButton(game.storeId.orEmpty(), game.name) - XboxLibraryButton(game.storeId.orEmpty(), item) + if (rest) { + val entryKey = game?.let(::hideKey) ?: storeKey + if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game) + if (cloud && (download != null || failed != null)) { + XboxStreamButton(game.storeId.orEmpty(), game.name) + XboxLibraryButton(game.storeId.orEmpty(), item) + } + BusyChip(s) } - BusyChip(s) } } @@ -956,13 +1047,26 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) { } @Composable -private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) { +private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, sessionRunning: Boolean, a: FrontEndActions) { var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) } - browsing?.let { AddonBrowserDialog(targets, it) { browsing = null } } + val curseForge = CurseForgeApp.find(UserAppsState.items) + val link = rememberCurseLink(curseForge, sessionRunning) + browsing?.let { AddonBrowserDialog(targets, it, curseForge, link) { browsing = null } } Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) { + CurseForgeEntry(a) targets.forEach { target -> - val names by produceState(emptyList<String>(), target.addOns, WowAddons.imports) { - value = withContext(Dispatchers.IO) { WowAddons.installed(target) } + val names by produceState(emptyList<WowAddons.Installed>(), target.addOns, WowAddons.imports) { + value = withContext(Dispatchers.IO) { WowAddons.details(target) } + } + val context = LocalContext.current + val updates by produceState(emptyMap<String, WowAddonCatalog.Addon>(), names) { + value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) } + } + val scanKey = link?.generation to WowAddons.imports + val managed by produceState(emptyMap<String, CurseForgeApp.Project>(), link, target.addOns, scanKey) { + value = if (link == null) emptyMap() else withContext(Dispatchers.IO) { + runCatching { CurseForgeApp.byFolder(link.installed(context, target, scanKey)) }.getOrDefault(emptyMap()) + } } if (targets.size > 1) SectionLabel(target.flavor) MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target } @@ -974,23 +1078,100 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: target.addOns.mkdirs() a.onBrowseFiles(target.addOns) } - names.forEach { name -> AddonRow(name, target, a) } + names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, link?.let { l -> managed[item.name.lowercase()]?.let { it to l } }) } } } } } @Composable -private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions) { +private fun CurseForgeEntry(a: FrontEndActions) { + val ctx = LocalContext.current + val name = stringResource(R.string.addons_source_curse) + LaunchedEffect(Unit) { UserAppsState.refresh(ctx) } + val app = CurseForgeApp.find(UserAppsState.items) + val idle = UserAppsState.working == null + if (app == null) { + MenuItem(stringResource(R.string.content_install_named, name), checked = false, enabled = idle && !SessionState.running) { + UserAppsState.add(ctx, CurseForgeApp.request(), name) + } + } else { + var asking by remember(app.key) { mutableStateOf(false) } + var checked by remember { mutableStateOf<String?>(null) } + val checkKey = app.key + "@" + app.version + LaunchedEffect(checkKey, UserAppsState.checking) { + if (UserAppsState.checking == null && checked != checkKey) { + checked = checkKey + UserAppsState.checkUpdate(ctx, app) + } + } + val update = (UserAppsState.updates[app.key] as? UserApps.UpdateCheck.Available)?.release + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + MenuItem( + stringResource(R.string.user_apps_open, name), checked = false, enabled = idle, + detail = app.version, modifier = Modifier.weight(1f), + ) { a.onUserApp(app) } + DeleteButton(name, enabled = idle && !SessionState.running) { asking = true } + } + if (update != null) MenuItem(stringResource(R.string.user_apps_update_to, update.tag), checked = false, enabled = idle && !SessionState.running) { + UserAppsState.update(ctx, app, update) + } + (UserAppsState.updates[app.key] as? UserApps.UpdateCheck.Failed)?.let { failed -> + MenuItem(stringResource(R.string.user_apps_check_updates), checked = false, enabled = idle && UserAppsState.checking == null, detail = failed.message) { + UserAppsState.checkUpdate(ctx, app) + } + } + if (asking) ConfirmDialog( + title = stringResource(R.string.flathub_remove_title, name), + text = stringResource(R.string.flathub_remove_note), + confirm = stringResource(R.string.user_apps_remove), + onConfirm = { asking = false; UserAppsState.remove(ctx, app) }, + onDismiss = { asking = false }, + ) + } + if (UserAppsState.working == name || (UserAppsState.lastError?.startsWith(name) == true)) UserAppsProgress() +} + +@Composable +internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, curse: Pair<CurseForgeApp.Project, CurseLink>? = null) { + val name = item.name + val update = wowiUpdate.takeIf { curse == null } + val outdated = update != null || curse?.first?.update == true var asking by remember(target.addOns, name) { mutableStateOf(false) } + var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) } + val context = LocalContext.current + val scope = rememberCoroutineScope() val delete = stringResource(R.string.common_delete) + val colors = MaterialTheme.colorScheme Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) { - Text(name, fontSize = 14.sp, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) - if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true } + Column(Modifier.weight(1f)) { + Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + val detail = listOfNotNull(item.version, if (outdated) stringResource(R.string.upd_available) else null).joinToString(" · ") + if (detail.isNotEmpty()) Text( + progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp, + color = if (outdated) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } + if (outdated && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) { + progress = 0 + scope.launch { + val message = withContext(Dispatchers.IO) { + if (curse != null) { + val (project, link) = curse + val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false) + WowAddons.changed() + if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name) + } else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first } + } + progress = null + if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show() + } + } + if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true } } if (asking) ConfirmDialog( - title = stringResource(R.string.games_delete_addon_title, name), + title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name), text = stringResource(R.string.games_delete_addon_body), - confirm = delete, + confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete, onConfirm = { a.onAddonDelete(target, name) }, onDismiss = { asking = false }, ) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt index 39c6b07768..6042598d8f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt @@ -58,6 +58,7 @@ import coil.size.Precision import kotlin.math.max internal val LocalPillButtons = compositionLocalOf { false } +internal val LocalGradientOutline = compositionLocalOf { false } internal class GlassBackdrop { var painter: Painter? = null diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt index 3eb42902b3..275c9361ef 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameResources.kt @@ -60,7 +60,7 @@ internal fun gameResources(title: String, game: Library.SteamGame?): List<GameRe internal fun GameResourcesRow(title: String, game: Library.SteamGame?, modifier: Modifier = Modifier) { val links = remember(title, game) { gameResources(title, game) } if (links.isEmpty()) return - FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) { + FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { links.forEach { ResourceLink(it) } } } @@ -79,14 +79,14 @@ private fun ResourceLink(link: GameResource) { val tint = if (hot) pal.signal else pal.onSurfaceVariant Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp), - modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 44.dp).clip(shape) + modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 34.dp).clip(shape) .background(if (hot) pal.signal.copy(alpha = 0.14f) else if (glass) Color.White.copy(alpha = 0.07f) else Color.Transparent) .glideBorder(hot, shape, pal.signal, restColor = if (glass) Color.White.copy(alpha = 0.12f) else Color.Transparent) .semantics { contentDescription = description } .hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = open) - .controllerConfirm(onClick = open).padding(horizontal = if (glass) 14.dp else 8.dp), + .controllerConfirm(onClick = open).padding(horizontal = if (glass) 11.dp else 8.dp), ) { - Text(label, fontSize = if (glass) 13.sp else 12.sp, fontWeight = FontWeight.Medium, color = if (glass && !hot) MaterialTheme.colorScheme.onBackground else tint, maxLines = 1) + Text(label, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = if (glass && !hot) MaterialTheme.colorScheme.onBackground else tint, maxLines = 1) Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = tint.copy(alpha = 0.65f), modifier = Modifier.size(11.dp)) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt index f35d3daa46..47952e8502 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt @@ -46,8 +46,11 @@ internal class InputLayoutPreviewView(context: Context) : View(context) { private var sourceHeight = 563 fun update(layout: SavedInputLayout, role: InputRole) { sourceHeight = if (role == InputRole.PRIMARY) 563 else 870 - renderer.updateCustomLayout(layout.elements) - renderer.updateStyle(layout.style.copy(opacity = 100)) + val primary = role == InputRole.PRIMARY + val artwork = if (primary) PadKit.forOverlay(context, layout) else null + val elements = if (artwork != null) OnScreenLayout.editorElements(context, layout, 1000, sourceHeight) else layout.elements + renderer.updateCustomLayout(elements) + renderer.updateStyle(layout.style.copy(opacity = 100), artwork) renderer.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(sourceHeight, MeasureSpec.EXACTLY)) renderer.layout(0, 0, 1000, sourceHeight) contentDescription = layout.name diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt index 812557f368..2fe1346034 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt @@ -267,18 +267,14 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe } } InputPage.SOURCE -> { - if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) { - ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared), - listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), - SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), - oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() } - } if (layout != null) SettingsGroup(stringResource(R.string.ctrl_layout)) { if (layout.editable) InputNavigationRow(stringResource(R.string.input_edit_layout), layout.name, Modifier.testTag("input-surface-${role.name.lowercase()}")) { surface = true } else InputHint(layout.name) InputNavigationRow(stringResource(R.string.input_saved_layouts), stringResource(R.string.input_saved_layouts_hint)) { go(InputPage.LAYOUTS) } if (layout.editable) { - InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } } + if (PadKit.forOverlay(context, layout).let { kit -> role != InputRole.PRIMARY || kit == null || layout.elements.any { !kit.artwork(it) } }) { + InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } } + } SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1, format = { "$it%" }) { opacity -> update { it.withLayout(layout.copy(style = layout.style.copy(opacity = opacity))) } } for (button in layout.quickButtons) ToggleRow(host, "quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null, @@ -286,6 +282,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe } if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable)) } + if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) { + ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared), + listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), + SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), + oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() } + } SettingsGroup(stringResource(R.string.input_assign_actions)) { val users = library.usersOfBindings(preset.id) if (users.size > 1) InputHint(stringResource(R.string.input_shared_with, users.filterNot { it.id == profileId }.joinToString { it.name })) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt index 5b94225115..8f8e592cd2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt @@ -63,10 +63,17 @@ import com.droiddeck.launcher.session.SessionState private data class SurfaceSnapshot(val elements: List<InputSurfaceElement>, val actions: Map<String, InputAction>, val clicks: Map<String, InputAction>, val scale: Float, val aspect: Float) -private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int) { +private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int, + private val layout: SavedInputLayout) { private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale) val ids = generator(1f).elements().map { it.id }.toSet() - fun rescale(stored: List<InputSurfaceElement>, from: Float, to: Float) = generator(to).rescale(stored, generator(from)) + fun stock(scale: Float) = generator(scale).elements() + private fun placed(scale: Float) = OnScreenLayout.editorElements(context, + layout.copy(elements = stock(scale), aspect = 0f, rotated = emptyList(), scale = scale), width, height) + fun rescale(stored: List<InputSurfaceElement>, from: Float, to: Float) = + if (PadKit.forOverlay(context, layout) == null || OnScreenLayout.generatedSize(context, layout.copy(elements = stored, scale = from), width, height) != null) + generator(to).rescale(stored, generator(from)) + else rescaleBetween(stored, placed(from), placed(to), stock(from), stock(to)) fun reset(stored: List<InputSurfaceElement>) = generator(1f).regenerate(stored).associateBy { it.id }.let { placed -> stored.map { placed[it.id] ?: it } } } @@ -78,21 +85,28 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB var clicks by mutableStateOf(preset.clicks) var selected by mutableStateOf<String?>(null) var toolsExpanded by mutableStateOf(false) - var toolsX by mutableFloatStateOf(.02f) + var toolsX by mutableFloatStateOf(-1f) var toolsY by mutableFloatStateOf(.02f) var snap by mutableStateOf(snap) var adding by mutableStateOf(false) var properties by mutableStateOf(false) var clickProperties by mutableStateOf(false) var history by mutableStateOf<List<SurfaceSnapshot>>(emptyList()) + var canvas by mutableStateOf(IntSize.Zero) var layoutScale by mutableFloatStateOf(layout.scale) var aspect by mutableFloatStateOf(layout.aspect) private var scaleBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Float>?>(null) private var scaleValue by mutableIntStateOf(100) + private var pieceBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Int>?>(null) + private var pieceLayout: List<InputSurfaceElement>? = null + private val piece get() = element?.let { e -> (if (elements.any { it.id == e.id }) elements else shown).groupOf(e) }.orEmpty() + val scaleRange get() = if (piece.isEmpty()) 80..125 else 50..200 private val rescales get() = gamepad?.let { pad -> elements.any { it.id in pad.ids } } == true val scale get() = when { + piece.isNotEmpty() -> pieceBase?.takeIf { it.second == piece && pieceLayout == elements }?.third ?: 100 scaleBase?.second == elements -> scaleValue - rescales -> (layoutScale * 100).roundToInt() + rescales -> ((if (canvas.width > 0 && canvas.height > 0 && aspect > 0f && (aspect < 1f) != (canvasAspect < 1f)) + OnScreenLayout.oriented(layout, canvas.width, canvas.height).scale else layoutScale) * 100).roundToInt() else -> 100 } val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) }) @@ -102,18 +116,29 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB if (from <= 0f || aspect <= 0f || abs(from / aspect - 1f) < .01f) return placed return OnScreenLayout.fit(placed, from, 1f, (aspect * 1000).roundToInt().coerceAtLeast(1), 1000, Rect()) } - val element get() = elements.firstOrNull { it.id == selected } + val element get() = elements.firstOrNull { it.id == selected } ?: shown.firstOrNull { it.id == selected } val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) } fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } } + private fun adoptDisplayedFrame(context: android.content.Context): Boolean { + if (canvas.width <= 0 || canvas.height <= 0 || shown.isEmpty() || aspect <= 0f || (aspect < 1f) == (canvasAspect < 1f)) return false + val open = toolsExpanded + beginEdit(shown, canvasAspect, gamepad?.let { GamepadScaler(context, canvas.width, canvas.height, layout) }) + toolsExpanded = open + return true + } + fun beginEdit(displayed: List<InputSurfaceElement>, aspect: Float, scaler: GamepadScaler? = gamepad) { checkpoint() + toolsExpanded = false elements = OnScreenLayout.editorFrame(layout.copy(elements = elements), displayed) + if (this.aspect > 0f && aspect > 0f && (this.aspect < 1f) != (aspect < 1f)) layoutScale = OnScreenLayout.oriented(layout, (aspect * 1000).roundToInt(), 1000).scale this.aspect = aspect scaler?.let { gamepad = it } } - fun scaleAll(percent: Int) { - val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() } + fun scaleAll(context: android.content.Context, percent: Int) { + val adopted = adoptDisplayedFrame(context) + val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { if (!adopted) checkpoint() } val factor = percent / 100f val pad = gamepad elements = if (base.third > 0f && pad != null) { @@ -123,7 +148,65 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB } else base.first.scaled(factor) scaleValue = percent; scaleBase = Triple(base.first, elements, base.third) } - fun resetPositions() { positioned?.let { checkpoint(); elements = it; if (rescales) layoutScale = 1f } } + fun scaleSelected(context: android.content.Context, percent: Int) { + val id = selected ?: return + val adopted = adoptDisplayedFrame(context) + val base = pieceBase?.takeIf { it.second == piece && pieceLayout == elements } ?: run { + if (!adopted && canvas.width > 0 && canvas.height > 0 && shown.isNotEmpty()) { + val open = toolsExpanded + beginEdit(shown, canvasAspect) + toolsExpanded = open + } else if (!adopted) checkpoint() + val start = elements.firstOrNull { it.id == id }?.let { elements.groupOf(it) } ?: return + Triple(start, start, 100) + } + val resized = base.first.resizedAroundCentre(percent / 100f) + val byId = resized.associateBy { it.id } + elements = elements.map { byId[it.id] ?: it } + pieceBase = Triple(base.first, resized, percent) + pieceLayout = elements + } + var shown by mutableStateOf<List<InputSurfaceElement>>(emptyList()) + private val canvasAspect get() = canvas.width.toFloat() / canvas.height.coerceAtLeast(1) + + private fun stored(id: String): Boolean { + if (elements.any { it.id == id }) return true + if (shown.none { it.id == id }) return false + beginEdit(shown, canvasAspect) + return true + } + + fun missing(context: android.content.Context): List<InputSurfaceElement> { + val pad = gamepad ?: return emptyList() + if (canvas.width <= 0 || canvas.height <= 0) return emptyList() + val ids = shown.map { it.id }.toSet() + return OnScreenLayout.editorElements(context, layout.copy(elements = pad.stock(layoutScale), aspect = 0f, rotated = emptyList(), scale = layoutScale), + canvas.width, canvas.height).filter { it.id !in ids } + } + + fun restore(context: android.content.Context, element: InputSurfaceElement) { + val legacy = gamepad?.stock(layoutScale)?.firstOrNull { it.id == element.id } + val generated = OnScreenLayout.generatedSize(context, layout.copy(elements = elements), canvas.width, canvas.height) != null + if (generated && legacy != null) { checkpoint(); elements = elements + legacy } + else { beginEdit(shown, canvasAspect); elements = elements + element } + if (element.id == "builtin:keyboard" && actions[element.id] == null) actions = actions + (element.id to InputAction.Command(InputCommand.KEYBOARD)) + selected = element.id + } + + fun remove(id: String) { + if (elements.any { it.id == id }) checkpoint() else stored(id) + elements = elements.filterNot { it.id == id }; actions = actions - id; clicks = clicks - id; selected = null + } + + fun update(element: InputSurfaceElement) { + stored(element.id) + elements = elements.map { if (it.id == element.id) element else it } + } + + fun resetPositions(context: android.content.Context) { + val adopted = adoptDisplayedFrame(context) + positioned?.let { if (!adopted) checkpoint(); elements = it; if (rescales) layoutScale = 1f } + } fun action(e: InputSurfaceElement) = preset.copy(elements = actions).action(e) fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e) } @@ -142,7 +225,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> val (display, metrics) = InputLibraries.primaryDisplay(context) val gamepad = savedLayout.elements.takeIf { e -> e.any { it.id.startsWith("legacy:") } }?.let { val (w, h) = OnScreenLayout.generatedSize(context, savedLayout, metrics.widthPixels, metrics.heightPixels) ?: (metrics.widthPixels to metrics.heightPixels) - GamepadScaler(display, w, h) + GamepadScaler(display, w, h, savedLayout) } val defaults = InputLibraries.defaultPositions(context, library, savedLayout) SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context)) @@ -166,7 +249,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> InputLibraries.update(context) { latest -> val l = latest.layouts.first { it.id == savedLayout.id } val p = latest.preset(savedBindings.id) - latest.withLayout(l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } }, + latest.withLayout(OnScreenLayout.withFrame(context, l, draft.elements, draft.aspect, draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } }, clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } })) } }.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) } @@ -225,7 +308,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> else "${library.profile(profile).name} · ${roleLabel(role)}", onSave = { action -> draft.checkpoint() if (draft.clickProperties) draft.clicks = draft.clicks + (element.id to action) else draft.actions = draft.actions + (element.id to action) - draft.elements = draft.elements.map { if (it.id == element.id) properties.copy(name = properties.name.trim().ifBlank { element.name }) else it } + draft.update(properties.copy(name = properties.name.trim().ifBlank { element.name })) draft.properties = false }) } @@ -245,7 +328,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> } } } - if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column { + if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column(Modifier.verticalScroll(rememberScrollState())) { for (kind in InputElementKind.entries) PadTextButton(onClick = { draft.checkpoint() val w = if (kind.control.dimensions == 2) .4f else .2f val h = .3f @@ -253,6 +336,11 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> val element = InputSurfaceElement(kind.control, (1f - w) / 2, (1f - h) / 2, w, h, newInputId(), kind, name) draft.elements = draft.elements + element; draft.selected = element.id draft.adding = false; draft.toolsExpanded = false }) { Text(stringResource(kind.label())) } + val missing = remember(draft.elements, draft.canvas) { draft.missing(context) } + if (missing.isNotEmpty()) HorizontalDivider() + for (element in missing) PadTextButton(onClick = { draft.restore(context, element); draft.adding = false; draft.toolsExpanded = false }) { + Text(PadKit.forOverlay(context, savedLayout)?.name(element.control)?.takeIf { element.name == element.control.label } ?: element.name) + } } }) if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text(stringResource(R.string.input_editor_discard)) }, confirmButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_ok)) } }, @@ -266,11 +354,13 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) { AndroidView(factory = { InputSurfaceEditorView(it) }, modifier = Modifier.fillMaxSize().testTag("input-layout-canvas"), update = { view -> view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13)) - view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout; view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap + view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout.copy(scale = draft.layoutScale); view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap view.isEnabled = !draft.properties && !draft.adding view.onSelect = { if (!draft.properties) draft.selected = it } - view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h) else null) } - view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } } + view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h, draft.layout) else null) } + view.onResize = { w, h -> draft.canvas = IntSize(w, h) } + view.onDisplayed = { draft.shown = it } + view.onChange = { changed -> if (!draft.properties) changed.associateBy { it.id }.let { byId -> draft.elements = draft.elements.map { byId[it.id] ?: it } } } }) } @@ -283,7 +373,8 @@ private fun FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeav val screenHeight = with(density) { maxHeight.toPx() } val margin = with(density) { 8.dp.toPx() } var panelSize by remember { mutableStateOf(IntSize.Zero) } - val x = (draft.toolsX * screenWidth).coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin)) + val x = (if (draft.toolsX < 0f) (screenWidth - panelSize.width) / 2f else draft.toolsX * screenWidth) + .coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin)) val y = (draft.toolsY * screenHeight).coerceIn(margin, (screenHeight - panelSize.height - margin).coerceAtLeast(margin)) val position by rememberUpdatedState(Offset(x, y)) val expandedWidth = minOf(420.dp, maxWidth - 16.dp) @@ -332,15 +423,15 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave) SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { draft.adding = true } SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() } - if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions() } + if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions(context) } Row(verticalAlignment = Alignment.CenterVertically) { Checkbox(draft.snap, { draft.snap = it; ControllerPrefs.setSnap(context, it) }) Text(stringResource(R.string.ctrl_editor_snap)) } PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave) } - if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, 80..125, step = 5, - format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(it) } + if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, draft.scaleRange, step = 5, + format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { if (draft.element != null) draft.scaleSelected(context, it) else draft.scaleAll(context, it) } } @OptIn(ExperimentalLayoutApi::class) @@ -352,9 +443,7 @@ private fun SurfaceSelection(draft: SurfaceDraft) { FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { PrimaryButton(stringResource(R.string.input_properties), compact = true) { draft.clickProperties = false; draft.properties = true } if (e.hasClick) SecondaryButton(stringResource(R.string.input_click_properties), compact = true) { draft.clickProperties = true; draft.properties = true } - SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { - draft.checkpoint(); draft.elements = draft.elements.filterNot { it.id == e.id }; draft.actions = draft.actions - e.id; draft.clicks = draft.clicks - e.id; draft.selected = null - } + SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(e.id) } } } ?: Text(stringResource(R.string.input_editor_hint)) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt index 1e21a245de..301747dc18 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt @@ -5,14 +5,20 @@ import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint +import android.graphics.Rect import android.view.HapticFeedbackConstants import android.view.MotionEvent import android.view.ViewConfiguration +import android.view.WindowInsets import android.widget.FrameLayout import com.droiddeck.launcher.input.OnScreenLayout +import com.droiddeck.launcher.input.PadKit import com.droiddeck.launcher.input.SavedInputLayout import com.droiddeck.launcher.input.InputSurfaceElement import com.droiddeck.launcher.input.InputSurfaceStyle +import com.droiddeck.launcher.input.dpadPiece +import com.droiddeck.launcher.input.frame +import com.droiddeck.launcher.input.groupOf import com.droiddeck.launcher.input.snapSurfaceElement import kotlin.math.abs @@ -22,9 +28,14 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { var aspect = 1f set(value) { field = value; refreshElements(); invalidate() } var sourceLayout: SavedInputLayout? = null - set(value) { field = value; refreshElements(); invalidate() } + set(value) { + field = value + updatePreviewStyle() + refreshElements() + invalidate() + } var style = InputSurfaceStyle() - set(value) { field = value; preview.updateStyle(value) } + set(value) { field = value; updatePreviewStyle() } var snap = true set(value) { field = value; if (!value) clearGuides() } private var guideX: Float? = null @@ -33,11 +44,13 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { set(value) { field = value; invalidate() } var onSelect: (String?) -> Unit = {} var onBeginEdit: (List<InputSurfaceElement>, Int, Int) -> Unit = { _, _, _ -> } - var onChange: (InputSurfaceElement) -> Unit = {} + var onChange: (List<InputSurfaceElement>) -> Unit = {} + var onResize: (Int, Int) -> Unit = { _, _ -> } + var onDisplayed: (List<InputSurfaceElement>) -> Unit = {} private val preview = InputSurfaceView(context) private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density } private val radius = 14 * resources.displayMetrics.density - private var original: InputSurfaceElement? = null + private var original: List<InputSurfaceElement> = emptyList() private var downX = 0f private var downY = 0f private var corner = 0 @@ -50,16 +63,39 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { addView(preview, LayoutParams(-1, -1)) } + private fun updatePreviewStyle() { + preview.updateStyle(style, PadKit.forOverlay(context, sourceLayout)) + } + + private var safe = Rect() + private var frameWidth = 0 + private var frameHeight = 0 + private fun refreshElements() { visibleElements = sourceLayout?.let { layout -> - OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), width, height) + OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), frameWidth, frameHeight, safe = safe) } ?: elements preview.updateCustomLayout(visibleElements) + onDisplayed(visibleElements) + } + + override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets { + val fresh = OnScreenLayout.safeInsets(insets, false) + if (fresh != safe) { safe = fresh; refreshElements(); invalidate() } + return super.onApplyWindowInsets(insets) + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec) + if (measuredWidth == frameWidth && measuredHeight == frameHeight) return + frameWidth = measuredWidth; frameHeight = measuredHeight + refreshElements() + super.onMeasure(widthMeasureSpec, heightMeasureSpec) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) - refreshElements() + onResize(w, h) } override fun dispatchDraw(canvas: Canvas) { @@ -67,13 +103,15 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { paint.style = Paint.Style.STROKE guideX?.let { canvas.drawLine(width * it, 0f, width * it, height.toFloat(), paint) } guideY?.let { canvas.drawLine(0f, height * it, width.toFloat(), height * it, paint) } - val e = visibleElements.firstOrNull { it.id == selected } ?: return + val e = visibleElements.firstOrNull { it.id == selected }?.let { visibleElements.groupOf(it).frame() } ?: return val l = width * e.x; val t = height * e.y; val r = l + width * e.width; val b = t + height * e.height paint.style = Paint.Style.STROKE; canvas.drawRect(l, t, r, b, paint) paint.style = Paint.Style.FILL for (x in listOf(l, r)) for (y in listOf(t, b)) canvas.drawCircle(x, y, radius / 3, paint) } + private fun contains(e: InputSurfaceElement, x: Float, y: Float) = x / width in e.x..(e.x + e.width) && y / height in e.y..(e.y + e.height) + private fun clearGuides() { guideX = null; guideY = null; invalidate() } override fun onInterceptTouchEvent(event: MotionEvent) = true @@ -85,7 +123,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { MotionEvent.ACTION_DOWN -> { clearGuides() downX = event.x; downY = event.y; dragging = false; corner = 0 - val current = visibleElements.firstOrNull { it.id == selected } + val current = visibleElements.firstOrNull { it.id == selected }?.let { visibleElements.groupOf(it).frame() } if (current != null) { val left = width * current.x; val top = height * current.y val right = left + width * current.width; val bottom = top + height * current.height @@ -93,13 +131,16 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { val vertical = if (abs(downY - top) < radius) 4 else if (abs(downY - bottom) < radius) 8 else 0 if (horizontal != 0 && vertical != 0) corner = horizontal or vertical } - original = if (corner != 0) current else visibleElements.asReversed().firstOrNull { - downX / width in it.x..(it.x + it.width) && downY / height in it.y..(it.y + it.height) - } - selected = original?.id; onSelect(selected) + val touched = if (corner != 0) visibleElements.firstOrNull { it.id == selected } + else visibleElements.asReversed().firstOrNull { contains(it, downX, downY) } + ?: visibleElements.filter { it.dpadPiece }.takeIf { it.isNotEmpty() && contains(it.frame(), downX, downY) } + ?.let { pad -> pad.firstOrNull { it.id == selected } ?: pad.first() } + original = touched?.let { visibleElements.groupOf(it) }.orEmpty() + selected = touched?.id; onSelect(selected) } MotionEvent.ACTION_MOVE -> { - val e = original ?: return true + if (original.isEmpty()) return true + val e = original.frame() if (!dragging && abs(event.x - downX) + abs(event.y - downY) > ViewConfiguration.get(context).scaledTouchSlop) { dragging = true; onBeginEdit(visibleElements, width, height) } @@ -107,20 +148,24 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { val dx = (event.x - downX) / width; val dy = (event.y - downY) / height val next = if (corner == 0) e.copy(x = (e.x + dx).coerceIn(0f, 1f - e.width), y = (e.y + dy).coerceIn(0f, 1f - e.height)) else { - val left = if (corner and 1 != 0) (e.x + dx).coerceIn(0f, e.x + e.width - .03f) else e.x - val top = if (corner and 4 != 0) (e.y + dy).coerceIn(0f, e.y + e.height - .03f) else e.y - val right = if (corner and 2 != 0) (e.x + e.width + dx).coerceIn(left + .03f, 1f) else e.x + e.width - val bottom = if (corner and 8 != 0) (e.y + e.height + dy).coerceIn(top + .03f, 1f) else e.y + e.height + val minW = (.03f * e.width / original.minOf { it.width }).coerceIn(.03f, e.width.coerceAtLeast(.03f)) + val minH = (.03f * e.height / original.minOf { it.height }).coerceIn(.03f, e.height.coerceAtLeast(.03f)) + val left = if (corner and 1 != 0) (e.x + dx).coerceIn(0f, (e.x + e.width - minW).coerceAtLeast(0f)) else e.x + val top = if (corner and 4 != 0) (e.y + dy).coerceIn(0f, (e.y + e.height - minH).coerceAtLeast(0f)) else e.y + val right = if (corner and 2 != 0) (e.x + e.width + dx).coerceIn((left + minW).coerceAtMost(1f), 1f) else e.x + e.width + val bottom = if (corner and 8 != 0) (e.y + e.height + dy).coerceIn((top + minH).coerceAtMost(1f), 1f) else e.y + e.height e.copy(x = left, y = top, width = right - left, height = bottom - top).bounded() } - val aligned = if (snap) snapSurfaceElement(next, visibleElements.filter { it.id != e.id }, 9 * resources.displayMetrics.density / width, + val aligned = if (snap) snapSurfaceElement(next, visibleElements.filter { v -> original.none { it.id == v.id } }, 9 * resources.displayMetrics.density / width, 9 * resources.displayMetrics.density / height, corner) else null if (aligned != null && (aligned.x != null && aligned.x != guideX || aligned.y != null && aligned.y != guideY)) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) guideX = aligned?.x; guideY = aligned?.y - onChange(aligned?.element ?: next) + val f = aligned?.element ?: next + val sx = f.width / e.width; val sy = f.height / e.height + onChange(original.map { it.copy(x = f.x + (it.x - e.x) * sx, y = f.y + (it.y - e.y) * sy, width = it.width * sx, height = it.height * sy) }) invalidate() } - MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { original = null; dragging = false; clearGuides() } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { original = emptyList(); dragging = false; clearGuides() } } return true } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt index 0058224c01..f06c43851c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt @@ -37,8 +37,11 @@ import com.droiddeck.launcher.input.InputButtonIcons import com.droiddeck.launcher.input.InputButtonShape import com.droiddeck.launcher.input.InputButtonImages import com.droiddeck.launcher.input.PadBridge +import com.droiddeck.launcher.input.PadKit +import com.droiddeck.launcher.input.ThrottledRedraw import com.droiddeck.launcher.input.pcKeyLabel import com.droiddeck.launcher.session.SessionPrefs +import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.hypot import kotlin.math.min @@ -56,6 +59,10 @@ class InputSurfaceView( private val elementSources = ArrayList<InputSurfaceSource>() private var customCanvas: ViewGroup? = null private val owners = HashMap<Int, View>() + private var artwork: PadKit? = null + private val art by lazy(LazyThreadSafetyMode.NONE) { PadArt(context) } + private var artworkDpad = emptyList<HoldButton>() + private val artworkDpadBounds = RectF() private var requestedLayout = customLayout init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) } @@ -134,12 +141,16 @@ class InputSurfaceView( } } - fun updateStyle(style: InputSurfaceStyle) { - if (surfaceStyle == style) return + internal fun updateStyle(style: InputSurfaceStyle, artwork: PadKit? = null) { + if (surfaceStyle == style && this.artwork == artwork) return val relayout = surfaceStyle.hidden != style.hidden surfaceStyle = style + this.artwork = artwork if (relayout) updateCustomLayout(requestedLayout) - customCanvas?.let { canvas -> for (i in 0 until canvas.childCount) styleElement(canvas.getChildAt(i)) } + customCanvas?.let { canvas -> + for (i in 0 until canvas.childCount) styleElement(canvas.getChildAt(i)) + canvas.invalidate() + } } private fun styleElement(view: View) { @@ -173,6 +184,7 @@ class InputSurfaceView( } private fun renderCustom(pad: PadBridge?) { + artworkDpad = emptyList() val canvas = object : ViewGroup(context) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val layout = customLayout @@ -190,6 +202,21 @@ class InputSurfaceView( val x = (width * e.x).toInt(); val y = (height * e.y).toInt() child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight) } + updateArtworkDpad(this) + } + + override fun dispatchDraw(canvas: Canvas) { + val kit = artwork + if (kit != null && artworkDpad.isNotEmpty()) { + val alpha = (artworkDpad.first().alpha * 255f).toInt() + val saved = if (alpha == 255) canvas.save() + else canvas.saveLayerAlpha(artworkDpadBounds, alpha) + canvas.translate(artworkDpadBounds.left, artworkDpadBounds.top) + val held = artworkDpad.foldIndexed(0) { i, bits, button -> if (button.highlighted) bits or (1 shl i) else bits } + art.dpad(canvas, artworkDpadBounds.width(), artworkDpadBounds.height(), kit, held) + canvas.restoreToCount(saved) + } + super.dispatchDraw(canvas) } } canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || adaptive(it)) } @@ -197,7 +224,8 @@ class InputSurfaceView( val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } } canvas.addView(when (element.kind) { InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideWhenIdle && pad != null) - InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, source = source) + InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel, + stock = element.id == "legacy:${element.control.id}", source = source) InputElementKind.DPAD -> DirectionPad(context, element, source) else -> HoldButton(context, element, source) }.apply { tag = element; contentDescription = element.name; styleElement(this); source?.onStateChanged = { postInvalidate() } }) @@ -206,6 +234,34 @@ class InputSurfaceView( customCanvas = canvas } + private fun updateArtworkDpad(canvas: ViewGroup) { + val buttons = DIRECTIONS.mapNotNull { direction -> + val index = customLayout.indexOfFirst { element -> + element.control == direction && classic(element) && element.buttonShape == InputButtonShape.CIRCLE && + element.name == direction.label && element.icon == 0 && element.image.isEmpty() && + element.showLabel && !element.toggle && element.opacity == 1f + } + canvas.getChildAt(index) as? HoldButton + } + val previous = artworkDpad + artworkDpad = if (crossed(buttons)) buttons else emptyList() + if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() } + } + + private fun crossed(buttons: List<HoldButton>): Boolean { + if (buttons.size != DIRECTIONS.size) return false + val (up, right, down, left) = buttons + val centerX = (left.left + right.right) / 2f + val centerY = (up.top + down.bottom) / 2f + if (kotlin.math.abs((up.left + up.right) / 2f - centerX) > 2f || + kotlin.math.abs((down.left + down.right) / 2f - centerX) > 2f || + kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f || + kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f || + up.bottom >= down.top || left.right >= right.left) return false + artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat()) + return true + } + override fun onAttachedToWindow() { super.onAttachedToWindow() if (pad != null && elementSources.isEmpty()) { @@ -344,9 +400,20 @@ class InputSurfaceView( } private val imageRect = RectF() + val highlighted get() = if (element.toggle) source?.latched == true else down + override fun onDraw(canvas: Canvas) { - val lit = if (element.toggle) source?.latched == true else down + val lit = highlighted val classic = classic(element) + val kit = artwork + if (kit != null && element.image.isEmpty() && element.showLabel) { + if (this in artworkDpad) return + if (element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD) { + art.system(canvas, width.toFloat(), height.toFloat(), PadArt.Shape.ROUND, PadArt.Icon.KEYBOARD, lit) + return + } + if (kit.native(element) && art.button(canvas, width, height, element.control, kit, lit)) return + } drawSurface(canvas, lit, element.buttonShape, classic) val cx = width / 2f labelPaint.color = if (classic && tint != null) textColor(lit) else if (lit) ACCENT else TEXT @@ -364,7 +431,7 @@ class InputSurfaceView( if (classic && element.name == element.control.label) { val radius = min(width, height) / 2f val direction = DIRECTIONS.indexOf(element.control) - if (direction >= 0) { drawArrow(canvas, cx, height / 2f, radius * 0.34f, direction, labelPaint); return } + if (direction >= 0) { drawArrow(canvas, cx, height / 2f, radius * .34f, direction, labelPaint); return } val glyph = glyph(element.control) labelPaint.textSize = when { element.buttonShape == InputButtonShape.PILL -> height / 2f * 0.8f @@ -395,10 +462,12 @@ class InputSurfaceView( if (pressed) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY) if (!pressed && cancelled) source?.cancel() else source?.update(if (pressed) 1f else 0f) invalidate() + if (artwork != null && this in artworkDpad) customCanvas?.invalidate() } } - private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean = true, + private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean, + private val stock: Boolean, private val source: InputSurfaceSource? = null) : Surface(context) { private var gestureX = 0f private var gestureY = 0f @@ -421,18 +490,22 @@ class InputSurfaceView( private val glow = Paint(Paint.ANTI_ALIAS_FLAG) override fun onDraw(canvas: Canvas) { + if (!captioned || stock && artwork?.steam == true) { + art.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY) + return + } drawSurface(canvas, clicked) val cx = width / 2f val cy = height / 2f guide.strokeWidth = density - val reach = min(width, height) / 2f - 24 * density + val reach = (min(width, height) / 2f - 24 * density).coerceAtLeast(0f) canvas.drawCircle(cx, cy, reach, guide) canvas.drawCircle(cx, cy, reach / 2f, guide) canvas.drawLine(cx - reach, cy, cx + reach, cy, guide) canvas.drawLine(cx, cy - reach, cx, cy + reach, guide) captionPaint.textSize = 12 * density captionPaint.color = if (touching) ACCENT else TEXT_DIM - if (captioned) canvas.drawText((contentDescription?.toString() ?: if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad)).uppercase(), cx, 28 * density, captionPaint) + canvas.drawText((contentDescription?.toString() ?: if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad)).uppercase(), cx, 28 * density, captionPaint) if (touching) { val radius = 56 * density glow.shader = RadialGradient(fingerX, fingerY, radius, ACCENT_GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP) @@ -510,6 +583,10 @@ class InputSurfaceView( private var originY = 0f private var knobX = 0f private var knobY = 0f + private var drawnX = 0f + private var drawnY = 0f + private var atRim = false + private val redraw = ThrottledRedraw(this, STICK_REDRAW_MS) private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } private val knob = Paint(Paint.ANTI_ALIAS_FLAG) @@ -534,6 +611,18 @@ class InputSurfaceView( if (hideWhenIdle && !touching) return val cx = if (touching) originX else centreX() val cy = if (touching) originY else height / 2f + val kit = artwork + if (kit != null && classic(element)) { + val radius = min(width, height) / 2f - 2f * density + if (radius > 0f) { + art.stick(canvas, cx, cy, radius, kit, knobX, knobY, touching || clicking) + if (element.showLabel) { + labelPaint.color = TEXT + drawDirectionLabels(canvas, source, false, cx, cy, radius * .66f, radius * .34f, labelPaint) + } + return + } + } val color = tint if (classic(element) && color != null) { val radius = min(width, height) / 2f - 0.75f * density @@ -580,6 +669,7 @@ class InputSurfaceView( MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r) MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { touching = false + atRim = false val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL || event.flags and MotionEvent.FLAG_CANCELED != 0 travel = maxOf(travel, hypot(event.x - downX, event.y - downY)) lastUp = if (!clicking && !cancelled && event.eventTime - downAt <= STICK_TAP_MS && travel <= tapSlop) event.eventTime else 0L @@ -595,15 +685,27 @@ class InputSurfaceView( var dx = x - originX var dy = y - originY val length = hypot(dx, dy) - if (length > r) { dx *= r / length; dy *= r / length } - if (force || dx != knobX || dy != knobY) move(dx, dy, r) + val rim = length > r + if (rim) { dx *= r / length; dy *= r / length } + val reachedRim = rim && !atRim + atRim = rim + if (force || dx != knobX || dy != knobY) move(dx, dy, r, throttled = !force && !reachedRim, rim = rim) } - private fun move(dx: Float, dy: Float, r: Float) { + private fun move(dx: Float, dy: Float, r: Float, throttled: Boolean = false, rim: Boolean = false) { knobX = dx knobY = dy source?.update(dx / r, dy / r) - invalidate() + if (!throttled) { + redraw.cancel() + drawnX = dx + drawnY = dy + invalidate() + } else if (rim || abs(dx - drawnX) >= MIN_STICK_MOVE_PX || abs(dy - drawnY) >= MIN_STICK_MOVE_PX) { + drawnX = dx + drawnY = dy + redraw.request() + } } private fun setClick(down: Boolean) { @@ -616,6 +718,7 @@ class InputSurfaceView( override fun onDetachedFromWindow() { setClick(false) if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f) + redraw.cancel() super.onDetachedFromWindow() } } @@ -683,6 +786,8 @@ class InputSurfaceView( companion object { private const val CLICK_MS = 300L private const val STICK_TAP_MS = 200L + private const val STICK_REDRAW_MS = 33L + private const val MIN_STICK_MOVE_PX = 1f private const val CLASSIC_REACH = 0.5f private const val PANEL_REACH = 0.30f private const val HIT_SLACK = 0.25f diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index d901b1a68f..e940e7b47f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -90,6 +90,7 @@ import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.layout.layout import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext @@ -913,7 +914,6 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp), ) { - if (manage) ManageStoresChip() Box(Modifier.weight(1f).edgeFade(scroll).horizontalScroll(scroll)) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) { for (id in keys) { @@ -945,6 +945,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str } if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } + if (manage) ManageStoresChip() } } } @@ -1121,14 +1122,22 @@ internal fun ArtCard( } val showName = LibraryDisplay.title || hot val showDetail = LibraryDisplay.size || hot - if (showName || showDetail) Column( - verticalArrangement = Arrangement.spacedBy(1.dp), - modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth() - .background(Brush.verticalGradient(0f to Color.Transparent, 0.6f to Color.Black.copy(alpha = 0.78f), 1f to Color.Black.copy(alpha = 0.92f))) - .padding(start = 8.dp, end = 8.dp, top = 20.dp, bottom = if (download != null) 14.dp else 6.dp), - ) { - if (showName) Text(title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = if (hot) 2 else 1, overflow = TextOverflow.Ellipsis, lineHeight = 13.sp) - if (showDetail) detail() + if (showName || showDetail) { + val top = with(androidx.compose.ui.platform.LocalDensity.current) { 20.dp.roundToPx() } + val bottom = with(androidx.compose.ui.platform.LocalDensity.current) { (if (download != null) 14.dp else 6.dp).roundToPx() } + Column( + verticalArrangement = Arrangement.spacedBy(1.dp), + modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth() + .background(Brush.verticalGradient(0f to Color.Transparent, 0.6f to Color.Black.copy(alpha = 0.78f), 1f to Color.Black.copy(alpha = 0.92f))) + .layout { measurable, constraints -> + val inner = measurable.measure(constraints) + if (inner.height == 0) layout(inner.width, 0) {} else layout(inner.width, inner.height + top + bottom) { inner.place(0, top) } + } + .padding(horizontal = 8.dp), + ) { + if (showName) Text(title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = if (hot) 2 else 1, overflow = TextOverflow.Ellipsis, lineHeight = 13.sp) + if (showDetail) detail() + } } if (download != null) Box(Modifier.align(Alignment.BottomCenter).padding(start = 6.dp, end = 6.dp, bottom = 5.dp)) { ProgressBarThin(download.fraction, paused = download.state == DownloadState.PAUSED, verify = download.stage == DownloadStage.VERIFY) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt index 88b32cf5de..f58ee90807 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -126,6 +126,8 @@ internal object SheetTab { const val LIBRARY = "library" const val STEAM = "steam" const val FILES = "files" + const val DECKY = "decky" + const val BOOT_MOVIES = "boot-movies" } internal fun sheetTop(paneH: Float, buttonH: Float, minAbove: Float, ride: Float): Float = @@ -189,6 +191,7 @@ internal fun LiftHero( onOpenChange: (Boolean) -> Unit = {}, start: Dp = 44.dp, bottom: Dp = 44.dp, + onTextBounds: (Rect) -> Unit = {}, drop: DropSheetState? = null, overlay: @Composable BoxWithConstraintsScope.(lifted: () -> Float) -> Unit = {}, ) { @@ -573,7 +576,7 @@ internal fun LiftHero( } } - Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp)) { + Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp).onGloballyPositioned { onTextBounds(it.boundsInRoot()) }) { Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() } Spacer(Modifier.height(18.dp)) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt new file mode 100644 index 0000000000..c1c918ef32 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageDrawerPages.kt @@ -0,0 +1,95 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.DragHandle +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.activity.compose.BackHandler +import com.droiddeck.launcher.R + +@Composable +internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Modifier = Modifier, releaseSignal: Int = 0, onDone: () -> Unit) { + val ctx = LocalContext.current + val current by rememberUpdatedState(offeredNow) + val previewing = DevPreview.drawer != null + DisposableEffect(Unit) { onDispose { DrawerPages.heldFrom = null } } + DisposableEffect(previewing) { onDispose { if (previewing) DrawerPages.load(ctx) } } + val colors = MaterialTheme.colorScheme + BackHandler { onDone() } + Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(R.string.drawer_manage_pages), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, + color = colors.onBackground, modifier = Modifier.weight(1f), + ) + if (!DrawerPages.isDefault()) DrawerOutlineButton(stringResource(R.string.drawer_pages_reset)) { DrawerPages.reset(ctx) } + Spacer(Modifier.width(8.dp)) + DrawerOutlineButton(stringResource(R.string.drawer_pages_done), onClick = onDone) + } + SortableRows( + rows = { current.map { it.name } }, + commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) }, + movable = { it != SessionDrawerPage.MORE.name }, + rowHeight = STORE_ROW, handleWidth = STORE_HANDLE, + releaseSignal = releaseSignal, + onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } }, + onActivate = { name -> + current.firstOrNull { it.name == name }?.let { DrawerPages.setHidden(ctx, it, it !in DrawerPages.hidden) } + }, + ) { name, held, offset, hint, rowModifier, onFocus -> + val page = current.first { it.name == name } + // The same divider the launcher's Edit tabs uses: pages above it are tabs, pages below it are kept in More. + if (page == SessionDrawerPage.MORE) { MoreLine(STORE_ROW); return@SortableRows } + val shown = page !in DrawerPages.hidden + val pal = LocalPalette.current + val label = stringResource(page.title) + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + SortRowFrame(held, offset, rowModifier.testTag("drawer-page-row-$name"), hot, src, onFocus) { + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(width = STORE_HANDLE, height = STORE_ROW)) { + Icon(Icons.Filled.DragHandle, null, tint = if (held) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.weight(1f).alpha(if (shown) 1f else 0.5f), + ) { + Icon(page.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + if (hint != null) KeyHint("Y", hint) + ToggleSwitch( + shown, DrawerPages.hideable(page), label, + Modifier.testTag("drawer-page-shown-$name").focusProperties { canFocus = false }, + ) { DrawerPages.setHidden(ctx, page, !it) } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt index 7e732d4fe4..2b3a4a5413 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ManageStores.kt @@ -202,7 +202,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq if (!pad) return@LaunchedEffect repeat(60) { androidx.compose.runtime.withFrameNanos { } - if (holds || !open) return@LaunchedEffect + if (holds || !open || Steps.open) return@LaunchedEffect runCatching { inside.requestFocus() } } } @@ -210,7 +210,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq Modifier.width(width).fillMaxHeight() .onFocusChanged { holds = it.hasFocus } .focusRequester(inside) - .focusProperties { exit = { if (open) FocusRequester.Cancel else FocusRequester.Default } } + .focusProperties { exit = { if (open && !Steps.open) FocusRequester.Cancel else FocusRequester.Default } } .focusGroup() .background(MaterialTheme.colorScheme.background) .border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag(tag), @@ -221,8 +221,8 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq } } -private val STORE_ROW = 60.dp -private val STORE_HANDLE = 44.dp +internal val STORE_ROW = 60.dp +internal val STORE_HANDLE = 44.dp @Composable internal fun ManageStoresSheet() { @@ -302,7 +302,7 @@ private fun StoreSortRow( } @Composable -private fun SortRowFrame( +internal fun SortRowFrame( held: Boolean, offset: Float, modifier: Modifier, hot: Boolean, src: MutableInteractionSource, onFocus: (Boolean) -> Unit, content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit, ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 1cc0393388..3f561cae09 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -56,9 +56,12 @@ class DownloadRow(val key: String, val label: String, val detail: String, val pr class ModeSettings( val mode: String, val resolution: String, + val resolutionPortrait: String = com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE, val panelSize: Pair<Int, Int> = 1280 to 720, val hdr: Boolean, val hdrReason: String?, + val hdrDisplay: Boolean = true, + val zeroCopy: Boolean = true, val gpuDrivers: String? = null, val upscaler: Int = 0, val upscaleSharpness: Int = 75, @@ -75,6 +78,7 @@ class ModeSettings( val mic: Boolean?, val gameStorage: String? = null, val storageOptions: List<com.droiddeck.launcher.session.GameStorage.Option> = emptyList(), + val storageFat32: Boolean = false, val steamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Entry> = emptyList(), val foundSteamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Found> = emptyList(), val allFilesAccessMissing: Boolean = false, @@ -85,6 +89,7 @@ class ModeSettings( val picturePosition: String? = null, val integerScaling: Boolean? = null, val stretch16x9: Boolean? = null, + val avoidNotch: Boolean? = null, val steamClientArch: String? = null, val returnAfterGame: Boolean? = null, val shaderPrecache: Boolean? = null, @@ -109,11 +114,16 @@ class ModeSettings( val deckyDownloadingBinary: Boolean = false, val deckyEnabled: Boolean = false, val deckySessionRunning: Boolean = false, + val deckyPlugins: List<com.droiddeck.launcher.runtime.DeckyStore.Installed> = emptyList(), + val deckyStore: List<com.droiddeck.launcher.runtime.DeckyStore.Plugin>? = null, + val deckyStoreFailed: Boolean = false, ) class ModeSettingsActions( val onResolution: (String) -> Unit, + val onResolutionPortrait: (String) -> Unit = {}, val onHdr: (Boolean) -> Unit, + val onZeroCopy: (Boolean) -> Unit = {}, val onGpuDrivers: () -> Unit = {}, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, @@ -142,6 +152,7 @@ class ModeSettingsActions( val onPicturePosition: (String) -> Unit = {}, val onIntegerScaling: (Boolean) -> Unit = {}, val onStretch16x9: (Boolean) -> Unit = {}, + val onAvoidNotch: (Boolean) -> Unit = {}, val onSteamRepair: () -> Unit = {}, val onSteamClientArch: (String) -> Unit = {}, val onMangoapp: (Boolean) -> Unit = {}, @@ -164,6 +175,9 @@ class ModeSettingsActions( val onDeckyEnabled: (Boolean) -> Unit = {}, val onDeckyUninstall: () -> Unit = {}, val onPickDeckyPluginZip: () -> Unit = {}, + val onDeckyStoreRefresh: () -> Unit = {}, + val onDeckyStoreInstall: (com.droiddeck.launcher.runtime.DeckyStore.Plugin) -> Unit = {}, + val onDeckyRemove: (com.droiddeck.launcher.runtime.DeckyStore.Installed) -> Unit = {}, val onDismiss: () -> Unit, ) @@ -213,6 +227,8 @@ class SheetExtras( fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) { val steam = s.mode == SessionService.MODE_STEAM val host = rememberMenuHost() + if (tab == SheetTab.DECKY) { DeckyGroups(s, a, host); return } + if (tab == SheetTab.BOOT_MOVIES) { if (s.bootMovie != null) BootMovieGroup(s, a, host); return } Text( stringResource(when (s.mode) { SessionService.MODE_STEAM -> R.string.sheet_scope_steam @@ -229,9 +245,20 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: val controlsBelow = SessionPrefs.controlsBelowWanted(context, s.mode, if (portraitWindow) shortSide else longSide, if (portraitWindow) longSide else shortSide) val portrait = portraitWindow && !controlsBelow - val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution, portrait) + val sessionDisplay = com.droiddeck.launcher.session.SessionDisplay + val landscapeChoice = sessionDisplay.effectiveChoice(s.resolution, s.resolutionPortrait, false) + val portraitChoice = sessionDisplay.effectiveChoice(s.resolution, s.resolutionPortrait, true) + val activeChoice = if (portraitWindow) portraitChoice else landscapeChoice + val displaySize = sessionDisplay.resolveChoice(s.panelSize, activeChoice, portrait) SettingsGroup(stringResource(R.string.display_session)) { - ResolutionRow(host, s.resolution, s.panelSize, a.onResolution, portrait = portrait) + ResolutionRow(host, "resolution", stringResource(R.string.display_resolution_landscape), s.resolution, landscapeChoice, + com.droiddeck.launcher.session.SessionDisplay.LINK_PORTRAIT, + if (sessionDisplay.isLink(s.resolutionPortrait)) landscapeChoice else sessionDisplay.orientCustom(s.resolutionPortrait, false), + s.panelSize, a.onResolution, portrait = false) + ResolutionRow(host, "resolution-portrait", stringResource(R.string.display_resolution_portrait), s.resolutionPortrait, portraitChoice, + com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE, + if (sessionDisplay.isLink(s.resolution)) portraitChoice else sessionDisplay.orientCustom(s.resolution, true), + s.panelSize, a.onResolutionPortrait, portrait = true) s.picturePosition?.let { position -> ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null, listOf("top" to stringResource(R.string.display_position_top), @@ -243,13 +270,18 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: } if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) || com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) { - val canStretch = !com.droiddeck.launcher.session.SessionDisplay.isFollow(s.resolution) && + val canStretch = !com.droiddeck.launcher.session.SessionDisplay.isFollow(activeChoice) && com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize) ChoiceRow(host, "game-fit", stringResource(R.string.display_game_fit), stringResource(if (canStretch) R.string.display_game_fit_hint else R.string.display_game_fit_unavailable), listOf(false to stringResource(R.string.display_preserve), true to stringResource(R.string.display_stretch)), s.stretch16x9 && canStretch, enabled = canStretch, onPick = a.onStretch16x9) } + s.avoidNotch?.let { enabled -> + ToggleRow(host, "avoid-notch", stringResource(R.string.display_avoid_notch), + stringResource(R.string.display_avoid_notch_hint), checked = enabled, onChange = a.onAvoidNotch) + } + ToggleRow(host, "zero-copy", stringResource(R.string.display_zero_copy), null, checked = s.zeroCopy, onChange = a.onZeroCopy) } SettingsGroup(stringResource(R.string.display_image_scaling)) { s.integerScaling?.let { enabled -> @@ -276,9 +308,8 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: } SettingsGroup(stringResource(R.string.mode_hdr)) { ToggleRow( - host, "hdr", stringResource(R.string.mode_hdr10), - s.hdrReason?.let { stringResource(R.string.mode_hdr_unavailable, it) } - ?: stringResource(R.string.mode_hdr_restart), + host, "hdr", stringResource(if (s.hdrDisplay) R.string.mode_hdr10 else R.string.drawer_fake_hdr), + s.hdrReason?.let { stringResource(R.string.mode_hdr_unavailable, it) }, checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr, ) } @@ -425,7 +456,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: ValueChip(options.firstOrNull { it.path == s.gameStorage }?.chip ?: "-", open) { host.open = if (open) null else "storage" } AnchoredMenu( open, onDismiss = { if (host.open == "storage") host.open = null }, title = stringResource(R.string.mode_second_library), - note = stringResource(R.string.mode_storage_note), + note = stringResource(R.string.mode_storage_note).let { if (s.storageFat32) stringResource(R.string.main_storage_fat32) + "\n" + it else it }, ) { firstItemFocus -> options.forEachIndexed { index, choice -> MenuItem(choice.label, checked = choice.path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) { @@ -487,75 +518,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: } if (tab == SheetTab.STEAM && steam) { extras.account(host) - SettingsGroup(stringResource(R.string.mode_decky)) { - val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null && - s.deckyInstalled != s.deckyLatestRelease.tag - val status = when { - s.deckyStage != null -> s.deckyStage - s.deckyChecking -> stringResource(R.string.mode_decky_checking) - s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_ready, s.deckyLatestRelease.tag) - s.deckyInstalled == null -> stringResource(R.string.mode_decky_none) - s.deckyLatestRelease == null -> stringResource(R.string.mode_decky_installed, s.deckyInstalled) - updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag) - else -> stringResource(R.string.mode_decky_current, s.deckyInstalled) - } - SettingsRow(stringResource(R.string.mode_decky_loader), status) { - val action = when { - s.deckyStage != null -> stringResource(R.string.common_working) - s.deckyChecking -> stringResource(R.string.common_checking) - s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_install_latest) - s.deckyInstalled != null && updateAvailable -> stringResource(R.string.common_update) - else -> stringResource(R.string.common_check) - } - Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) { - SecondaryButton( - action, - enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning, - ) { - if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck() - else s.deckyLatestRelease?.let(a.onDeckyInstall) - } - if (s.deckyInstalled != null) DeckyUninstall(enabled = s.deckyStage == null && !s.deckySessionRunning, onUninstall = a.onDeckyUninstall) - } - } - ChoiceRow( - host, "decky-channel", stringResource(R.string.decky_channel), - stringResource(R.string.decky_channel_hint), - listOf( - DeckyManager.BRANCH_STABLE to stringResource(R.string.decky_channel_stable), - DeckyManager.BRANCH_PRERELEASE to stringResource(R.string.decky_channel_prerelease), - ) + if (s.deckyBranch == DeckyManager.BRANCH_TESTING) listOf( - DeckyManager.BRANCH_TESTING to stringResource(R.string.decky_channel_testing), - ) else emptyList(), - s.deckyBranch, - enabled = s.deckyStage == null && !s.deckySessionRunning, - onPick = a.onDeckyBranch, - ) - if (s.deckyInstalled != null) ToggleRow( - host, "decky-enabled", stringResource(R.string.mode_decky), - if (s.deckyEnabled) stringResource(R.string.mode_decky_on) - else stringResource(R.string.mode_decky_off), - s.deckyEnabled, - enabled = !s.deckySessionRunning && s.deckyStage == null, - onChange = a.onDeckyEnabled, - ) - SettingsRow( - stringResource(R.string.mode_decky_plugins), - stringResource(R.string.mode_decky_plugins_hint), - ) { - SecondaryButton( - if (s.deckyStage != null && s.deckyDownloadingBinary) stringResource(R.string.mode_decky_plugin_downloading) else stringResource(R.string.mode_decky_plugin_install_zip), - enabled = s.deckyInstalled != null && s.deckyStage == null && !s.deckySessionRunning, - onClick = a.onPickDeckyPluginZip, - ) - } - if (s.deckyStage != null && s.deckyPercent >= 0) { - LinearProgressIndicator( - progress = { s.deckyPercent / 100f }, - modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp), - ) - } - } SettingsGroup(stringResource(R.string.mode_client)) { ToggleRow( host, "mangoapp", stringResource(R.string.mode_mangoapp), @@ -585,7 +547,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: onPick = a.onSteamClientArch, ) } - if (s.bootMovie != null) BootMovieGroup(s, a, host) if (s.integration != null) SteamIntegrationGroup(s.integration, onFeature = a.onIntegration, onAppInfo = a.onIntegrationAppInfo, onLocation = a.onIntegrationLocation) } @@ -647,7 +608,7 @@ internal fun DeckyZipWarningDialog(onConfirm: () -> Unit, onCancel: () -> Unit) private const val DECKY_ZIP_WARNING_SECONDS = 5 @Composable -private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) { +internal fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) { val colors = MaterialTheme.colorScheme val label = stringResource(R.string.common_uninstall) val title = stringResource(R.string.mode_decky_remove_title) @@ -698,10 +659,10 @@ internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss: @OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class) @Composable -internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, Int>) -> Unit, onDismiss: () -> Unit) { +internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, Int>) -> Unit, onDismiss: () -> Unit, portrait: Boolean = false) { var w by remember { mutableStateOf(initial?.first?.toString() ?: "") } var h by remember { mutableStateOf(initial?.second?.toString() ?: "") } - val parsed = SessionPrefs.parseResolution("${w}x$h") + val parsed = if (portrait) SessionPrefs.parseOrientedResolution("${w}x$h") else SessionPrefs.parseResolution("${w}x$h") com.droiddeck.launcher.ui.GlideAlertDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.mode_custom_res_title)) }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt index a2dad0a54c..bdb28f6fa7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt @@ -81,7 +81,7 @@ private fun MoreTile(s: FrontEndState, key: String, first: Boolean, modifier: Mo .then(if (first) Modifier.paneEntry() else Modifier.paneItem("more:$key")) .testTag("more-$key") .height(112.dp).clip(shape) - .background(if (hot) pal.signal.copy(alpha = 0.12f) else colors.surface) + .background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.12f)) else Modifier) .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(src) .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt index 1a674da7f6..c9c469dad0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -26,10 +26,10 @@ internal object DeveloperTools { internal object NavTabs { const val MORE = "more" - val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent") - val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent") + val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent") + val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent") val DEFAULT_HIDDEN = setOf("android-apps", "agent") - private val SHELVED_WHEN_NEW = setOf("storage", "sync", "android-apps", "agent") + private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent") private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates") private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync") private const val LAYOUT_VERSION = 2 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt b/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt new file mode 100644 index 0000000000..e0ae4c9480 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/PadArt.kt @@ -0,0 +1,392 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.DashPathEffect +import android.graphics.LinearGradient +import android.graphics.Paint +import android.graphics.Path +import android.graphics.RadialGradient +import android.graphics.RectF +import android.graphics.Shader +import android.graphics.Typeface +import com.droiddeck.launcher.input.DpadStyle +import com.droiddeck.launcher.input.FaceGlyphs +import com.droiddeck.launcher.input.InputControl +import com.droiddeck.launcher.input.PadKit +import com.droiddeck.launcher.input.StickCap +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sin + +/** The on-screen controls' shared drawing: one glass material, shaped per virtual controller. */ +internal class PadArt(context: Context) { + private val density = context.resources.displayMetrics.density + private val body = Paint(Paint.ANTI_ALIAS_FLAG) + private val shine = Paint(Paint.ANTI_ALIAS_FLAG) + private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } + private val ink = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create("sans-serif-medium", Typeface.BOLD) } + private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND } + private val fill = Paint(Paint.ANTI_ALIAS_FLAG) + private val path = Path() + private val arm = Path() + private val bar = Path() + private val rect = RectF() + private var shineTop = Float.NaN + private var shineHeight = Float.NaN + + private fun dp(value: Float) = value * density + + fun button(canvas: Canvas, width: Int, height: Int, control: InputControl, kit: PadKit, pressed: Boolean): Boolean { + val w = width.toFloat() + val h = height.toFloat() + if (min(w, h) <= dp(4f)) return false + when (control) { + InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> + face(canvas, w / 2f, h / 2f, min(w, h) / 2f - dp(2f), control, kit, pressed) + InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT -> shoulder(canvas, w, h, control, kit, pressed) + InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> grip(canvas, w, h, control.label, pressed) + InputControl.L3, InputControl.R3 -> small(canvas, w, h, control.label, pressed) + InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT -> arrow(canvas, w, h, control, pressed) + InputControl.SELECT, InputControl.START, InputControl.GUIDE, InputControl.QAM -> { + val (shape, icon) = systemLook(kit, control) + system(canvas, w, h, shape, icon, pressed) + } + else -> return false + } + return true + } + + private fun systemLook(kit: PadKit, control: InputControl): Pair<Shape, Icon> = when { + kit.steam -> when (control) { + InputControl.SELECT -> Shape.CHIP to Icon.VIEW + InputControl.START -> Shape.CHIP to Icon.MENU + InputControl.GUIDE -> Shape.PILL to Icon.STEAM + else -> Shape.PILL to Icon.QAM + } + kit.playStation -> when (control) { + InputControl.SELECT -> Shape.PILL to if (kit == PadKit.DUALSHOCK) Icon.SHARE else Icon.CREATE + InputControl.START -> Shape.PILL to if (kit == PadKit.DUALSHOCK) Icon.OPTIONS else Icon.MENU + InputControl.GUIDE -> Shape.ROUND to Icon.HOME + else -> Shape.ROUND to Icon.QAM + } + else -> Shape.ROUND to when (control) { + InputControl.SELECT -> Icon.BACK + InputControl.START -> Icon.START + InputControl.GUIDE -> Icon.HOME + else -> Icon.QAM + } + } + + fun glass(canvas: Canvas, shape: Path, pressed: Boolean, tint: Int = BODY) { + shape.computeBounds(rect, false) + body.color = if (pressed) PRESSED else tint + body.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW) + canvas.drawPath(shape, body) + body.clearShadowLayer() + if (!pressed) { + if (rect.top != shineTop || rect.height() != shineHeight) { + shineTop = rect.top; shineHeight = rect.height() + shine.shader = LinearGradient(0f, rect.top, 0f, rect.top + rect.height() * .55f, SHINE, Color.TRANSPARENT, Shader.TileMode.CLAMP) + } + canvas.drawPath(shape, shine) + } + edge.color = if (pressed) EDGE_PRESSED else EDGE + edge.strokeWidth = dp(1.25f) + canvas.drawPath(shape, edge) + } + + fun circle(cx: Float, cy: Float, r: Float): Path = path.apply { reset(); addCircle(cx, cy, r, Path.Direction.CW) } + + fun roundRect(l: Float, t: Float, r: Float, b: Float, radius: Float): Path = path.apply { + reset(); addRoundRect(RectF(l, t, r, b), radius, radius, Path.Direction.CW) + } + + private fun corners(l: Float, t: Float, r: Float, b: Float, tl: Float, tr: Float, br: Float, bl: Float): Path = path.apply { + reset(); addRoundRect(RectF(l, t, r, b), floatArrayOf(tl, tl, tr, tr, br, br, bl, bl), Path.Direction.CW) + } + + fun text(canvas: Canvas, value: String, cx: Float, cy: Float, size: Float, color: Int, maxWidth: Float = Float.MAX_VALUE) { + ink.textSize = size + val measured = ink.measureText(value) + if (measured > maxWidth) ink.textSize = size * maxWidth / measured + ink.color = color + canvas.drawText(value, cx, cy - (ink.ascent() + ink.descent()) / 2f, ink) + } + + fun face(canvas: Canvas, cx: Float, cy: Float, r: Float, control: InputControl, kit: PadKit, pressed: Boolean) { + glass(canvas, circle(cx, cy, r), pressed) + when (kit.face) { + FaceGlyphs.COLOR_SYMBOLS -> symbol(canvas, cx, cy, r, control, if (pressed) ON_ACCENT else SYMBOL_COLORS[control] ?: INK) + FaceGlyphs.MONO_SYMBOLS -> symbol(canvas, cx, cy, r, control, if (pressed) ON_ACCENT else INK_SOFT) + FaceGlyphs.COLOR_LETTERS -> text(canvas, control.label, cx, cy, r * .95f, if (pressed) ON_ACCENT else LETTER_COLORS[control] ?: INK) + FaceGlyphs.MONO_LETTERS -> text(canvas, control.label, cx, cy, r * .95f, if (pressed) ON_ACCENT else INK) + } + } + + private fun symbol(canvas: Canvas, cx: Float, cy: Float, r: Float, control: InputControl, color: Int) { + val s = r * .4f + line.color = color; line.strokeWidth = r * .12f + when (control) { + InputControl.A -> { canvas.drawLine(cx - s, cy - s, cx + s, cy + s, line); canvas.drawLine(cx + s, cy - s, cx - s, cy + s, line) } + InputControl.B -> canvas.drawCircle(cx, cy, s * 1.05f, line) + InputControl.X -> canvas.drawRoundRect(RectF(cx - s * .95f, cy - s * .95f, cx + s * .95f, cy + s * .95f), s * .18f, s * .18f, line) + else -> canvas.drawPath(path.apply { reset(); moveTo(cx, cy - s * 1.1f); lineTo(cx + s * 1.1f, cy + s * .85f); lineTo(cx - s * 1.1f, cy + s * .85f); close() }, line) + } + } + + fun shoulder(canvas: Canvas, w: Float, h: Float, control: InputControl, kit: PadKit, pressed: Boolean) { + val inset = dp(2f) + val l = inset; val t = inset; val r = w - inset; val b = h - inset + val trigger = control == InputControl.LT || control == InputControl.RT + val big = (b - t) * if (trigger) .9f else .62f + val small = dp(5f) + val left = control == InputControl.LT || control == InputControl.LB + glass(canvas, if (left) corners(l, t, r, b, big, small, small, small) else corners(l, t, r, b, small, big, small, small), pressed) + text(canvas, kit.label(control), w / 2f, h / 2f, (b - t) * .46f, if (pressed) ON_ACCENT else INK, (r - l) * .8f) + } + + /** A back grip: a capsule along the long side of its box, at most 2.2 times as long as it is thick. */ + fun grip(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) { + val inset = dp(3f) + val thick = (min(w, h) - 2 * inset).coerceAtLeast(1f) + val long = (max(w, h) - 2 * inset).coerceAtMost(thick * 2.2f) + val bw = if (w >= h) long else thick; val bh = if (w >= h) thick else long + val cx = w / 2f; val cy = h / 2f + glass(canvas, roundRect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, thick / 2), pressed) + text(canvas, label, cx, cy, thick * .42f, if (pressed) ON_ACCENT else INK_SOFT) + } + + fun small(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) { + val r = min(w, h) / 2f * VISUAL + glass(canvas, circle(w / 2f, h / 2f, r), pressed) + text(canvas, label, w / 2f, h / 2f, r * .62f, if (pressed) ON_ACCENT else INK) + } + + enum class Shape { ROUND, PILL, CHIP } + enum class Icon { VIEW, MENU, QAM, KEYBOARD, BACK, START, CREATE, HOME, STEAM, SHARE, OPTIONS } + + fun system(canvas: Canvas, w: Float, h: Float, shape: Shape, icon: Icon, pressed: Boolean, ink: Int = INK) { + val cx = w / 2f; val cy = h / 2f + val size = when (shape) { + Shape.ROUND -> { val r = min(w, h) / 2f * VISUAL; glass(canvas, circle(cx, cy, r), pressed); r * 1.2f } + Shape.PILL -> { val vh = min(h * VISUAL, w * VISUAL / 2.3f); val vw = vh * 2.3f + glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh / 2), pressed); vh * 1.1f } + Shape.CHIP -> { val vh = min(h * VISUAL, w * VISUAL / 1.9f); val vw = vh * 1.9f + glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh * .32f), pressed); vh * 1.05f } + } + icon(canvas, cx, cy, size, icon, if (pressed) ON_ACCENT else ink) + } + + fun icon(canvas: Canvas, cx: Float, cy: Float, size: Float, icon: Icon, color: Int) { + val u = size / 28f + line.color = color; line.strokeWidth = 3.2f * u + fill.color = color; fill.shader = null + when (icon) { + Icon.VIEW -> { + canvas.drawRoundRect(RectF(cx - 12 * u, cy - 9 * u, cx + 3 * u, cy + 3 * u), 3 * u, 3 * u, line) + fill.color = Color.argb(230, 14, 16, 20) + canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, fill) + canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, line) + } + Icon.MENU -> for (dy in intArrayOf(-7, 0, 7)) canvas.drawLine(cx - 11 * u, cy + dy * u, cx + 11 * u, cy + dy * u, line) + Icon.QAM -> for (dx in intArrayOf(-10, 0, 10)) canvas.drawCircle(cx + dx * u, cy, 3.4f * u, fill) + Icon.KEYBOARD -> { + canvas.drawRoundRect(RectF(cx - 16 * u, cy - 11 * u, cx + 16 * u, cy + 11 * u), 4.5f * u, 4.5f * u, line) + for (row in 0..1) for (col in 0..3) canvas.drawCircle(cx + (-9 + col * 6) * u, cy + (-4 + row * 5) * u, 1.7f * u, fill) + line.strokeWidth = 2.6f * u; canvas.drawLine(cx - 6 * u, cy + 6 * u, cx + 6 * u, cy + 6 * u, line) + } + Icon.BACK, Icon.START -> { + val f = if (icon == Icon.START) 1f else -1f + line.strokeWidth = 2.6f * u + canvas.drawPath(path.apply { reset(); moveTo(cx - 6 * f * u, cy - 8 * u); lineTo(cx + 7 * f * u, cy); lineTo(cx - 6 * f * u, cy + 8 * u); close() }, line) + } + Icon.CREATE -> { + line.strokeWidth = 2.8f * u + canvas.drawLine(cx - 8 * u, cy + 8 * u, cx - 2 * u, cy - 8 * u, line) + canvas.drawLine(cx + u, cy + 8 * u, cx + 4 * u, cy - 2 * u, line) + canvas.drawLine(cx + 8 * u, cy + 8 * u, cx + 9 * u, cy + 3 * u, line) + } + Icon.HOME -> canvas.drawPath(path.apply { + reset(); moveTo(cx - 13 * u, cy - u); lineTo(cx, cy - 13 * u); lineTo(cx + 13 * u, cy - u) + moveTo(cx - 9 * u, cy - 4 * u); lineTo(cx - 9 * u, cy + 11 * u); lineTo(cx + 9 * u, cy + 11 * u); lineTo(cx + 9 * u, cy - 4 * u) + }, line) + Icon.STEAM, Icon.SHARE, Icon.OPTIONS -> { + ink.letterSpacing = .12f + text(canvas, when (icon) { Icon.STEAM -> "STEAM"; Icon.SHARE -> "SHARE"; else -> "OPTIONS" }, cx, cy, 14 * u, color, size * 1.9f) + ink.letterSpacing = 0f + } + } + } + + private fun chevron(canvas: Canvas, ax: Float, ay: Float, dx: Float, dy: Float, k: Float, color: Int, width: Float) { + val px = -dy; val py = dx + line.color = color; line.strokeWidth = width + canvas.drawPath(path.apply { + reset(); moveTo(ax - dx * k * .5f + px * k, ay - dy * k * .5f + py * k); lineTo(ax + dx * k * .6f, ay + dy * k * .6f) + lineTo(ax - dx * k * .5f - px * k, ay - dy * k * .5f - py * k) + }, line) + } + + private fun cross(target: Path, cx: Float, cy: Float, s: Float, h: Float, rc: Float) = target.apply { + reset() + addRoundRect(RectF(cx - h, cy - s, cx + h, cy + s), rc, rc, Path.Direction.CW) + bar.reset() + bar.addRoundRect(RectF(cx - s, cy - h, cx + s, cy + h), rc, rc, Path.Direction.CW) + op(bar, Path.Op.UNION) + } + + fun arrow(canvas: Canvas, w: Float, h: Float, control: InputControl, pressed: Boolean) { + val cx = w / 2f; val cy = h / 2f + val s = min(w, h) / 2f - dp(2f) + val (dx, dy) = when (control) { + InputControl.UP -> 0f to -1f + InputControl.RIGHT -> 1f to 0f + InputControl.DOWN -> 0f to 1f + else -> -1f to 0f + } + glass(canvas, roundRect(cx - s, cy - s, cx + s, cy + s, s * .32f), pressed) + chevron(canvas, cx, cy, dx, dy, s * .3f, if (pressed) ON_ACCENT else INK, s * .14f) + } + + /** [held] bits: up 1, right 2, down 4, left 8. */ + fun dpad(canvas: Canvas, w: Float, h: Float, kit: PadKit, held: Int, chevrons: Boolean = true, ink: Int = INK) { + val cx = w / 2f; val cy = h / 2f + val s = min(w, h) / 2f - dp(3f) + if (s <= 0f) return + val dirs = arrayOf(floatArrayOf(0f, -1f), floatArrayOf(1f, 0f), floatArrayOf(0f, 1f), floatArrayOf(-1f, 0f)) + when (kit.dpad) { + DpadStyle.CROSS, DpadStyle.DISC -> { + val disc = kit.dpad == DpadStyle.DISC + val arms = if (disc) s * .78f else s + val half = if (disc) s * .25f else s * .37f + if (disc) { + glass(canvas, circle(cx, cy, s), false) + fill.shader = null; fill.color = Color.argb(18, 255, 255, 255) + canvas.drawPath(cross(arm, cx, cy, arms, half, half * .5f), fill) + edge.color = Color.argb(56, 255, 255, 255); edge.strokeWidth = dp(1f) + canvas.drawPath(arm, edge) + } else glass(canvas, cross(arm, cx, cy, arms, half, half * .43f), false) + for (i in 0..3) { + val dx = dirs[i][0]; val dy = dirs[i][1] + val on = held and (1 shl i) != 0 + if (on && half > dp(2f)) { + fill.shader = null; fill.color = PRESSED + val near = half + dp(1f); val far = arms - dp(2f); val side = half - dp(2f) + rect.set(if (dx == 0f) cx - side else if (dx > 0) cx + near else cx - far, if (dy == 0f) cy - side else if (dy > 0) cy + near else cy - far, + if (dx == 0f) cx + side else if (dx > 0) cx + far else cx - near, if (dy == 0f) cy + side else if (dy > 0) cy + far else cy - near) + canvas.drawRoundRect(rect, half * .4f, half * .4f, fill) + } + val m = (arms + half) / 2f + if (chevrons) chevron(canvas, cx + dx * m, cy + dy * m, dx, dy, half * .32f, if (on) ON_ACCENT else ink, half * .17f) + } + if (!disc) { fill.shader = null; fill.color = Color.argb(18, 255, 255, 255); canvas.drawCircle(cx, cy, half * .36f, fill) } + } + DpadStyle.ARROWS -> { + fill.shader = null; fill.color = Color.argb(56, 0, 0, 0) + canvas.drawCircle(cx, cy, s, fill) + edge.color = Color.argb(36, 255, 255, 255); edge.strokeWidth = dp(1f) + canvas.drawCircle(cx, cy, s, edge) + val bw = s * .5f; val tip = s * .14f; val base = s * .38f; val top = s * .9f; val rc = s * .11f + for (i in 0..3) { + canvas.save() + canvas.rotate(i * 90f, cx, cy) + arm.reset() + arm.moveTo(cx, cy - tip); arm.lineTo(cx - bw / 2, cy - base); arm.lineTo(cx - bw / 2, cy - top + rc) + arm.quadTo(cx - bw / 2, cy - top, cx - bw / 2 + rc, cy - top); arm.lineTo(cx + bw / 2 - rc, cy - top) + arm.quadTo(cx + bw / 2, cy - top, cx + bw / 2, cy - top + rc); arm.lineTo(cx + bw / 2, cy - base); arm.close() + val on = held and (1 shl i) != 0 + glass(canvas, arm, on) + val ty = cy - (base + top) / 2f; val ts = s * .07f + fill.shader = null; fill.color = if (on) ON_ACCENT else INK_SOFT + if (chevrons) canvas.drawPath(path.apply { reset(); moveTo(cx, ty - ts); lineTo(cx + ts, ty + ts * .7f); lineTo(cx - ts, ty + ts * .7f); close() }, fill) + canvas.restore() + } + } + } + } + + fun stick(canvas: Canvas, cx: Float, cy: Float, radius: Float, kit: PadKit, kx: Float, ky: Float, active: Boolean) { + fill.alpha = 255 + fill.shader = RadialGradient(cx, cy, radius, WELL_IN, WELL_OUT, Shader.TileMode.CLAMP) + fill.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW) + canvas.drawCircle(cx, cy, radius, fill) + fill.clearShadowLayer(); fill.shader = null + edge.color = Color.argb(61, 255, 255, 255); edge.strokeWidth = dp(1.25f) + canvas.drawCircle(cx, cy, radius, edge) + line.color = Color.argb(71, 255, 255, 255); line.strokeWidth = dp(1.4f) + for (i in 0 until 8) { + val a = i * Math.PI / 4 + val c = cos(a).toFloat(); val n = sin(a).toFloat() + canvas.drawLine(cx + c * (radius - dp(7f)), cy + n * (radius - dp(7f)), cx + c * (radius - dp(3.5f)), cy + n * (radius - dp(3.5f)), line) + } + if (active && (kx != 0f || ky != 0f)) { + val angle = Math.toDegrees(atan2(ky, kx).toDouble()).toFloat() + line.color = ACCENT; line.strokeWidth = dp(3f) + val r = radius - dp(2f) + canvas.drawArc(RectF(cx - r, cy - r, cx + r, cy + r), angle - 35f, 70f, false, line) + } + val k = radius * .46f + val x = cx + kx; val y = cy + ky + if (kit.stick == StickCap.RINGED) { + line.color = if (active) ACCENT else Color.argb(140, 226, 232, 240); line.strokeWidth = dp(2.8f) + canvas.drawCircle(x, y, k * 1.14f, line) + } + glass(canvas, circle(x, y, k), false) + when (kit.stick) { + StickCap.DISHED -> { + fill.shader = RadialGradient(x, y - k * .1f, k * .74f, Color.argb(107, 0, 0, 0), Color.TRANSPARENT, Shader.TileMode.CLAMP) + canvas.drawCircle(x, y, k * .74f, fill); fill.shader = null + edge.color = if (active) ACCENT else Color.argb(51, 255, 255, 255); edge.strokeWidth = dp(1f) + canvas.drawCircle(x, y, k * .74f, edge) + } + StickCap.KNURLED -> { + line.color = if (active) ACCENT else Color.argb(66, 255, 255, 255); line.strokeWidth = dp(2.3f) + line.pathEffect = DashPathEffect(floatArrayOf(dp(1.2f), dp(1.9f)), 0f) + canvas.drawCircle(x, y, k * .9f, line); line.pathEffect = null + fill.color = Color.argb(56, 0, 0, 0); canvas.drawCircle(x, y, k * .6f, fill) + } + StickCap.RINGED -> { edge.color = Color.argb(36, 255, 255, 255); edge.strokeWidth = dp(1f); canvas.drawCircle(x, y, k * .66f, edge) } + } + } + + fun trackpad(canvas: Canvas, w: Float, h: Float, touching: Boolean, fx: Float, fy: Float) { + val inset = dp(1.5f) + val radius = min(w, h) * .14f + fill.shader = null; fill.color = Color.argb(51, 14, 16, 20) + rect.set(inset, inset, w - inset, h - inset) + canvas.drawRoundRect(rect, radius, radius, fill) + edge.color = if (touching) Color.argb(191, 0x1A, 0x9F, 0xFF) else Color.argb(51, 255, 255, 255) + edge.strokeWidth = dp(if (touching) 1.5f else 1f) + canvas.drawRoundRect(rect, radius, radius, edge) + if (!touching) return + val glow = min(w, h) * .3f + fill.shader = RadialGradient(fx, fy, glow, GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP) + canvas.drawCircle(fx, fy, glow, fill); fill.shader = null + fill.color = ACCENT; canvas.drawCircle(fx, fy, dp(5f), fill) + } + + companion object { + const val VISUAL = .72f + val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF) + val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F) + val INK = Color.rgb(0xF4, 0xF7, 0xFB) + val INK_SOFT = Color.argb(209, 0xF4, 0xF7, 0xFB) + private val BODY = Color.argb(133, 14, 16, 20) + private val PRESSED = Color.argb(235, 0x1A, 0x9F, 0xFF) + private val SHINE = Color.argb(43, 255, 255, 255) + private val EDGE = Color.argb(77, 255, 255, 255) + private val EDGE_PRESSED = Color.argb(140, 255, 255, 255) + private val SHADOW = Color.argb(97, 0, 0, 0) + private val WELL_IN = Color.argb(140, 5, 7, 10) + private val WELL_OUT = Color.argb(71, 14, 16, 20) + private val GLOW = Color.argb(140, 0x1A, 0x9F, 0xFF) + private val LETTER_COLORS = mapOf(InputControl.A to Color.rgb(0x5C, 0xCB, 0x5F), InputControl.B to Color.rgb(0xF0, 0x50, 0x4A), + InputControl.X to Color.rgb(0x4C, 0x9B, 0xF0), InputControl.Y to Color.rgb(0xF5, 0xC0, 0x2E)) + private val SYMBOL_COLORS = mapOf(InputControl.A to Color.rgb(0x8D, 0xB4, 0xF2), InputControl.B to Color.rgb(0xF2, 0x61, 0x6B), + InputControl.X to Color.rgb(0xEE, 0x93, 0xD6), InputControl.Y to Color.rgb(0x45, 0xCB, 0xAA)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt b/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt index 3e4b57fb26..e510dbc848 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PageSwipe.kt @@ -6,6 +6,8 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset @@ -13,26 +15,40 @@ import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.util.VelocityTracker import androidx.compose.ui.input.pointer.util.addPointerInputChange +import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.layout.findRootCoordinates +import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.unit.dp import kotlin.math.abs internal object PageSwipe { var locks by mutableIntStateOf(0) var direction by mutableIntStateOf(0) + var on by mutableStateOf(true) } @Composable -internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): Modifier { +internal fun Modifier.pageSwipe(enabled: () -> Boolean, edgeGuard: () -> Boolean = { false }, onSwipe: (Int) -> Unit): Modifier { val enabledNow by rememberUpdatedState(enabled) + val edgeGuardNow by rememberUpdatedState(edgeGuard) val onSwipeNow by rememberUpdatedState(onSwipe) - return pointerInput(Unit) { + val placed = remember { arrayOfNulls<LayoutCoordinates>(1) } + return onGloballyPositioned { placed[0] = it }.pointerInput(Unit) { val distance = 72.dp.toPx() val flingDistance = 32.dp.toPx() val flingVelocity = 900.dp.toPx() val slop = viewConfiguration.touchSlop + val edge = 32.dp.toPx() awaitEachGesture { val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Final) - if (!enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture + if (!PageSwipe.on || !enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture + // A swipe in from the screen's edge brings back hidden system bars; it should not also turn the page. + if (edgeGuardNow()) { + val at = placed[0]?.takeIf { it.isAttached } + val x = at?.localToRoot(down.position)?.x ?: down.position.x + val width = at?.findRootCoordinates()?.size?.width?.toFloat() ?: size.width.toFloat() + if (x < edge || x > width - edge) return@awaitEachGesture + } val tracker = VelocityTracker() tracker.addPointerInputChange(down) var total = Offset.Zero @@ -48,7 +64,7 @@ internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): if (!mine && abs(total.x) > slop && abs(total.x) > abs(total.y) * 2f) mine = true if (mine) change.consume() } - if (!mine || PageSwipe.locks > 0) return@awaitEachGesture + if (!mine || !PageSwipe.on || PageSwipe.locks > 0) return@awaitEachGesture val vx = tracker.calculateVelocity().x val horizontal = abs(total.x) > abs(total.y) * 1.5f val far = abs(total.x) > distance diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt index 7f633fcf4f..2b07301b9a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt @@ -50,9 +50,7 @@ fun PhantomProcessGatePage( onDismiss: () -> Unit, onOpenDeveloperOptions: () -> Unit, onFixWithWirelessDebugging: () -> Unit, - onEnterAddressManually: () -> Unit, onCopyCommand: () -> Unit, - onOpenNotificationSettings: () -> Unit, ) { BackHandler(onBack = onDismiss) val context = LocalContext.current @@ -82,11 +80,11 @@ fun PhantomProcessGatePage( val fix: @Composable ColumnScope.() -> Unit = { if (sideQuest) SideQuestGroup(compact, onCopyCommand) else FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging, - onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) }) + onCancel = { WirelessAdbPairingService.cancel(context) }) } val side: @Composable ColumnScope.() -> Unit = { StatusGroup(status, compact) - if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onEnterAddressManually, onCopyCommand) + if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onCopyCommand) } if (wide) { Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth()) { @@ -104,15 +102,16 @@ fun PhantomProcessGatePage( } } -private data class GateEnvironment(val onWifi: Boolean, val notifications: Boolean) { +private data class GateEnvironment(val onWifi: Boolean) { companion object { fun read(context: Context): GateEnvironment { val connectivity = context.getSystemService(ConnectivityManager::class.java) val wifi = runCatching { - connectivity?.getNetworkCapabilities(connectivity.activeNetwork) - ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true + connectivity?.allNetworks?.any { network -> + connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true + } == true }.getOrDefault(true) - return GateEnvironment(wifi, WirelessAdbPairingService.notificationsEnabled(context)) + return GateEnvironment(wifi) } } } @@ -126,7 +125,6 @@ private fun FixGroup( applyingSavedPairing: Boolean, onOpenDeveloperOptions: () -> Unit, onFixWithWirelessDebugging: () -> Unit, - onOpenNotificationSettings: () -> Unit, onCancel: () -> Unit, ) { val pairing = stage is Stage.Waiting || stage is Stage.CodeNeeded || stage is Stage.Working @@ -144,6 +142,7 @@ private fun FixGroup( hasToggle -> { Body(stringResource(R.string.gate_toggle_steps)) PrimaryButton(stringResource(R.string.gate_open_dev), compact = compact, onClick = onOpenDeveloperOptions) + SecondaryButton(stringResource(R.string.gate_use_wireless_instead), compact = compact, enabled = environment.onWifi, onClick = onFixWithWirelessDebugging) } else -> { Body(stringResource(R.string.gate_no_toggle)) @@ -151,7 +150,7 @@ private fun FixGroup( PrimaryButton( if (stage is Stage.Failed) stringResource(R.string.store_try_again) else stringResource(R.string.gate_fix_for_me), compact = compact, - enabled = environment.onWifi && environment.notifications, + enabled = environment.onWifi, onClick = onFixWithWirelessDebugging, ) } @@ -160,10 +159,6 @@ private fun FixGroup( if (!environment.onWifi) { Body(stringResource(R.string.gate_needs_wifi), warn = true) } - if (!environment.notifications) { - Body(stringResource(R.string.gate_needs_notifications), warn = true) - SecondaryButton(stringResource(R.string.gate_allow_notifications), compact = compact, onClick = onOpenNotificationSettings) - } } } } @@ -224,7 +219,6 @@ private fun OtherWays( compact: Boolean, onOpenDeveloperOptions: () -> Unit, onFixWithWirelessDebugging: () -> Unit, - onEnterAddressManually: () -> Unit, onCopyCommand: () -> Unit, ) { var open by rememberSaveable { mutableStateOf(false) } @@ -240,14 +234,10 @@ private fun OtherWays( modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 14.dp, bottom = 14.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { - if (hasToggle) { - SecondaryButton(stringResource(R.string.gate_use_wireless_instead), compact = true, onClick = onFixWithWirelessDebugging) - } else { + if (!hasToggle) { Body(stringResource(R.string.gate_some_roms)) SecondaryButton(stringResource(R.string.gate_open_dev), compact = true, onClick = onOpenDeveloperOptions) } - Body(stringResource(R.string.gate_manual_hint)) - SecondaryButton(stringResource(R.string.gate_enter_manually), compact = true, onClick = onEnterAddressManually) Body(stringResource(R.string.gate_from_computer)) AdbCommand() SecondaryButton(stringResource(R.string.gate_copy_command), compact = true, onClick = onCopyCommand) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt index d25f723651..19af4ed03b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt @@ -75,6 +75,19 @@ internal fun SyncTabPage(s: FrontEndState, modifier: Modifier) { } } +@Composable +internal fun SteamTabPage(key: String, a: FrontEndActions, modifier: Modifier) { + LaunchedEffect(Unit) { a.onSteamSettings() } + Column(modifier.verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) { + PageHeader(stringResource(if (key == "decky") R.string.rail_decky else R.string.rail_boot_movies)) + a.modeSheet( + com.droiddeck.launcher.session.SessionService.MODE_STEAM, + if (key == "decky") SheetTab.DECKY else SheetTab.BOOT_MOVIES, + SheetExtras(), + ) + } +} + @Composable private fun ResetTabsRow() { val ctx = androidx.compose.ui.platform.LocalContext.current diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt index 7112d4f399..ca9ca5976c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt @@ -12,20 +12,25 @@ import com.droiddeck.launcher.session.SessionDisplay @Composable fun ResolutionRow( - host: MenuHost, choice: String, panel: Pair<Int, Int>, onPick: (String) -> Unit, + host: MenuHost, id: String, title: String, stored: String, choice: String, link: String, followTarget: String, + panel: Pair<Int, Int>, onPick: (String) -> Unit, chipModifier: Modifier = Modifier, portrait: Boolean = false, ) { val custom = "custom" + val linked = stored == link val size = SessionDisplay.resolveChoice(panel, choice, portrait) val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait) val choices = SessionDisplay.resolutionOptions(panel) - val customFollow = SessionDisplay.isFollow(choice) && choice !in choices - val selected = if (SessionDisplay.isFollow(choice)) choice + val customFollow = !linked && SessionDisplay.isFollow(choice) && choice !in choices + val selected = if (linked) link else if (SessionDisplay.isFollow(choice)) choice else if (size == screen) SessionDisplay.MATCH_SCREEN else choice var editCustom by remember { mutableStateOf(false) } var editFollow by remember { mutableStateOf(false) } - val options = choices.map { value -> + val followSize = SessionDisplay.resolveChoice(panel, followTarget, portrait) + val linkLabel = stringResource(if (link == SessionDisplay.LINK_LANDSCAPE) R.string.display_follow_landscape else R.string.display_follow_portrait, + followSize.first, followSize.second) + val options = listOf(link to linkLabel) + choices.map { value -> val dimensions = SessionDisplay.resolveChoice(panel, value, portrait) value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second) else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen) @@ -35,18 +40,18 @@ fun ResolutionRow( else "${dimensions.first}×${dimensions.second}" } + listOf(SessionDisplay.FOLLOW_CUSTOM to stringResource(R.string.display_follow_screen_scaled, if (customFollow) SessionDisplay.formatScale(SessionDisplay.followScale(choice) ?: 1f) else "…" - ) + if (customFollow) " (${size.first}×${size.second})" else "") + (custom to if (selected in choices) stringResource(R.string.mode_res_custom) + ) + if (customFollow) " (${size.first}×${size.second})" else "") + (custom to if (selected in choices || linked) stringResource(R.string.mode_res_custom) else stringResource(R.string.mode_res_custom_value, size.first, size.second)) - ChoiceRow(host, "resolution", stringResource(R.string.display_resolution), + ChoiceRow(host, id, title, stringResource(R.string.common_applies_next_session), - options, if (selected in choices) selected else if (customFollow) SessionDisplay.FOLLOW_CUSTOM else custom, chipModifier = chipModifier, + options, if (linked || selected in choices) selected else if (customFollow) SessionDisplay.FOLLOW_CUSTOM else custom, chipModifier = chipModifier, onPick = { value -> if (value == custom) editCustom = true else if (value == SessionDisplay.FOLLOW_CUSTOM) editFollow = true else onPick(value) }) if (editCustom) CustomResolutionDialog(size, onSave = { value -> editCustom = false; onPick("${value.first}x${value.second}") }, - onDismiss = { editCustom = false }) + onDismiss = { editCustom = false }, portrait = portrait) if (editFollow) CustomFollowScaleDialog(SessionDisplay.followScale(choice)?.takeIf { it > 1f }, onSave = { value -> editFollow = false; onPick(SessionDisplay.followScaled(value)) }, onDismiss = { editFollow = false }) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt new file mode 100644 index 0000000000..20c942dea6 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt @@ -0,0 +1,76 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.view.inputmethod.InputMethodManager +import android.widget.EditText +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalView +import kotlinx.coroutines.flow.first + +internal object ScreenTaps { + var count by mutableStateOf(0) +} + +/** A field that opens on a heavy page can take focus after the next tap has already finished. */ +@Composable +internal fun CancelPendingFocus(pending: Boolean, askedAtTap: Int, focused: Boolean, cancel: () -> Unit) { + val focusedNow by rememberUpdatedState(focused) + val cancelNow by rememberUpdatedState(cancel) + LaunchedEffect(pending, askedAtTap) { + if (!pending) return@LaunchedEffect + snapshotFlow { ScreenTaps.count }.first { it != askedAtTap } + if (!focusedNow) cancelNow() + } +} + +/** + * Tapped controls do not take focus in touch mode, so a text field would otherwise keep it, and its highlight. + * [x] and [y] share coordinates with [origin], the field's own position. + */ +internal fun releaseTextField(field: EditText, origin: IntArray, x: Float, y: Float) { + val margin = 12 * field.resources.displayMetrics.density + val insideX = x >= origin[0] - margin && x <= origin[0] + field.width + margin + val insideY = y >= origin[1] - margin && y <= origin[1] + field.height + margin + if (insideX && insideY) return + field.clearFocus() + (field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(field.windowToken, 0) +} + +/** A dialog's touches never reach the activity, so a dialog holding a search field counts its taps and releases the field itself. */ +internal fun Modifier.releaseTextFieldOnTap(): Modifier = composed { + val view = LocalView.current + val placed = remember { arrayOfNulls<LayoutCoordinates>(1) } + onGloballyPositioned { placed[0] = it }.pointerInput(view) { + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + ScreenTaps.count++ + var up: Offset? = null + while (true) { + val change = awaitPointerEvent(PointerEventPass.Final).changes.firstOrNull { it.id == down.id } ?: break + if ((change.position - down.position).getDistance() > viewConfiguration.touchSlop) break + if (!change.pressed) { up = change.position; break } + } + val at = up?.let { placed[0]?.takeIf { c -> c.isAttached }?.localToWindow(it) } ?: return@awaitEachGesture + view.post { + val field = view.findFocus() as? EditText ?: return@post + releaseTextField(field, IntArray(2).also(field::getLocationInWindow), at.x, at.y) + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index 6944d5a302..ff0400860c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -305,7 +305,7 @@ class SecondScreenPresentation( (onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap, picker = picker?.let { pick -> { pick(SecondScreenMode.DESKTOP) } }), weightParams()) } - SecondScreenMode.NONE -> Unit + SecondScreenMode.NONE, SecondScreenMode.MENU -> Unit } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt index 3751702897..b2bc10c8a4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -1,25 +1,103 @@ package com.droiddeck.launcher.ui +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.session.SessionPrefs + internal enum class SessionDrawerPage(val firstControl: String) { CONTROLLER("input-profile"), GLASSES("glasses-game"), DISPLAY("fg"), HUD("hud"), EFFECTS("look"), - VR("steamvr"), GAMES("anisotropy"), AGENT("agent-input"), SESSION("suspend"), + MORE("more-edit"), + VR("steamvr"), } -internal fun sessionDrawerPages( +internal object DrawerPages { + var order by mutableStateOf(SessionDrawerPage.entries.toList()) + private set + var hidden by mutableStateOf(emptySet<SessionDrawerPage>()) + private set + + /** The order captured when a page row was grabbed in Arrange pages; Back restores it. */ + var heldFrom: List<SessionDrawerPage>? = null + + fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION && page != SessionDrawerPage.MORE + + fun load(context: Context) { + order = arrange(SessionPrefs.drawerPageOrder(context)) + hidden = SessionPrefs.drawerPageHidden(context).mapNotNull { name -> SessionDrawerPage.entries.firstOrNull { it.name == name } } + .filter(::hideable).toSet() + } + + fun arrange(saved: List<String>): List<SessionDrawerPage> { + val all = SessionDrawerPage.entries + val out = saved.mapNotNull { name -> all.firstOrNull { it.name == name } }.distinct().toMutableList() + for (page in all.filterNot { it in out }) { + val before = all.subList(0, all.indexOf(page)).lastOrNull { it in out } + out.add(if (before == null) 0 else out.indexOf(before) + 1, page) + } + return out + } + + fun setHidden(context: Context, page: SessionDrawerPage, hide: Boolean) { + hidden = if (hide && hideable(page)) hidden + page else hidden - page + if (DevPreview.drawer == null) SessionPrefs.setDrawerPageHidden(context, hidden.map { it.name }.toSet()) + } + + /** [placed] holds the pages on offer in their new order; pages not on offer keep their slots. */ + fun rearrange(context: Context, placed: List<SessionDrawerPage>) { + if (placed.isEmpty() || !order.containsAll(placed)) return + val next = placed.iterator() + order = order.map { if (it in placed) next.next() else it } + if (DevPreview.drawer == null) SessionPrefs.setDrawerPageOrder(context, order.map { it.name }) + } + + fun reset(context: Context) { + order = SessionDrawerPage.entries.toList() + hidden = emptySet() + if (DevPreview.drawer != null) return + SessionPrefs.setDrawerPageOrder(context, order.map { it.name }) + SessionPrefs.setDrawerPageHidden(context, emptySet()) + } + + fun isDefault() = order == SessionDrawerPage.entries.toList() && hidden.isEmpty() +} + +internal fun offeredDrawerPages( hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, ): List<SessionDrawerPage> = - SessionDrawerPage.entries.filter { + DrawerPages.order.filter { (hasGlasses || it != SessionDrawerPage.GLASSES) && (hasAgent || it != SessionDrawerPage.AGENT) } +internal fun sessionDrawerPages( + hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, +): List<SessionDrawerPage> = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden } + +/** The pages shown as tabs: everything up to and including the More tab. */ +internal fun List<SessionDrawerPage>.strip(): List<SessionDrawerPage> { + val more = indexOf(SessionDrawerPage.MORE) + return if (more < 0) this else subList(0, more + 1) +} + +/** The pages kept inside More: those after the More tab. */ +internal fun List<SessionDrawerPage>.inMore(): List<SessionDrawerPage> { + val more = indexOf(SessionDrawerPage.MORE) + return if (more < 0) emptyList() else subList(more + 1, size) +} + +/** The tab that stands for [page]: the More tab for a page kept inside More. */ +internal fun List<SessionDrawerPage>.tabFor(page: SessionDrawerPage): SessionDrawerPage = + if (page in inMore()) SessionDrawerPage.MORE else page + internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage { val index = indexOf(current).coerceAtLeast(0) return this[Math.floorMod(index + direction, size)] diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 09e169e73b..ae1dd01b77 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -39,14 +39,17 @@ import androidx.compose.material.icons.outlined.AutoFixHigh import androidx.compose.material.icons.outlined.ExpandMore import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.MoreHoriz +import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.material.icons.outlined.PowerSettingsNew import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.material.icons.outlined.DesktopWindows import androidx.compose.material.icons.outlined.Layers import androidx.compose.material.icons.outlined.Pause +import androidx.compose.material.icons.outlined.PlayArrow import androidx.compose.material.icons.outlined.PictureInPictureAlt import androidx.compose.material.icons.automirrored.outlined.ExitToApp import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material.icons.outlined.Tune import androidx.compose.material.icons.outlined.Speed import androidx.compose.material.icons.outlined.SportsEsports import androidx.compose.material3.Icon @@ -93,6 +96,14 @@ import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.unit.Dp +import androidx.compose.runtime.rememberUpdatedState +import android.view.KeyEvent +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.ui.layout.positionInRoot +import androidx.compose.foundation.shape.CircleShape import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.HomeApp @@ -162,7 +173,7 @@ import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_ import kotlinx.coroutines.flow.collect import java.util.Locale -private val SessionDrawerPage.title: Int get() = when (this) { +internal val SessionDrawerPage.title: Int get() = when (this) { SessionDrawerPage.CONTROLLER -> R.string.drawer_page_controller SessionDrawerPage.GLASSES -> R.string.drawer_page_glasses SessionDrawerPage.DISPLAY -> R.string.drawer_page_display @@ -172,9 +183,10 @@ private val SessionDrawerPage.title: Int get() = when (this) { SessionDrawerPage.GAMES -> R.string.game_settings_title SessionDrawerPage.AGENT -> R.string.rail_agent SessionDrawerPage.SESSION -> R.string.mode_session + SessionDrawerPage.MORE -> R.string.drawer_page_more } -private val SessionDrawerPage.icon get() = when (this) { +internal val SessionDrawerPage.icon get() = when (this) { SessionDrawerPage.CONTROLLER -> Icons.Outlined.SportsEsports SessionDrawerPage.GLASSES -> GlassesIcon SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows @@ -184,6 +196,7 @@ private val SessionDrawerPage.icon get() = when (this) { SessionDrawerPage.GAMES -> Icons.Outlined.Layers SessionDrawerPage.AGENT -> Icons.Outlined.Terminal SessionDrawerPage.SESSION -> Icons.Outlined.Settings + SessionDrawerPage.MORE -> Icons.Outlined.MoreHoriz } private class DrawerFocus { @@ -229,6 +242,8 @@ class DrawerActions( val onMicEnabled: (Boolean) -> Unit = {}, val backHold: Boolean = true, val onBackHold: (Boolean) -> Unit = {}, + val dockedMenuController: Boolean = false, + val onDockedMenuController: (Boolean) -> Unit = {}, val backActionsInverted: Boolean, val backDoubleTapMs: Int = 500, val onBackDoubleTapMs: (Int) -> Unit = {}, @@ -257,6 +272,8 @@ class DrawerActions( val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF, val secondScreenMode: SecondScreenMode, val secondScreenNone: Boolean = true, + val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO, + val onDualScreenMode: (String) -> Unit = {}, val gameOnBottom: Boolean = false, val gameSwapAvailable: Boolean = false, val gameSwapBuiltIn: Boolean = true, @@ -266,6 +283,7 @@ class DrawerActions( val secondScreenDisplays: List<SecondScreenDisplay>, val selectedSecondScreenDisplay: Int, val onHud: (Boolean) -> Unit, + val onHudOnlyDuringGame: (Boolean) -> Unit = {}, val onHudSetting: (String, String) -> Unit = { _, _ -> }, val onGpuClockPin: (Boolean) -> Unit = {}, val onHudOrder: (Map<String, Boolean>, List<String>) -> Unit = { _, _ -> }, @@ -281,6 +299,9 @@ class DrawerActions( val blackFrameInsertion: Boolean = false, val blackFrameInsertionAvailable: Boolean = false, val onBlackFrameInsertion: (Boolean) -> Unit = {}, + val hdr: Boolean = false, + val hdrAvailable: Boolean = false, + val onHdr: (Boolean) -> Unit = {}, val onImportLossless: () -> Unit, val onKeyboard: () -> Unit, val onHardwareKeyboard: () -> Unit, @@ -328,6 +349,7 @@ class DrawerActions( val onSteamVr: (String) -> Unit = {}, val onTextureAnisotropy: (Int?) -> Unit = {}, val onTextureLodBias: (String?) -> Unit = {}, + val onSelectMenuMode: () -> Unit = {}, val onSecondScreenMode: (SecondScreenMode) -> Unit, val onSecondScreenDisplay: (Int) -> Unit, val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit, @@ -336,10 +358,19 @@ class DrawerActions( val pipAutoEnter: Boolean = false, val onPip: () -> Unit = {}, val onPause: () -> Unit = {}, + val paused: Boolean = false, + val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, + val onOrientation: (Int) -> Unit = {}, + val onResume: () -> Unit = {}, val onPipAutoEnter: (Boolean) -> Unit = {}, val unfoldedControls: Boolean? = null, val adaptiveSticks: Boolean? = null, val onAdaptiveSticks: (Boolean) -> Unit = {}, + val showFloatingSteamControls: Boolean = false, + val oscRearButtons: Boolean = false, + val oscTrackpads: Boolean = false, + val onOscRearButtons: (Boolean) -> Unit = {}, + val onOscTrackpads: (Boolean) -> Unit = {}, val quickButtons: Map<com.droiddeck.launcher.input.InputCommand, Boolean> = emptyMap(), val onQuickButton: (com.droiddeck.launcher.input.InputCommand, Boolean) -> Unit = { _, _ -> }, val onUnfoldedControls: (Boolean) -> Unit = {}, @@ -384,7 +415,10 @@ class DrawerActions( internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions, docked: Boolean = false, backRequest: Int = 0, onLayerChange: (Boolean) -> Unit = {}) { val pages = sessionDrawerPages(a.glassesPresent) - val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER + val page = requestedPage.takeIf { it in pages } ?: pages.first() + var managing by rememberSaveable { mutableStateOf(false) } + var releaseSignal by remember { mutableStateOf(0) } + val drawerContext = androidx.compose.ui.platform.LocalContext.current LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) } val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -398,6 +432,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) } var confirmStop by remember { mutableStateOf(false) } var sheetCoords by remember { mutableStateOf<LayoutCoordinates?>(null) } + val widthContext = LocalContext.current + var savedWidth by remember { mutableStateOf(SessionPrefs.drawerWidthDp(widthContext)) } var stopCoords by remember { mutableStateOf<LayoutCoordinates?>(null) } val pageScroll = remember { SessionDrawerPage.entries.associateWith { ScrollState(0) } } LaunchedEffect(glassesTab) { @@ -408,11 +444,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont val focus = remember { DrawerFocus() } val inputModeManager = LocalInputModeManager.current val focusManager = LocalFocusManager.current + // A page kept inside More is one step deeper than the strip: back returns to More before it closes the menu. + val insideMore = page in pages.inMore() BackHandler(enabled = open) { - if (host.open != null) host.open = null else a.onClose() + when { + host.open != null -> host.open = null + insideMore -> onPageChange(SessionDrawerPage.MORE) + else -> a.onClose() + } } BackHandler(enabled = open && confirmStop) { confirmStop = false } - val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop) + val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore) LaunchedEffect(layerOpen) { onLayerChange(layerOpen) } var seenBackRequest by remember { mutableStateOf(backRequest) } LaunchedEffect(backRequest) { @@ -422,9 +464,10 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont confirmStop -> confirmStop = false appToChooseDisplay != null -> appToChooseDisplay = null host.open != null -> host.open = null + insideMore -> onPageChange(SessionDrawerPage.MORE) } } - LaunchedEffect(page) { host.open = null; appToChooseDisplay = null } + LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false } LaunchedEffect(a.selectedGameProfileId) { if (host.open == "fex") host.open = null } @@ -486,31 +529,45 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) { val short = maxHeight < 440.dp - val sheetWidth = if (docked) maxWidth else minOf(420.dp, maxWidth * 0.92f) + // The handle keeps a strip on the left free, so a sheet dragged wide can always be dragged back. + val maxSheet = (maxWidth - DRAWER_EDGE_GAP).coerceAtLeast(0.dp) + val minSheet = minOf(DRAWER_MIN_WIDTH, maxSheet) + val defaultSheet = minOf(420.dp, maxWidth * 0.92f) + val sheetWidth = if (docked) maxWidth else (savedWidth?.dp ?: defaultSheet).coerceIn(minSheet, maxSheet) val narrow = sheetWidth < 320.dp AnimatedVisibility( open, enter = if (docked) fadeIn(Motion.tw(160)) else slideInHorizontally(Motion.sp(0.8f, Spring.StiffnessLow)) { it } + fadeIn(Motion.tw(220)), exit = if (docked) fadeOut(Motion.tw(140)) else slideOutHorizontally(Motion.tw(240)) { it } + fadeOut(Motion.tw(200)), ) { - FocusGlideHost(Modifier.fillMaxHeight().width(sheetWidth)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) { + FocusGlideHost(Modifier.fillMaxHeight().width(if (docked) sheetWidth else sheetWidth + DRAWER_HANDLE_STRIP)) { Box(Modifier.fillMaxSize().onGloballyPositioned { sheetCoords = it }) { Column( modifier = Modifier .fillMaxSize() + .padding(start = if (docked) 0.dp else DRAWER_HANDLE_STRIP) .background(if (docked) pal.background else pal.background.copy(alpha = 0.97f)) .blockTouches() .focusGroup() .controllerBack { - if (host.open != null) host.open = null else a.onClose() + when { + host.open != null -> host.open = null + managing -> DrawerPages.heldFrom?.let { held -> + DrawerPages.rearrange(drawerContext, held) + releaseSignal++ + } ?: run { managing = false } + insideMore -> onPageChange(SessionDrawerPage.MORE) + else -> a.onClose() + } } .padding(12.dp), ) { val showPicker = a.secondScreenDisplays.isNotEmpty() val roomyHeader = sheetWidth >= if (showPicker) 560.dp else 408.dp + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), - modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp) + modifier = Modifier.weight(1f).heightIn(min = 44.dp) .then(if (roomyHeader) Modifier else Modifier.horizontalScroll(rememberScrollState())), ) { SteamActionPill( @@ -521,18 +578,18 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont ScreenPicker( secondScreenModes(a.secondScreenNone, com.droiddeck.launcher.session.SessionState.deckPad, a.dashboardAvailable, a.desktopAvailable), a.secondScreenMode, onPick = { host.open = null; a.onSecondScreenMode(it) }, - onMenu = if (docked) ({ host.open = null }) else null, menuShown = docked, + onMenu = if (docked) ({ host.open = null; a.onSelectMenuMode() }) else null, menuShown = docked, ), focus.track(page, "screen").testTag("drawer-screen-picker"), ) } else if (roomyHeader) Spacer(Modifier.weight(1f)) SteamActionPill( - stringResource(R.string.stores_dl_pause), Icons.Outlined.Pause, focus.track(page, "pause"), - ) { host.open = null; a.onPause() } + stringResource(if (a.paused) R.string.resume_session else R.string.stores_dl_pause), + if (a.paused) Icons.Outlined.PlayArrow else Icons.Outlined.Pause, focus.track(page, "pause"), + ) { host.open = null; if (a.paused) a.onResume() else a.onPause() } if (a.pipSupported) SteamActionPill( stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"), ) { host.open = null; a.onPip() } - if (docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } val steamActions = a.steam && a.onSteamMenu != null && a.onQam != null val qamInteraction = remember { MutableInteractionSource() } var qamStartedOnPress by remember { mutableStateOf(false) } @@ -562,7 +619,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont onQamConfirm = { host.open = null; a.onQam?.invoke() }, showShortcuts = !docked, ) - if (!docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } + } + StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true } } a.onAchievements?.let { show -> DrawerAchievementsRow(a.achievementsProgress, Modifier.padding(top = if (short) 6.dp else 10.dp).then(focus.track(page, "achievements"))) { @@ -575,13 +633,19 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont modifier = Modifier.fillMaxWidth().padding(top = 6.dp), ) { DrawerBumper("LB", stringResource(R.string.drawer_prev_page), modifier = focus.track(page, "prev")) { - host.open = null; onPageChange(pages.step(page, -1)) + host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), -1)) } - DrawerPageTabs(page = page, pages = pages, compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) } + DrawerPageTabs(page = pages.tabFor(page), pages = pages.strip(), compact = true, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) } DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) { - host.open = null; onPageChange(pages.step(page, 1)) + host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), 1)) } } + if (insideMore && !managing) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) } + if (managing) ManageDrawerPages( + offeredDrawerPages(a.glassesPresent), + Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp), + releaseSignal, + ) { managing = false } else { if (page == SessionDrawerPage.GLASSES) SegmentedTabs( glassesPages, glassesTab, modifier = Modifier.fillMaxWidth().padding(top = 8.dp), tabModifier = { key -> focus.track(page, "glasses-tab-$key").testTag("glasses-tab-$key") }, @@ -636,6 +700,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } } + SettingsGroup(stringResource(R.string.setup_orientation)) { + ChoiceRow(host, "orientation", stringResource(R.string.setup_session_orientation), null, + SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) }, + a.orientation, chipModifier = focus.track(page, "orientation"), onPick = a.onOrientation) + } SettingsGroup(stringResource(R.string.display_image_scaling)) { if (a.steam) SettingsRow(stringResource(R.string.display_integer_scaling), null) { PadTextButton( @@ -718,6 +787,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont ToggleRow(host, "adaptive-sticks", stringResource(R.string.ctrl_adaptive), null, on, chipModifier = focus.track(page, "adaptive-sticks"), onChange = a.onAdaptiveSticks) } + if (a.showFloatingSteamControls) { + ToggleRow(host, "rear-buttons", stringResource(R.string.osc_rear_buttons), null, a.oscRearButtons, + chipModifier = focus.track(page, "rear-buttons"), onChange = a.onOscRearButtons) + ToggleRow(host, "trackpads", stringResource(R.string.osc_trackpads), null, a.oscTrackpads, + chipModifier = focus.track(page, "trackpads"), onChange = a.onOscTrackpads) + } for ((button, shown) in a.quickButtons) { val key = "quick-${button.name.lowercase()}" ToggleRow(host, key, stringResource(quickButtonLabel(button)), null, shown, @@ -746,6 +821,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) }, a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs) PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") }) + if (a.secondScreenDisplays.isNotEmpty()) ToggleRow(host, "docked-menu-controller", stringResource(R.string.drawer_docked_menu_controller), + null, a.dockedMenuController, + chipModifier = focus.track(page, "docked-menu-controller"), onChange = a.onDockedMenuController) ToggleRow(host, "corner-tap", stringResource(R.string.drawer_corner_tap), stringResource(R.string.drawer_corner_tap_hint), a.cornerTap, chipModifier = focus.track(page, "corner-tap"), onChange = a.onCornerTap) @@ -837,6 +915,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont ) } SessionDrawerPage.AGENT -> Unit + SessionDrawerPage.MORE -> DrawerMorePage(host, pages.inMore(), { host.open = null; onPageChange(it) }, { host.open = null; managing = true }) { key -> focus.track(page, key) } SessionDrawerPage.SESSION -> { SettingsGroup(stringResource(R.string.drawer_support)) { SettingsRow(stringResource(R.string.report_problem), stringResource(R.string.report_problem_hint)) { @@ -912,7 +991,14 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } } } + } } + if (!docked) DrawerResizeHandle( + width = sheetWidth, min = minSheet, max = maxSheet, + onWidth = { savedWidth = it.value.roundToInt() }, + onCommit = { savedWidth?.let { SessionPrefs.setDrawerWidthDp(widthContext, it) } }, + modifier = Modifier.align(Alignment.CenterStart).then(focus.track(page, "resize")), + ) StopConfirm( open = confirmStop, pill = sheetCoords?.let { sc -> stopCoords?.takeIf { it.isAttached && sc.isAttached }?.let { sc.localBoundingBoxOf(it, clipBounds = false) } }, @@ -969,7 +1055,7 @@ private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics. } @Composable -private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) { +internal fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val source = remember { MutableInteractionSource() } @@ -991,15 +1077,14 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit val src = remember { MutableInteractionSource() } val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill") - val shape = RoundedCornerShape(20.dp) + val shape = androidx.compose.foundation.shape.CircleShape val stopDescription = stringResource(R.string.stop_session) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, - modifier = modifier.heightIn(min = 44.dp).widthIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop") + modifier = modifier.size(44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop") .clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f)) .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick) - .controllerConfirm(onClick = onClick) - .padding(horizontal = 12.dp), + .controllerConfirm(onClick = onClick), ) { Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp)) } @@ -1101,6 +1186,70 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag private const val LOOK_CUSTOM = "custom" +/** The row above a page kept inside More that goes back to the More list. */ +@Composable +private fun DrawerMoreBack(title: String, modifier: Modifier, onBack: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val source = remember { MutableInteractionSource() } + val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value + val shape = RoundedCornerShape(12.dp) + val label = stringResource(R.string.drawer_more_back, stringResource(R.string.drawer_page_more)) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = modifier.padding(top = 8.dp, start = 14.dp, end = 14.dp).fillMaxWidth().heightIn(min = 44.dp).clip(shape) + .background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent) + .glideBorder(hot, shape, pal.signal) + .testTag("drawer-more-back") + .hoverable(source) + .clickable(interactionSource = source, indication = null, role = androidx.compose.ui.semantics.Role.Button, onClick = onBack) + .controllerConfirm(onClick = onBack) + .semantics { contentDescription = label } + .padding(horizontal = 8.dp), + ) { + Icon(Icons.AutoMirrored.Outlined.ArrowBack, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp)) + Text(stringResource(R.string.drawer_page_more), fontSize = 13.sp, color = colors.onSurfaceVariant) + Text("·", fontSize = 13.sp, color = colors.onSurfaceVariant) + Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1) + } +} + +/** The pages kept inside More, and the way into arranging which pages sit on the strip and which here. */ +@Composable +private fun DrawerMorePage(host: MenuHost, pages: List<SessionDrawerPage>, onOpen: (SessionDrawerPage) -> Unit, onEdit: () -> Unit, track: (String) -> Modifier) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + SettingsGroup(stringResource(R.string.drawer_page_more)) { + if (pages.isEmpty()) Text( + stringResource(R.string.drawer_more_empty), fontSize = 13.sp, color = colors.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp), + ) + for (item in pages) { + val source = remember { MutableInteractionSource() } + val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value + val shape = RoundedCornerShape(12.dp) + val open = { onOpen(item) } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(shape) + .background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent) + .glideBorder(hot, shape, pal.signal) + .then(track("more-${item.name.lowercase()}")) + .testTag("drawer-more-${item.name.lowercase()}") + .hoverable(source) + .clickable(interactionSource = source, indication = null, role = androidx.compose.ui.semantics.Role.Button, onClick = open) + .controllerConfirm(onClick = open) + .padding(horizontal = 14.dp), + ) { + Icon(item.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp)) + Text(stringResource(item.title), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.weight(1f)) + } + } + } + Spacer(Modifier.height(10.dp)) + DrawerOutlineButton(stringResource(R.string.drawer_manage_pages), modifier = track("more-edit").testTag("drawer-more-edit"), onClick = onEdit) +} + @Composable private fun ScreenEffectsGroup( host: MenuHost, a: DrawerActions, advancedExpanded: Boolean, onAdvancedToggle: () -> Unit, @@ -1161,7 +1310,9 @@ private fun ScreenEffectsGroup( ToggleRow(host, "toon", stringResource(R.string.drawer_toon), null, e.toon, chipModifier = track("toon")) { a.onEffects(e.copy(toon = it)) } ToggleRow(host, "crt", stringResource(R.string.drawer_crt), null, e.crt, chipModifier = track("crt")) { a.onEffects(e.copy(crt = it)) } ToggleRow(host, "ntsc", stringResource(R.string.drawer_ntsc), null, e.ntsc, chipModifier = track("ntsc")) { a.onEffects(e.copy(ntsc = it)) } - ToggleRow(host, "fake-hdr", stringResource(R.string.drawer_fake_hdr), null, e.hdr, chipModifier = track("fake-hdr")) { a.onEffects(e.copy(hdr = it)) } + if (a.hdrAvailable) ToggleRow(host, "hdr", stringResource(R.string.mode_hdr), null, a.hdr, + chipModifier = track("hdr"), onChange = a.onHdr) + else ToggleRow(host, "fake-hdr", stringResource(R.string.drawer_fake_hdr), null, e.hdr, chipModifier = track("fake-hdr")) { a.onEffects(e.copy(hdr = it)) } if (a.blackFrameInsertionAvailable) ToggleRow(host, "bfi", stringResource(R.string.drawer_bfi), stringResource(R.string.drawer_bfi_note), a.blackFrameInsertion, chipModifier = track("bfi"), onChange = a.onBlackFrameInsertion) @@ -1285,12 +1436,93 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole (if (dashboard) listOf(SecondScreenMode.DASHBOARD) else emptyList()) + (if (desktop) listOf(SecondScreenMode.DESKTOP) else emptyList()) +private val DRAWER_MIN_WIDTH = 300.dp +private val DRAWER_HANDLE_STRIP = 24.dp +private val DRAWER_EDGE_GAP = 80.dp + +/** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */ +@Composable +private fun DrawerResizeHandle(width: Dp, min: Dp, max: Dp, onWidth: (Dp) -> Unit, onCommit: () -> Unit, modifier: Modifier) { + val pal = LocalPalette.current + val density = LocalDensity.current + val source = remember { MutableInteractionSource() } + val focused by source.collectIsFocusedAsState() + var dragging by remember { mutableStateOf(false) } + var coords by remember { mutableStateOf<LayoutCoordinates?>(null) } + val current by rememberUpdatedState(width) + val lower by rememberUpdatedState(min) + val upper by rememberUpdatedState(max) + val change by rememberUpdatedState(onWidth) + val commit by rememberUpdatedState(onCommit) + val hot = focused || dragging + val label = stringResource(R.string.drawer_resize) + Box( + contentAlignment = Alignment.Center, + modifier = modifier.width(24.dp).height(96.dp) + .onGloballyPositioned { coords = it } + .focusable(true, source) + .onPreviewKeyEvent { event -> + val key = event.nativeKeyEvent + val wider = key.keyCode == KeyEvent.KEYCODE_DPAD_LEFT + if (!wider && key.keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) false + else { + if (key.action == KeyEvent.ACTION_DOWN) { + change((current + if (wider) 24.dp else (-24).dp).coerceIn(lower, upper)) + commit() + } + true + } + } + // The handle moves with the finger as the sheet resizes, so the drag is measured on the screen. + .pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false) + var last = (coords?.positionInRoot()?.x ?: 0f) + down.position.x + // Several moves can arrive before the sheet recomposes, so the width is accumulated here. + var live = current + dragging = true + do { + val event = awaitPointerEvent() + val pointer = event.changes.firstOrNull() ?: break + val x = (coords?.positionInRoot()?.x ?: 0f) + pointer.position.x + val delta = with(density) { (x - last).toDp() } + last = x + if (delta != 0.dp) { + live = (live - delta).coerceIn(lower, upper) + change(live) + } + pointer.consume() + } while (event.changes.any { it.pressed }) + dragging = false + commit() + } + } + .semantics { + contentDescription = label + stateDescription = "${width.value.roundToInt()} dp" + }, + ) { + Box( + Modifier.width(if (hot) 6.dp else 4.dp).height(56.dp).clip(CircleShape) + .background(if (hot) pal.signal else pal.onSurfaceVariant.copy(alpha = 0.55f)), + ) + } +} + @Composable private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { val choosesDisplay = a.secondScreenDisplays.size > 1 val swapsGame = a.gameSwapAvailable || a.gameOnBottom - if (!choosesDisplay && !swapsGame) return + val hasSecondScreen = a.secondScreenDisplays.isNotEmpty() + if (!hasSecondScreen && !choosesDisplay && !swapsGame) return SettingsGroup(stringResource(R.string.drawer_second_screen)) { + if (hasSecondScreen) ChoiceRow(host, "dual-screen-mode", stringResource(R.string.setup_dual_screen_sessions), null, + listOf( + com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto), + com.droiddeck.launcher.input.DualScreen.MODE_ON to stringResource(R.string.setup_dual_screen_on), + com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED to stringResource(R.string.setup_dual_screen_swapped), + com.droiddeck.launcher.input.DualScreen.MODE_OFF to stringResource(R.string.setup_dual_screen_off), + ), a.dualScreenMode, chipModifier = track("dual-screen-mode"), onPick = a.onDualScreenMode) if (swapsGame) ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null, if (a.gameSwapBuiltIn) listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom)) else listOf(false to stringResource(R.string.main_primary), true to stringResource(R.string.main_secondary)), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt index 135cd79a63..b95dd6ae1b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -93,6 +93,8 @@ internal object SettingsIndex { s(SettingsSection.CONTROLLER, R.string.setup_tab_controller, "gamepad", "buttons", "mapping", "profile", "remap"), SettingsEntry(SettingsPlace.TAB, R.string.rail_storage, tab = "storage", words = listOf("sd card", "space", "uninstall", "disk")), SettingsEntry(SettingsPlace.TAB, R.string.rail_sync, tab = "sync", words = listOf("syncthing", "saves")), + SettingsEntry(SettingsPlace.TAB, R.string.rail_decky, tab = "decky", words = listOf("plugins", "plugin store", "homebrew", "loader")), + SettingsEntry(SettingsPlace.TAB, R.string.rail_boot_movies, tab = "boot-movies", words = listOf("startup movie", "boot video", "animation", "steamdeckrepo")), s(SettingsSection.GLASSES, R.string.setup_tab_glasses, "xreal", "viture", "vr", "ar"), s(SettingsSection.LAUNCHER, R.string.setup_theme, "color", "dark"), @@ -108,6 +110,8 @@ internal object SettingsIndex { s(SettingsSection.LAUNCHER, R.string.setup_launcher_orientation, "rotate", "portrait"), s(SettingsSection.LAUNCHER, R.string.setup_session_orientation, "rotate", "portrait"), s(SettingsSection.LAUNCHER, R.string.setup_fullscreen), + s(SettingsSection.LAUNCHER, R.string.setup_page_swipe, "gesture"), + s(SettingsSection.LAUNCHER, R.string.setup_controller_haptics, "vibration", "rumble"), s(SettingsSection.LAUNCHER, R.string.setup_dual_screen_launcher, "thor", "second screen", "bottom screen"), s(SettingsSection.LAUNCHER, R.string.setup_low_storage_warning), s(SettingsSection.LAUNCHER, R.string.mode_sgdb_key, "artwork", "steamgriddb"), @@ -137,7 +141,7 @@ internal object SettingsIndex { SettingsEntry(SettingsPlace.STEAM_QAM, R.string.drawer_frame_limit, R.string.perf_title, words = listOf("fps", "cap", "limit", "steam games")), SettingsEntry(SettingsPlace.STEAM_QAM, R.string.perf_title, words = listOf("performance overlay", "fps", "counter", "tdp")), - sh(R.string.drawer_page_display, R.string.display_session, "resolution", "scaling", "hdr", "refresh"), + sh(R.string.drawer_page_display, R.string.display_session, "resolution", "scaling", "hdr", "refresh", "zero-copy"), sh(R.string.drawer_page_display, R.string.sheet_graphics_drivers, "turnip", "driver", "gpu", "adreno", "mali"), sh(R.string.mode_tab_steam, R.string.setup_offline, "offline", "steam"), sh(R.string.mode_audio, R.string.mode_mic, "microphone", "voice"), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt index f2adebd9bf..0a4ab5590c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt @@ -49,6 +49,12 @@ internal fun SettingsPillSearch( val icon = remember { FocusRequester() } var toIcon by remember { mutableStateOf(false) } var focusOnOpen by remember { mutableStateOf(false) } + var focusTap by remember { mutableStateOf(0) } + var fieldFocused by remember { mutableStateOf(false) } + CancelPendingFocus(focusOnOpen, focusTap, fieldFocused) { + focusOnOpen = false + if (query.isEmpty()) onClose() + } val close = { toIcon = true; focusOnOpen = false; onClose() } BackHandler(enabled = searching) { close() } LaunchedEffect(toIcon, searching, open <= 0.01f) { @@ -73,15 +79,18 @@ internal fun SettingsPillSearch( Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) { AdbTextField( value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, - placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen, + placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap, clearFocus = !searching, - onFocusChange = { focused -> if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() } }, + onFocusChange = { focused -> + fieldFocused = focused + if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() } + }, ) } SmallIconButton(Icons.Filled.Close, stringResource(R.string.settings_search_clear), tint = colors.onSurfaceVariant) { close() } } } else { - Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusOnOpen = true; onOpen() } } + Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusTap = ScreenTaps.count; focusOnOpen = true; onOpen() } } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 5ebcc3c051..977fb98c44 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -163,6 +163,8 @@ internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modif } } +internal val LocalRevealChecked = androidx.compose.runtime.compositionLocalOf { true } + @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable internal fun TabStrip( @@ -347,7 +349,7 @@ fun AnchoredMenu( } } .verticalScroll(scroll), - ) { content(firstItemFocus) } + ) { androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content(firstItemFocus) } } if (scroll.canScrollForward) Icon( Icons.Filled.KeyboardArrowDown, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.align(Alignment.BottomCenter).size(20.dp), @@ -377,7 +379,7 @@ fun MenuItem( val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value val shift by animateFloatAsState(if (hot) 2f else 0f, Motion.sp(0.5f), label = "miShift") val reveal = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() } - if (checked) LaunchedEffect(Unit) { reveal.bringIntoView() } + if (checked && LocalRevealChecked.current) LaunchedEffect(Unit) { reveal.bringIntoView() } Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier.fillMaxWidth() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index 20dd2c2807..b966257c08 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -29,8 +29,13 @@ import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.ui.text.font.FontWeight import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState @@ -140,6 +145,7 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) onOpen = a.onSteamSettings, onPrimary = a.onPlay, modifier = modifier.clipToBounds(), start = if (narrow) 20.dp else 44.dp, bottom = 44.dp, + onTextBounds = { words = it }, background = { when { games.isEmpty() -> EmptyLibrary( @@ -152,28 +158,56 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) }, scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() }, words = { + val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState() + val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState() + val onboardingFacts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState() + val onboardingRows = com.droiddeck.launcher.session.Onboarding.rows(onboardingActive, onboardingFailed, onboardingFacts) + val firstRun by com.droiddeck.launcher.session.Onboarding.firstRun.collectAsState() + val settling = firstRun && onboardingActive.isNotEmpty() && com.droiddeck.launcher.session.Onboarding.pending(onboardingRows) + val limitBlocks = com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) + val mark: @Composable () -> Unit = { + Wordmark(if (narrow) 30.dp else 40.dp) + } val runtimeStatus: @Composable () -> Unit = { - if (s.busy || (s.available != null && s.available != s.installed)) RuntimeChip(s) - else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true, + if (!settling && (s.busy || (s.available != null && s.available != s.installed))) RuntimeChip(s) + else if (!settling && setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true, modifier = Modifier.testTag("play-needs-you")) { SetupTabs.openSection = SettingsSection.OVERVIEW } - else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) + else if (!settling && s.integration.suggested && signedIn && !limitBlocks) IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration) } if (narrow) Column( - verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.onPlaced { words = it.boundsInParent() }, + verticalArrangement = Arrangement.spacedBy(12.dp), ) { - Wordmark(30.dp) + mark() runtimeStatus() } else Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), - modifier = Modifier.onPlaced { words = it.boundsInParent() }, ) { - Wordmark(if (narrow) 30.dp else 40.dp) + mark() runtimeStatus() } }, button = { click -> - PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, large = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.testTag("play-steam"), onClick = click) + val onboardingActive by com.droiddeck.launcher.session.Onboarding.active.collectAsState() + val onboardingFailed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState() + val onboardingFacts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState() + val onboardingRows = com.droiddeck.launcher.session.Onboarding.rows(onboardingActive, onboardingFailed, onboardingFacts) + val firstRun by com.droiddeck.launcher.session.Onboarding.firstRun.collectAsState() + val settling = firstRun && onboardingActive.isNotEmpty() && com.droiddeck.launcher.session.Onboarding.pending(onboardingRows) + val overall = com.droiddeck.launcher.session.Onboarding.overall(onboardingRows) + val limitBlocks = com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) + LaunchedEffect(settling) { + while (settling) { + kotlinx.coroutines.delay(2_000) + a.onRefreshPhantomStatus() + } + a.onRefreshPhantomStatus() + } + if (settling) PrimaryButton( + stringResource(if (limitBlocks) R.string.onboarding_button_finish else R.string.onboarding_button_getting_ready, overall), + enabled = limitBlocks, main = true, large = true, progress = overall / 100f, + modifier = Modifier.testTag("play-steam"), onClick = { a.onQueuePlaySteam(); ChildProcessSetup.request?.invoke() ?: a.onShowPhantomGate() }, + ) else PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, large = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.testTag("play-steam"), onClick = click) }, rows = { tab -> a.modeSheet(mode, tab, extras) }, ) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt index 2827e3c7cd..e7b6a09b19 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamIntegrationGroup.kt @@ -23,6 +23,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.AutoAwesome import androidx.compose.material.icons.outlined.Close +import androidx.compose.material.icons.outlined.Bluetooth import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.KeyboardCommandKey import androidx.compose.material.icons.outlined.LightMode @@ -61,6 +62,7 @@ internal fun SteamIntegration.State.enabled(feature: Feature) = when (feature) { Feature.BRIGHTNESS -> brightness Feature.HOME -> home Feature.SHORTCUTS -> shortcuts + Feature.BLUETOOTH -> bluetooth } internal fun SteamIntegration.State.enabledCount() = Feature.entries.count { enabled(it) } @@ -116,6 +118,7 @@ private fun IntegrationRow( feature == Feature.WIFI -> if (on) R.string.integration_wifi_on else R.string.integration_wifi_hint feature == Feature.BRIGHTNESS -> R.string.integration_brightness_hint feature == Feature.HOME -> R.string.integration_home_hint + feature == Feature.BLUETOOTH -> R.string.integration_bluetooth_hint else -> R.string.integration_shortcuts_hint }) Row( @@ -164,6 +167,7 @@ private fun featureIcon(feature: Feature) = when (feature) { Feature.BRIGHTNESS -> Icons.Outlined.LightMode Feature.HOME -> Icons.Outlined.Home Feature.SHORTCUTS -> Icons.Outlined.KeyboardCommandKey + Feature.BLUETOOTH -> Icons.Outlined.Bluetooth } private fun featureTitle(feature: Feature) = when (feature) { @@ -171,6 +175,7 @@ private fun featureTitle(feature: Feature) = when (feature) { Feature.BRIGHTNESS -> R.string.integration_brightness Feature.HOME -> R.string.integration_home Feature.SHORTCUTS -> R.string.integration_shortcuts + Feature.BLUETOOTH -> R.string.integration_bluetooth } @Composable diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt index 73e68986de..b888f08065 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt @@ -45,6 +45,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Matrix @@ -174,6 +175,7 @@ internal fun StepOut( var grown by remember { mutableStateOf(false) } var measured by remember { mutableStateOf<IntSize?>(null) } val first = remember { FocusRequester() } + var holdsFocus by remember { mutableStateOf(false) } val glide = LocalFocusGlide.current val opener = remember { arrayOfNulls<GlideSource>(1) } val openNow = androidx.compose.runtime.rememberUpdatedState(open) @@ -241,8 +243,12 @@ internal fun StepOut( LaunchedEffect(open, measured) { if (!open || measured == null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect delay(Motion.ms(300).toLong()) - withFrameNanos { } - runCatching { first.requestFocus() } + // Another focus group can hold on to focus for a few frames, so the request is repeated until it lands. + repeat(30) { + withFrameNanos { } + if (holdsFocus) return@LaunchedEffect + runCatching { first.requestFocus() } + } } LaunchedEffect(open, grown, inputMode.inputMode) { @@ -289,6 +295,7 @@ internal fun StepOut( .heightIn(max = availableHeight) .onSizeChanged { if (measured != it) measured = it } .controllerBack(onDismiss) + .onFocusChanged { holdsFocus = it.hasFocus } .focusProperties { exit = { if (openNow.value) FocusRequester.Cancel else FocusRequester.Default } } .focusGroup() .verticalScroll(rememberScrollState()) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt index f34161f6aa..00b09f2145 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt @@ -83,6 +83,7 @@ import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import com.droiddeck.launcher.R import com.droiddeck.launcher.files.InAppFilePicker +import com.droiddeck.launcher.session.GameStorage import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.storage.Bucket import com.droiddeck.launcher.storage.CleanItem @@ -179,6 +180,10 @@ private fun DefaultStorageGroup() { val customLabel = SessionPrefs.defaultStorageFolderLabel(ctx).ifBlank { customPath.takeIf { it.isNotBlank() }?.let { File(it).name }.orEmpty() } + fun warnIfFat32() { + val target = StoreInstallRoot.externalTarget(ctx) ?: return + if (GameStorage.isFat32(target.root.path)) Toast.makeText(ctx, R.string.main_storage_fat32, Toast.LENGTH_LONG).show() + } val pickFolder = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode != Activity.RESULT_OK) return@rememberLauncherForActivityResult val path = InAppFilePicker.pickedPath(result.data) ?: return@rememberLauncherForActivityResult @@ -192,6 +197,7 @@ private fun DefaultStorageGroup() { value = SessionPrefs.DEFAULT_STORAGE_EXTERNAL revision++ open = false + warnIfFat32() } fun chooseFolder() { open = false @@ -250,6 +256,7 @@ private fun DefaultStorageGroup() { SessionPrefs.clearDefaultStorageFolder(ctx) pick(SessionPrefs.DEFAULT_STORAGE_EXTERNAL) revision++ + warnIfFat32() } } if (customPath.isNotBlank()) { @@ -261,7 +268,12 @@ private fun DefaultStorageGroup() { if (free >= 0) stringResource(R.string.storage_default_folder_free, gb(free)) else stringResource(R.string.storage_default_folder_missing) } ?: stringResource(R.string.storage_default_folder_missing), - ) { if (customTarget != null) pick(SessionPrefs.DEFAULT_STORAGE_EXTERNAL) else chooseFolder() } + ) { + if (customTarget != null) { + pick(SessionPrefs.DEFAULT_STORAGE_EXTERNAL) + warnIfFat32() + } else chooseFolder() + } } MenuItem( stringResource(R.string.storage_default_choose_folder), checked = false, @@ -453,7 +465,7 @@ private fun BucketCard( modifier = modifier.paneItem("storage:${bucket.name}") .graphicsLayer { scaleX = scale; scaleY = scale } .clip(Shape14) - .background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface) + .background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier) .glideBorder(hot, Shape14, pal.signal, pal.line) .then(if (onClick != null) Modifier.hoverable(src) .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt index 5d9adf2cbf..2d6e37753c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt @@ -174,7 +174,7 @@ internal fun AchievementRow(a: Achievement, compact: Boolean, modifier: Modifier Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier.fillMaxWidth().clip(shape) - .background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface) + .background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier) .glideBorder(hot, shape, pal.signal, pal.line) .focusable(interactionSource = interaction) .padding(if (compact) 8.dp else 10.dp), @@ -369,7 +369,7 @@ internal fun DrawerAchievementsRow(progress: Pair<Int, Int>?, modifier: Modifier verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = modifier.fillMaxWidth().height(44.dp).clip(shape) - .background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface) + .background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier) .glideBorder(hot, shape, pal.signal, pal.line) .clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interaction, indication = LocalIndication.current, onClick = onClick) .controllerConfirm(onClick = onClick) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt index e3724dd83d..356b69af9c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StorePage.kt @@ -533,7 +533,7 @@ private fun AppCard(app: CardApp, size: Dp, first: Boolean, cards: HashMap<Strin Column( Modifier.width(size).paneItem("tile:store:${app.id}").then(if (first) Modifier.firstTile() else Modifier) .graphicsLayer { scaleX = scale; scaleY = scale } - .clip(shape).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface) + .clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier) .glideBorder(hot, shape, pal.signal, pal.line) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) .controllerConfirm(onClick = onClick) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index a54c7f9bfb..30caa5fca7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -925,6 +925,12 @@ internal fun ModeHeader( val pal = LocalPalette.current var searching by remember { mutableStateOf(query.isNotEmpty()) } var focusOnOpen by remember { mutableStateOf(false) } + var focusTap by remember { mutableStateOf(0) } + var fieldFocused by remember { mutableStateOf(false) } + CancelPendingFocus(focusOnOpen, focusTap, fieldFocused) { + focusOnOpen = false + if (query.isEmpty()) searching = false + } val open by animateFloatAsState(if (searching) 1f else 0f, Motion.sp(0.75f, 420f), label = "searchOpen") // Closing takes the field away with focus still in it; the search button gets it once it is back on screen. val searchIcon = remember { FocusRequester() } @@ -955,9 +961,12 @@ internal fun ModeHeader( Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) { AdbTextField( value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, - placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen, + placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap, clearFocus = clearSearchFocus || !searching, - onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } }, + onFocusChange = { focused -> + fieldFocused = focused + if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } + }, ) } if (searching && closable) SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant, onClick = close) @@ -965,7 +974,7 @@ internal fun ModeHeader( } } val searchButton: @Composable () -> Unit = { - Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } } + Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { focusTap = ScreenTaps.count; searching = true; focusOnOpen = true } } } BoxWithConstraints(Modifier.fillMaxWidth()) { val stacked = maxWidth < NarrowPaneWidth diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt index efe8a808bc..391957cf58 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt @@ -118,6 +118,8 @@ internal fun SortableRows( rowHeight: androidx.compose.ui.unit.Dp, handleWidth: androidx.compose.ui.unit.Dp, onActivate: (String) -> Unit, + onGrab: (before: List<String>?) -> Unit = {}, + releaseSignal: Int = 0, row: @Composable (key: String, held: Boolean, offset: Float, hint: String?, modifier: Modifier, onFocus: (Boolean) -> Unit) -> Unit, ) { val pad = LocalInputModeManager.current.inputMode == InputMode.Keyboard @@ -129,6 +131,9 @@ internal fun SortableRows( val rowPx = with(LocalDensity.current) { rowHeight.toPx() } val handlePx = with(LocalDensity.current) { handleWidth.toPx() } val list = rows() + val grab by rememberUpdatedState(onGrab) + LaunchedEffect(grabbed) { grab(if (grabbed != null) before else null) } + LaunchedEffect(releaseSignal) { if (releaseSignal > 0) grabbed = null } Column( Modifier.fillMaxWidth().pointerInput(Unit) { awaitEachGesture { @@ -208,10 +213,10 @@ internal fun SortableRows( } @Composable -private fun MoreLine() { +internal fun MoreLine(height: androidx.compose.ui.unit.Dp = TAB_ROW) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - Column(Modifier.fillMaxWidth().height(TAB_ROW).testTag("tab-more-line")) { + Column(Modifier.fillMaxWidth().height(height).testTag("tab-more-line")) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt new file mode 100644 index 0000000000..8206bb035e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt @@ -0,0 +1,49 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.SystemUpdate +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathFillType +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.update.AppUpdates + +internal enum class BuildKind { STABLE, PREVIEW, TEST, LOCAL } + +internal object RunningBuild { + var channel by mutableStateOf(AppUpdates.Channel.STABLE) + + fun kind(me: AppUpdates.Installed = AppUpdates.installed(), channel: AppUpdates.Channel = this.channel): BuildKind = when { + me.pr > 0 -> BuildKind.TEST + !me.ciBuild -> BuildKind.LOCAL + channel == AppUpdates.Channel.NIGHTLY -> BuildKind.PREVIEW + else -> BuildKind.STABLE + } +} + +private const val PHONE = "M17,1.01L7,1c-1.1,0 -2,0.9 -2,2v18c0,1.1 0.9,2 2,2h10c1.1,0 2,-0.9 2,-2V3c0,-1.1 -0.9,-1.99 -2,-1.99zM17,19H7V5h10v14z" +private const val LETTER_P = "M9.6,7.6 H12.6 A2.4,2.4 0 0 1 12.6,12.4 H11.4 V16.4 H9.6 Z M11.4,9.2 V10.8 H12.6 A0.8,0.8 0 0 0 12.6,9.2 Z" +private const val LETTER_T = "M8.6,7.6 H15.4 V9.3 H12.9 V16.4 H11.1 V9.3 H8.6 Z" +private const val LETTER_L = "M9.8,7.6 H11.6 V14.7 H15 V16.4 H9.8 Z" + +private fun phoneWith(name: String, letter: String) = + ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f) + .addPath(addPathNodes(PHONE), fill = SolidColor(Color.Black)) + .addPath(addPathNodes(letter), fill = SolidColor(Color.Black), pathFillType = PathFillType.EvenOdd) + .build() + +private val PreviewIcon by lazy { phoneWith("UpdatesPreview", LETTER_P) } +private val TestIcon by lazy { phoneWith("UpdatesTest", LETTER_T) } +private val LocalIcon by lazy { phoneWith("UpdatesLocal", LETTER_L) } + +internal fun updatesIcon(kind: BuildKind): ImageVector = when (kind) { + BuildKind.STABLE -> Icons.Filled.SystemUpdate + BuildKind.PREVIEW -> PreviewIcon + BuildKind.TEST -> TestIcon + BuildKind.LOCAL -> LocalIcon +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt deleted file mode 100644 index ebcfcb1ea7..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt +++ /dev/null @@ -1,626 +0,0 @@ -package com.droiddeck.launcher.ui - -import com.droiddeck.launcher.R -import androidx.compose.ui.res.stringResource -import android.text.Editable -import android.text.InputType -import android.text.TextWatcher -import android.view.inputmethod.EditorInfo -import android.widget.EditText -import androidx.activity.compose.BackHandler -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.focus.FocusDirection -import androidx.compose.ui.focus.FocusManager -import androidx.compose.ui.graphics.toArgb -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalFocusManager -import androidx.compose.ui.platform.LocalSoftwareKeyboardController -import androidx.compose.ui.text.TextRange -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.input.ImeOptions -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.input.TextFieldValue -import androidx.compose.ui.unit.dp -import androidx.compose.ui.viewinterop.AndroidView -import com.droiddeck.launcher.core.PhantomProcessLimit -import com.droiddeck.launcher.core.WirelessAdbFix -import kotlin.math.min -import kotlin.math.roundToInt - -@Composable -fun WirelessAdbFixPage( - onBack: () -> Unit, - desiredEnabled: Boolean, - onOpenDeveloperOptions: () -> Unit, - onPair: (String, Int, String, (String?) -> Unit) -> Unit, - onFindConnectPort: (String, (Int?) -> Unit) -> Unit, - onApply: (String, Int, Boolean, (String?) -> Unit) -> Unit, -) { - val context = LocalContext.current - val savedAddress = remember { WirelessAdbFix.savedConnectionAddress(context) } - var step by rememberSaveable { mutableStateOf(if (savedAddress == null) 0 else 1) } - var pairingAddress by rememberSaveable { mutableStateOf("") } - var connectionAddress by rememberSaveable { mutableStateOf(savedAddress.orEmpty()) } - var pairingCode by rememberSaveable { mutableStateOf("") } - var busy by remember { mutableStateOf(false) } - var editing by remember { mutableStateOf(false) } - var message by remember { mutableStateOf<String?>(null) } - var messageIsError by remember { mutableStateOf(false) } - val focusManager = LocalFocusManager.current - val keyboardController = LocalSoftwareKeyboardController.current - val pairingEndpoint = parseAdbAddress(pairingAddress) - - val pairNow: () -> Unit = { - parseAdbAddress(pairingAddress)?.let { endpoint -> - keyboardController?.hide() - focusManager.clearFocus() - busy = true - editing = false - message = null - messageIsError = false - onPair(endpoint.host, endpoint.port, pairingCode) { error -> - pairingCode = "" - if (error != null) { - busy = false - message = error - messageIsError = true - } else { - step = 1 - busy = true - message = context.getString(R.string.wadb_finding_port) - onFindConnectPort(endpoint.host) { discoveredPort -> - if (discoveredPort == null) { - connectionAddress = formatAddressHost(endpoint.host) + ":" - busy = false - message = context.getString(R.string.wadb_enter_port) - } else { - connectionAddress = formatAdbAddress(endpoint.host, discoveredPort) - message = context.getString(R.string.wadb_applying) - onApply(endpoint.host, discoveredPort, desiredEnabled) { applyError -> - busy = false - if (applyError == null) { - step = 2 - message = null - } else { - message = context.getString(R.string.wadb_apply_failed, applyError) - messageIsError = true - } - } - } - } - } - } - } - } - val applyAddress: () -> Unit = { - parseAdbAddress(connectionAddress)?.let { endpoint -> - keyboardController?.hide() - focusManager.clearFocus() - busy = true - editing = false - message = null - messageIsError = false - onApply(endpoint.host, endpoint.port, desiredEnabled) { error -> - busy = false - if (error == null) { - step = 2 - message = null - } else { - message = error - messageIsError = true - } - } - } - } - val pairAgain: () -> Unit = { - step = 0 - pairingAddress = "" - pairingCode = "" - message = null - messageIsError = false - } - - BackHandler { if (!busy) onBack() } - - BoxWithConstraints(Modifier.fillMaxSize()) { - val compactSplit = maxWidth < 620.dp && maxHeight < 500.dp - val form: @Composable () -> Unit = { - WirelessStepForm( - step = step, - pairingAddress = pairingAddress, - onPairingAddressChange = { pairingAddress = it }, - pairingCode = pairingCode, - onPairingCodeChange = { pairingCode = it.filter(Char::isDigit).take(6) }, - connectionAddress = connectionAddress, - onConnectionAddressChange = { connectionAddress = it }, - busy = busy, - message = message, - messageIsError = messageIsError, - compact = compactSplit, - editing = editing, - onEditingChanged = { editing = it }, - focusManager = focusManager, - desiredEnabled = desiredEnabled, - canPair = pairingEndpoint != null && pairingCode.length == 6, - onPair = pairNow, - onApply = applyAddress, - onPairAgain = pairAgain, - ) - } - SettingsPage( - host = rememberMenuHost(), - title = when { - compactSplit && step < 2 -> stringResource(R.string.wadb_title_wireless) - step == 2 -> stringResource(R.string.wadb_title_done) - else -> stringResource(R.string.wadb_title) - }, - eyebrow = stringResource(R.string.setup_title), - lede = when { - compactSplit && step == 0 -> stringResource(R.string.wadb_lede_compact0) - compactSplit && step == 1 -> stringResource(R.string.wadb_lede_compact1) - compactSplit -> stringResource(R.string.wadb_lede_done) - step == 0 -> stringResource(R.string.wadb_lede0) - step == 1 -> stringResource(R.string.wadb_lede1) - else -> stringResource(R.string.wadb_lede_done_long) - }, - onBack = { if (!busy) onBack() }, - action = if (compactSplit && step < 2) { - { SecondaryButton(stringResource(R.string.setup_dev_options), compact = true, enabled = !busy, onClick = onOpenDeveloperOptions) } - } else null, - scrollContent = !compactSplit, - compactLayout = compactSplit, - ) { - BoxWithConstraints(Modifier.fillMaxWidth()) { - val wide = maxWidth >= 620.dp - if (step == 2) { - Column( - modifier = Modifier.widthIn(max = 680.dp).fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(10.dp), - ) { - SettingsGroup(stringResource(R.string.setup_limit), compact = compactSplit) { - Text( - if (desiredEnabled) stringResource(R.string.wadb_confirmed_on) else stringResource(R.string.wadb_confirmed_off), - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(14.dp), - ) - } - PrimaryButton(stringResource(R.string.setup_check_done), enabled = !busy, onClick = onBack) - } - } else if (compactSplit) { - Column( - modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - form() - if (!editing) CompactComputerFallback(desiredEnabled) - } - } else { - val routes: @Composable () -> Unit = { - FallbackOrder(desiredEnabled, busy, onOpenDeveloperOptions) - } - if (wide) { - Row( - modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(14.dp), - verticalAlignment = Alignment.Top, - ) { - Column(Modifier.weight(1f)) { routes() } - Column(Modifier.weight(1f)) { form() } - } - } else { - Column( - modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - routes() - form() - } - } - } - } - } - } -} - -@Composable -private fun WirelessStepForm( - step: Int, - pairingAddress: String, - onPairingAddressChange: (String) -> Unit, - pairingCode: String, - onPairingCodeChange: (String) -> Unit, - connectionAddress: String, - onConnectionAddressChange: (String) -> Unit, - busy: Boolean, - message: String?, - messageIsError: Boolean, - compact: Boolean, - editing: Boolean, - onEditingChanged: (Boolean) -> Unit, - focusManager: FocusManager, - desiredEnabled: Boolean, - canPair: Boolean, - onPair: () -> Unit, - onApply: () -> Unit, - onPairAgain: () -> Unit, -) { - if (step == 0) { - SettingsGroup(stringResource(R.string.wadb_pair_group), compact = compact) { - Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp), - verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp), - ) { - AdbTextField( - value = pairingAddress, - onValueChange = onPairingAddressChange, - label = stringResource(R.string.wadb_pair_address), - placeholder = "192.168.1.42:37123", - keyboardType = KeyboardType.Ascii, - imeAction = ImeAction.Next, - compact = compact, - onFocusChange = onEditingChanged, - onNext = { focusManager.moveFocus(FocusDirection.Next) }, - ) - Row( - verticalAlignment = Alignment.Bottom, - horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.fillMaxWidth(), - ) { - AdbTextField( - value = pairingCode, - onValueChange = onPairingCodeChange, - label = stringResource(R.string.wadb_pin), - placeholder = stringResource(R.string.wadb_pin_placeholder), - keyboardType = KeyboardType.Number, - imeAction = ImeAction.Done, - compact = compact, - onFocusChange = onEditingChanged, - onDone = { - focusManager.clearFocus() - }, - modifier = Modifier.weight(1f), - ) - PrimaryButton(stringResource(R.string.wadb_pair), compact = compact, enabled = !busy && canPair, onClick = onPair) - } - StatusMessage(busy, message, isError = messageIsError) - } - } - } else { - SettingsGroup(stringResource(R.string.wadb_apply_group), compact = compact) { - Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp), - verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp), - ) { - AdbTextField( - value = connectionAddress, - onValueChange = onConnectionAddressChange, - label = stringResource(R.string.wadb_connect_address), - placeholder = "192.168.1.42:45678", - keyboardType = KeyboardType.Ascii, - imeAction = ImeAction.Done, - compact = compact, - onFocusChange = onEditingChanged, - onDone = { focusManager.clearFocus() }, - ) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.fillMaxWidth(), - ) { - StatusMessage(busy, message, Modifier.weight(1f), isError = messageIsError) - SecondaryButton(stringResource(R.string.wadb_pair_again), compact = compact, enabled = !busy, onClick = onPairAgain) - PrimaryButton( - if (desiredEnabled) stringResource(R.string.setup_limit_turn_on) else stringResource(R.string.wadb_turn_off), - compact = compact, - enabled = !busy && parseAdbAddress(connectionAddress) != null, - onClick = onApply, - ) - } - } - } - } -} - -@Composable -internal fun AdbTextField( - value: String, - onValueChange: (String) -> Unit, - label: String, - keyboardType: KeyboardType, - imeAction: ImeAction, - modifier: Modifier = Modifier, - placeholder: String? = null, - compact: Boolean = false, - onFocusChange: (Boolean) -> Unit = {}, - clearFocus: Boolean = false, - onNext: (() -> Unit)? = null, - onDone: (() -> Unit)? = null, - focusOnShow: Boolean = false, - showLabel: Boolean = true, - onBack: (() -> Unit)? = null, -) { - val context = LocalContext.current - val onBackLatest = rememberUpdatedState(onBack) - val focusAsked = remember { booleanArrayOf(false) } - val palette = LocalPalette.current - val onValueChangeLatest = rememberUpdatedState(onValueChange) - val onNextLatest = rememberUpdatedState(onNext) - val onDoneLatest = rememberUpdatedState(onDone) - val onFocusChangeLatest = rememberUpdatedState(onFocusChange) - var focused by remember { mutableStateOf(false) } - val shape = RoundedCornerShape(8.dp) - val inputHeight = if (compact) 44.dp else 52.dp - val colors = MaterialTheme.colorScheme - val bottomTyping = LocalBottomTyping.current - val bottomTypingLatest = rememberUpdatedState(bottomTyping) - val typingRequest = remember { arrayOfNulls<TypingRequest>(1) } - - fun typeOnBottom(editText: EditText): Boolean { - if (!bottomTypingLatest.value || !DualScreenPanel.attached) return false - val text = editText.text.toString() - lateinit var request: TypingRequest - request = TypingRequest( - TextFieldValue(text, TextRange(editText.selectionStart.coerceIn(0, text.length), editText.selectionEnd.coerceIn(0, text.length))), - ImeOptions(singleLine = true, keyboardType = keyboardType, imeAction = imeAction), - { next -> - if (editText.text.toString() != next.text) editText.setText(next.text) - editText.setSelection(next.selection.start.coerceIn(0, next.text.length), next.selection.end.coerceIn(0, next.text.length)) - }, - { action -> editText.onEditorAction(imeActionFlag(action)) }, - { editText.post { if (typingRequest[0] === request) onBackLatest.value?.invoke() ?: editText.clearFocus() } }, - ) - typingRequest[0] = request - DualScreenPanel.startTyping(request) - return true - } - - DisposableEffect(Unit) { - onDispose { typingRequest[0]?.let { DualScreenPanel.stopTyping(it) } } - } - - Column(modifier = modifier.fillMaxWidth()) { - if (showLabel) Text( - label, - style = MaterialTheme.typography.labelSmall, - fontWeight = FontWeight.Medium, - color = colors.onSurfaceVariant, - maxLines = 1, - ) - Box( - modifier = Modifier - .fillMaxWidth() - .height(inputHeight) - .background(colors.surfaceVariant, shape) - .glideBorder(focused, shape, palette.signal, palette.line2) - .padding(horizontal = 10.dp), - contentAlignment = Alignment.CenterStart, - ) { - AndroidView( - modifier = Modifier.fillMaxSize(), - factory = { viewContext -> - EditText(viewContext).apply { - isSingleLine = true - setHorizontallyScrolling(true) - background = null - setPadding((2 * context.resources.displayMetrics.density).roundToInt(), 0, 0, 0) - setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, if (compact) 13f else 14f) - setTextColor(colors.onBackground.toArgb()) - setHintTextColor(colors.onSurfaceVariant.toArgb()) - contentDescription = label - inputType = if (keyboardType == KeyboardType.Number) { - InputType.TYPE_CLASS_NUMBER - } else { - InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS - } - imeOptions = imeActionFlag(imeAction) or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI - hint = placeholder - setOnEditorActionListener { _, actionId, event -> - val isEnter = event?.keyCode == android.view.KeyEvent.KEYCODE_ENTER - when { - imeAction == ImeAction.Next && (actionId == EditorInfo.IME_ACTION_NEXT || isEnter) -> { - onNextLatest.value?.invoke() - true - } - imeAction == ImeAction.Done && (actionId == EditorInfo.IME_ACTION_DONE || isEnter) -> { - onDoneLatest.value?.invoke() - true - } - // Search and Go are terminal: leaving them unhandled - // keeps focus in the field, so the keyboard would stay - // up over the results it was used to find. - imeAction in setOf(ImeAction.Search, ImeAction.Go) && - (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || isEnter) -> { - onDoneLatest.value?.invoke() - post { - clearFocus() - (context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) - as? android.view.inputmethod.InputMethodManager) - ?.hideSoftInputFromWindow(windowToken, 0) - } - true - } - else -> false - } - } - showSoftInputOnFocus = !bottomTyping - // B on a controller puts the keyboard away first; with no keyboard up it goes back as usual. - var hidingKeyboard = false - setOnKeyListener { view, keyCode, event -> - if (keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return@setOnKeyListener false - if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) { - hidingKeyboard = androidx.core.view.ViewCompat.getRootWindowInsets(view) - ?.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()) == true - if (hidingKeyboard) (view.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) - ?.hideSoftInputFromWindow(view.windowToken, 0) - onBackLatest.value?.let { hidingKeyboard = true; it() } - } - hidingKeyboard - } - setOnClickListener { if (hasFocus() && !typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) } - setOnFocusChangeListener { _, hasFocus -> - focused = hasFocus - if (hasFocus) { if (!typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) } - else typingRequest[0]?.let { DualScreenPanel.stopTyping(it) } - onFocusChangeLatest.value(hasFocus) - } - addTextChangedListener(object : TextWatcher { - override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit - override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit - override fun afterTextChanged(s: Editable?) { - onValueChangeLatest.value(s?.toString().orEmpty()) - } - }) - } - }, - update = { editText -> - editText.showSoftInputOnFocus = !bottomTyping - if (focusOnShow && !focusAsked[0]) { - focusAsked[0] = true - editText.post { - editText.requestFocus() - if (!bottomTypingLatest.value) (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) - ?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT) - } - } - if (clearFocus && editText.hasFocus()) { - editText.clearFocus() - (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) - ?.hideSoftInputFromWindow(editText.windowToken, 0) - } - editText.setTextColor(colors.onBackground.toArgb()) - editText.setHintTextColor(colors.onSurfaceVariant.toArgb()) - editText.hint = placeholder - editText.contentDescription = label - if (editText.text.toString() != value) { - val cursor = if (editText.hasFocus()) editText.selectionStart.coerceAtLeast(0) else value.length - editText.setText(value) - editText.setSelection(min(cursor, value.length)) - } - }, - ) - } - } -} - -@Composable -private fun FallbackOrder( - desiredEnabled: Boolean, - busy: Boolean, - onOpenDeveloperOptions: () -> Unit, -) { - SettingsGroup(stringResource(R.string.wadb_other_ways)) { - Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Text(stringResource(R.string.wadb_dev_try_first), style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground) - Text(if (desiredEnabled) stringResource(R.string.wadb_restrict_on) else stringResource(R.string.wadb_restrict_off), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - SecondaryButton(stringResource(R.string.gate_open_dev), enabled = !busy, onClick = onOpenDeveloperOptions) - Text(stringResource(R.string.wadb_computer_last), style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground) - Text(stringResource(R.string.wadb_only_if), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - Text( - PhantomProcessLimit.adbCommand(desiredEnabled), - style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace), - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} - -@Composable -private fun CompactComputerFallback(desiredEnabled: Boolean) { - SettingsGroup(stringResource(R.string.wadb_computer_group), compact = true) { - Text( - PhantomProcessLimit.adbCommand(desiredEnabled), - style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace), - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp), - ) - } -} - -@Composable -private fun StatusMessage(busy: Boolean, message: String?, modifier: Modifier = Modifier, isError: Boolean = false) { - if (busy) { - Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) - Text(message ?: stringResource(R.string.common_working), style = MaterialTheme.typography.bodySmall) - } - } else { - message?.let { - Text( - it, - modifier = modifier, - style = MaterialTheme.typography.bodySmall, - color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} - -private data class AdbEndpoint(val host: String, val port: Int) - -private fun parseAdbAddress(value: String): AdbEndpoint? { - val address = value.trim() - val host: String - val portText: String - if (address.startsWith("[")) { - val closingBracket = address.indexOf(']') - if (closingBracket <= 1 || address.getOrNull(closingBracket + 1) != ':') return null - host = address.substring(1, closingBracket) - if (':' !in host) return null - portText = address.substring(closingBracket + 2) - } else { - val colon = address.lastIndexOf(':') - if (colon <= 0 || address.indexOf(':') != colon) return null - host = address.substring(0, colon) - portText = address.substring(colon + 1) - } - if (host.isBlank() || host.any(Char::isWhitespace)) return null - val port = portText.toIntOrNull()?.takeIf { it in 1..65535 } ?: return null - return AdbEndpoint(host, port) -} - -private fun formatAddressHost(host: String): String = if (':' in host) "[$host]" else host -private fun formatAdbAddress(host: String, port: Int): String = "${formatAddressHost(host)}:$port" - -private fun showKeyboardHere(editText: EditText) { - (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) - ?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT) -} - -private fun imeActionFlag(action: ImeAction): Int = when (action) { - ImeAction.Next -> EditorInfo.IME_ACTION_NEXT - ImeAction.Done -> EditorInfo.IME_ACTION_DONE - ImeAction.Go -> EditorInfo.IME_ACTION_GO - ImeAction.Search -> EditorInfo.IME_ACTION_SEARCH - else -> EditorInfo.IME_ACTION_UNSPECIFIED -} diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 4ad4263161..d9d2eb111f 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.wayland +import android.os.Build import android.os.Handler import android.os.HandlerThread import android.os.Process @@ -29,11 +30,28 @@ object CompositorHost { @Volatile private var vsyncGeneration = 0 - private fun vsyncCallback(generation: Int) = object : Choreographer.FrameCallback { - override fun doFrame(frameTimeNanos: Long) { - if (generation != vsyncGeneration) return + private fun postVsync(generation: Int) { + val choreographer = Choreographer.getInstance() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + choreographer.postVsyncCallback { data -> + if (generation != vsyncGeneration) return@postVsyncCallback + val lines = data.frameTimelines + val line = data.preferredFrameTimeline + val period = if (lines.size > 1) { + lines[1].expectedPresentationTimeNanos - lines[0].expectedPresentationTimeNanos + } else { + 0L + } + WaylandCompositor.nativeFrameTimeline(line.expectedPresentationTimeNanos, line.deadlineNanos, period) + WaylandCompositor.nativeVsync(data.frameTimeNanos) + if (vsyncRunning) postVsync(generation) + } + return + } + choreographer.postFrameCallback { frameTimeNanos -> + if (generation != vsyncGeneration) return@postFrameCallback WaylandCompositor.nativeVsync(frameTimeNanos) - if (vsyncRunning) Choreographer.getInstance().postFrameCallback(this) + if (vsyncRunning) postVsync(generation) } } @@ -66,7 +84,7 @@ object CompositorHost { com.droiddeck.launcher.gpu.TpUbwcHint.applyToProcess(context) WaylandCompositor.nativeStartWithSurface( surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir, - SessionPrefs.androidDriver(context).isEmpty(), + SessionPrefs.displayDriverFromAuto(context), ) attached = surface started = true @@ -149,14 +167,14 @@ object CompositorHost { private fun resumeVsync() { if (vsyncRunning) return - val callback = vsyncCallback(++vsyncGeneration) + val generation = ++vsyncGeneration vsyncRunning = true WaylandCompositor.nativeLog("screen", if (ownVsyncThread) "screen tick runs on its own display-priority thread" else "screen tick runs on the main thread") if (!ownVsyncThread) { - Choreographer.getInstance().postFrameCallback(callback) + postVsync(generation) return } - vsyncHandler.post { Choreographer.getInstance().postFrameCallback(callback) } + vsyncHandler.post { postVsync(generation) } } private fun pauseVsync() { diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/HdrSupport.kt b/app/src/main/java/com/droiddeck/launcher/wayland/HdrSupport.kt index 91f408d916..0a5cb88be2 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/HdrSupport.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/HdrSupport.kt @@ -48,8 +48,11 @@ object HdrSupport { ) } + fun blocked(context: Context): String? = + if (Build.VERSION.SDK_INT < 29) context.getString(R.string.hdr_needs_android_10) else null + private fun reason(context: Context, hdr10: Boolean, formats: String): String? = when { - Build.VERSION.SDK_INT < 29 -> context.getString(R.string.hdr_needs_android_10) + Build.VERSION.SDK_INT < 29 -> blocked(context) !hdr10 -> if (formats.isEmpty()) context.getString(R.string.hdr_none) else context.getString(R.string.hdr_not_hdr10, formats) else -> null } diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index 874493e41c..4e824f6dba 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -26,6 +26,7 @@ public final class WaylandCompositor { public interface GameListener { void onGameSurface(String window, String gpuName); void onGameFrame(); + default void onCompositorFrame() {} default void onGameProgram(int pid, String program) {} } @@ -70,6 +71,12 @@ public final class WaylandCompositor { if (l != null) l.onGameFrame(); } + @SuppressWarnings("unused") + static void onCompositorFrame() { + GameListener l = gameListener; + if (l != null) l.onCompositorFrame(); + } + @SuppressWarnings("unused") static void onGameProgram(int pid, String program) { GameListener l = gameListener; @@ -94,6 +101,73 @@ public final class WaylandCompositor { if (l != null) l.onPointerLock(locked, x, y); } + public interface OverlayPlanesListener { + void onOverlayPlanes(int planes); + } + + private static volatile OverlayPlanesListener overlayPlanesListener; + private static volatile int overlayPlanes = -1; + + public static synchronized void setOverlayPlanesListener(OverlayPlanesListener l) { + overlayPlanesListener = l; + if (l != null) l.onOverlayPlanes(overlayPlanes); + } + + public static synchronized void clearOverlayPlanesListener(OverlayPlanesListener l) { + if (overlayPlanesListener == l) overlayPlanesListener = null; + } + + @SuppressWarnings("unused") + static synchronized void onOverlayPlanes(int planes) { + overlayPlanes = planes; + OverlayPlanesListener l = overlayPlanesListener; + if (l != null) l.onOverlayPlanes(planes); + } + + public interface RefreshTargetListener { + void onRefreshTarget(int refresh, int frameRate); + } + + private static volatile RefreshTargetListener refreshTargetListener; + private static volatile long refreshTarget; + + public static void setRefreshTargetListener(RefreshTargetListener l) { + refreshTargetListener = l; + long target = refreshTarget; + if (l != null) l.onRefreshTarget((int) (target >> 32), (int) target); + } + + public static void clearRefreshTargetListener(RefreshTargetListener l) { + if (refreshTargetListener == l) refreshTargetListener = null; + } + + public interface ContentRateListener { + void onContentRate(int fps); + } + + private static volatile ContentRateListener contentRateListener; + + public static void setContentRateListener(ContentRateListener l) { + contentRateListener = l; + } + + public static void clearContentRateListener(ContentRateListener l) { + if (contentRateListener == l) contentRateListener = null; + } + + @SuppressWarnings("unused") + static void onContentRate(int fps) { + ContentRateListener l = contentRateListener; + if (l != null) l.onContentRate(fps); + } + + @SuppressWarnings("unused") + static void onRefreshTarget(int refresh, int frameRate) { + refreshTarget = ((long) refresh << 32) | (frameRate & 0xffffffffL); + RefreshTargetListener l = refreshTargetListener; + if (l != null) l.onRefreshTarget(refresh, frameRate); + } + public interface ClipboardListener { void onGuestClipboardText(String text); } @@ -180,6 +254,8 @@ public final class WaylandCompositor { public static native void nativeVsync(long frameTimeNanos); + public static native void nativeFrameTimeline(long presentNanos, long deadlineNanos, long periodNanos); + public static native void nativeSetClockControl(String path); public static native int nativeCompositorTid(); @@ -210,8 +286,12 @@ public final class WaylandCompositor { public static native void nativeSetOutputRefreshRate(float hz); + public static native void nativeSetPanelRates(int[] rates); + public static native void nativeSetZeroCopy(boolean on); + public static native void nativeSetDisplayBufferDriver(boolean on); + public static native int nativeZeroCopyFrames(); public static native int nativeZeroCopyLastFrameAgeMs(); @@ -247,7 +327,7 @@ public final class WaylandCompositor { public static native void nativeResetFirstFrame(); - public static final int HDR_MODE_OFF = 0, HDR_MODE_ON = 1, HDR_MODE_FORCE = 2; + public static final int HDR_MODE_OFF = 0, HDR_MODE_ON = 1, HDR_MODE_FORCE = 2, HDR_MODE_TONEMAP = 3; public static native void nativeSetHdrRequest(int mode, String source, boolean dxvkHdr, boolean zeroCopyForced); diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 6433943918..59188caba6 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">إخراج HDR10</string> <string name="mode_hdr_unavailable">غير متاح: %1$s.</string> - <string name="mode_hdr_restart">أعد تشغيل التطبيق لتطبيق التغيير.</string> <string name="mode_drivers">برامج التشغيل</string> <string name="mode_gpu_drivers">برامج تشغيل GPU</string> <string name="mode_gpu_drivers_hint">مشتركة بين Steam وسطح المكتب. يتم ضبطها في صفحة «المكوّنات».</string> @@ -333,7 +332,6 @@ <string name="mode_startup">بدء التشغيل</string> <string name="mode_startup_session">الفتح عند التشغيل</string> <string name="mode_startup_session_hint">يبدأ هذه الجلسة عند تشغيل DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">جارٍ البحث عن إصدارات…</string> <string name="mode_decky_ready">جاهز لتثبيت %1$s.</string> <string name="mode_decky_none">لم يتم العثور على إصدار متوافق. حاول مرة أخرى لاحقًا.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">محدَّث · %1$s</string> <string name="mode_decky_loader">المُحمِّل</string> <string name="mode_decky_install_latest">تثبيت أحدث إصدار</string> - <string name="decky_channel">قناة التحديث</string> - <string name="decky_channel_hint">إصدارات Decky Loader التي تُثبَّت. يستخدم مُحدِّث Decky نفسه القناة ذاتها.</string> <string name="decky_channel_stable">مستقرة</string> <string name="decky_channel_prerelease">إصدار تجريبي مسبق</string> <string name="decky_channel_testing">اختبار</string> <string name="decky_channel_failed">تعذّر حفظ قناة تحديث Decky</string> - <string name="mode_decky_on">يبدأ مع Steam. أثناء تفعيله، قد تتمكن التطبيقات الأخرى على هذا الجهاز من التحكم في Steam.</string> - <string name="mode_decky_off">متوقف. يبقى منفذ تصحيح الأخطاء عن بُعد في Steam مغلقًا.</string> <string name="mode_decky_remove_title">هل تريد إلغاء تثبيت Decky Loader؟</string> <string name="mode_decky_remove_text">يزيل المُحمِّل. يتم الاحتفاظ بالمكونات الإضافية والإعدادات.</string> <string name="mode_client">العميل</string> @@ -965,13 +959,15 @@ <string name="setup_launcher_orientation_auto">اتّباع تدوير الجهاز</string> <string name="setup_orientation_portrait">عمودي</string> <string name="setup_session_orientation">اتجاه الجلسة</string> - <string name="setup_session_orientation_hint">يُطبَّق على Steam والألعاب وسطح المكتب ومحرّر وحدة التحكم. تدور الدقّات المُعدّة مسبقًا مع الجلسة، ويبقى العرض والارتفاع المخصّصان كما أُدخلا.</string> + <string name="setup_session_orientation_hint">يُطبَّق على Steam والألعاب وسطح المكتب ومحرّر وحدة التحكم. تدور الدقّات المُعدّة مسبقًا مع الجلسة، وعندما يتبع أحد الاتجاهين الآخر ينعكس العرض والارتفاع المخصّصان ليتطابقا.</string> <string name="setup_orientation_auto">أفقي تلقائي</string> <string name="setup_orientation_landscape">أفقي</string> <string name="setup_orientation_reverse">أفقي معكوس</string> <string name="setup_fullscreen">ملء الشاشة</string> <string name="setup_fullscreen_on">يخفي شريطي الحالة والتنقّل في Android</string> <string name="setup_fullscreen_off">يعرض شريطي الحالة والتنقّل في Android</string> + <string name="setup_page_swipe">التمرير بين الصفحات</string> + <string name="setup_page_swipe_hint">اسحب عبر الصفحة لتغيير علامة التبويب.</string> <string name="setup_dual_screen_launcher">المشغّل على شاشتين</string> <string name="setup_dual_screen_launcher_hint">يضع الوضع «تلقائي» أقسام المشغّل (Steam والمكتبة والمتاجر وغيرها) على الشاشة الثانية في الأجهزة المحمولة المزوّدة بشاشة ثانية مدمجة. ويستخدم الوضع «تشغيل» أي شاشة ثانية. أما الوضع «إيقاف» فيُبقي المشغّل على شاشة واحدة.</string> <string name="setup_dual_screen_sessions">الجلسات على شاشتين</string> @@ -1308,8 +1304,6 @@ <string name="gate_open_dev">فتح خيارات المطوّرين</string> <string name="gate_no_toggle">لا يحتوي إصدار Android هذا على مفتاح لذلك، لذا يغيّره DroidDeck عبر تصحيح الأخطاء اللاسلكي. يستغرق نحو دقيقة، ولا يحتاج إلى جهاز كمبيوتر.</string> <string name="gate_needs_wifi">يحتاج تصحيح الأخطاء اللاسلكي إلى Wi-Fi. تعمل أي شبكة؛ فهو لا يحتاج إلى اتصال بالإنترنت.</string> - <string name="gate_needs_notifications">يظهر رمز الإقران في إشعار. فعِّل الإشعارات لـ DroidDeck، أو استخدم «طرق أخرى».</string> - <string name="gate_allow_notifications">السماح بالإشعارات</string> <string name="gate_step1">افتح الإعدادات ← خيارات المطوّرين ← تصحيح الأخطاء اللاسلكي وفعِّله</string> <string name="gate_step2">اضغط على «إقران جهاز برمز إقران»</string> <string name="gate_step3">أدخل الرمز في إشعار DroidDeck</string> @@ -1326,48 +1320,13 @@ <string name="gate_status">الحالة</string> <string name="gate_polling">يتم التحقّق كل ثانيتين. تُغلَق هذه الصفحة عند إيقافه.</string> <string name="gate_other_ways">طرق أخرى</string> - <string name="gate_other_toggle">تصحيح الأخطاء اللاسلكي، عنوان يدوي، ADB من كمبيوتر</string> - <string name="gate_other_no_toggle">عنوان يدوي، ADB من كمبيوتر، خيارات المطوّرين</string> <string name="gate_use_wireless_instead">استخدام تصحيح الأخطاء اللاسلكي بدلًا من ذلك</string> <string name="gate_some_roms">تضيف بعض إصدارات ROM هذا المفتاح رغم ذلك. ابحث عن «العمليات الفرعية» في خيارات المطوّرين.</string> - <string name="gate_manual_hint">إذا لم ينجح الإشعار، أدخل عنوان النافذة المنبثقة ورمزها بنفسك.</string> - <string name="gate_enter_manually">إدخال العنوان يدويًا</string> <string name="gate_from_computer">من جهاز كمبيوتر يحتوي على ADB:</string> <string name="gate_copy_command">نسخ الأمر</string> <string name="gate_sidequest_steps">وصّل النظارة بالكمبيوتر وافتح SideQuest. اختر “Run ADB Command” ثم “Custom Command”، واكتب الأمر الظاهر أدناه، ثم اختر “Run Command”.</string> <string name="gate_choose_display">اختر الشاشة التي ستُفتَح فيها إعدادات Android.</string> <string name="gate_main_screen">الشاشة الرئيسية</string> - <string name="wadb_finding_port">تم الإقران. جارٍ البحث عن منفذ تصحيح الأخطاء اللاسلكي…</string> - <string name="wadb_enter_port">تم الإقران. أدخل المنفذ من الإعدادات.</string> - <string name="wadb_applying">تم العثور على الجهاز. جارٍ تطبيق الإعداد…</string> - <string name="wadb_apply_failed">تعذّر التطبيق تلقائيًا. تحقّق من العنوان أدناه وأعد المحاولة. %1$s</string> - <string name="wadb_title_wireless">تصحيح الأخطاء اللاسلكي</string> - <string name="wadb_title_done">تم تحديث حد العمليات الفرعية</string> - <string name="wadb_title">تغيير حد العمليات الفرعية</string> - <string name="wadb_lede_compact0">إذا كان هذا الخيار غير متاح، فأقرن عبر تصحيح الأخطاء اللاسلكي.</string> - <string name="wadb_lede_compact1">تم الإقران. تحقّق من عنوان IP والمنفذ في تصحيح الأخطاء اللاسلكي.</string> - <string name="wadb_lede_done">تم تحديث حد العمليات الفرعية.</string> - <string name="wadb_lede0">استخدم الخطوة 2 إذا لم يكن في خيارات المطوّرين إعداد للعمليات الفرعية. افتح خيارات المطوّرين ← تصحيح الأخطاء اللاسلكي ← إقران جهاز برمز إقران.</string> - <string name="wadb_lede1">تم الإقران. استخدم العنوان أدناه، أو حدِّثه من تصحيح الأخطاء اللاسلكي ← عنوان IP والمنفذ.</string> - <string name="wadb_lede_done_long">تم تحديث حد العمليات الفرعية عبر تصحيح الأخطاء اللاسلكي.</string> - <string name="wadb_confirmed_on">أكّد Android أن الحد مفعّل.</string> - <string name="wadb_confirmed_off">أكّد Android أن الحد معطّل.</string> - <string name="wadb_pair_group">2 · إقران تصحيح الأخطاء اللاسلكي</string> - <string name="wadb_pair_address">عنوان IP ومنفذ النافذة المنبثقة للإقران</string> - <string name="wadb_pin">رمز الإقران (PIN)</string> - <string name="wadb_pin_placeholder">6 أرقام</string> - <string name="wadb_pair">إقران</string> - <string name="wadb_apply_group">2 · التطبيق عبر تصحيح الأخطاء اللاسلكي</string> - <string name="wadb_connect_address">عنوان IP ومنفذ الاتصال</string> - <string name="wadb_pair_again">إقران مرة أخرى</string> - <string name="wadb_turn_off">إيقاف الحد</string> - <string name="wadb_other_ways">طرق أخرى لتغييره</string> - <string name="wadb_dev_try_first">1 · خيارات المطوّرين (جرّب هذا أولًا)</string> - <string name="wadb_restrict_on">عطِّل «إيقاف القيود المفروضة على العمليات الثانوية».</string> - <string name="wadb_restrict_off">فعِّل «إيقاف القيود المفروضة على العمليات الثانوية».</string> - <string name="wadb_computer_last">3 · ADB من كمبيوتر (كخيار أخير)</string> - <string name="wadb_only_if">فقط إذا كان تصحيح الأخطاء اللاسلكي غير متاح.</string> - <string name="wadb_computer_group">3 · ADB من كمبيوتر (كخيار أخير)</string> <string name="ctrl_color">اللون</string> <string name="ctrl_custom">مخصّص</string> <string name="ctrl_opacity">العتامة</string> @@ -1679,8 +1638,6 @@ <item quantity="many">تم محو %1$d مجلدًا لسجلات الجلسات.</item> <item quantity="other">تم محو %1$d مجلد لسجلات الجلسات.</item> </plurals> - <string name="main_wadb_pair_failed">فشل الإقران عبر تصحيح الأخطاء اللاسلكي</string> - <string name="main_wadb_command_failed">فشل أمر تصحيح الأخطاء اللاسلكي</string> <string name="main_wadb_unavailable">تصحيح الأخطاء اللاسلكي غير متاح</string> <string name="main_adb_copied">تم نسخ أمر ADB</string> <string name="main_pick_roms">اختر مجلد ROMs</string> @@ -2565,10 +2522,16 @@ <string name="driver_tag_bundle">Android + Linux</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">شاشة الجلسة</string> - <string name="display_resolution">الدقة</string> + <string name="display_zero_copy">العرض بدون نسخ</string> + <string name="display_resolution_landscape">دقة الوضع الأفقي</string> + <string name="display_resolution_portrait">دقة الوضع العمودي</string> + <string name="display_follow_landscape">اتباع الأفقي (%1$d×%2$d)</string> + <string name="display_follow_portrait">اتباع العمودي (%1$d×%2$d)</string> <string name="display_game_fit">ملاءمة اللعبة لنسبة 16:9</string> <string name="display_game_fit_hint">كيفية ملاءمة ألعاب 16:9 لهذه الشاشة. يُطبَّق في الجلسة التالية.</string> <string name="display_game_fit_unavailable">اختر «مطابقة الشاشة» أو حجمًا مخصَّصًا أضيق من 16:9.</string> + <string name="display_avoid_notch">تجنّب فتحة الكاميرا</string> + <string name="display_avoid_notch_hint">يُبقي الصورة بعيدًا عن فتحة الكاميرا. يُطبَّق عند العودة إلى الجلسة.</string> <string name="display_preserve">الحفاظ على النسب</string> <string name="display_stretch">تمديد لملء الشاشة</string> <string name="display_image_scaling">تكبير الصورة</string> @@ -2855,6 +2818,7 @@ <string name="stores_login_error_ssl">الاتصال بصفحة تسجيل الدخول غير آمن.</string> <string name="stores_login_error_verification">تعذّر التحقّق من تسجيل الدخول. حاوِل مرة أخرى.</string> <string name="stores_login_error_generic">فشل تسجيل الدخول. حاوِل مرة أخرى.</string> + <string name="stores_login_continue_in_browser">يحتاج %1$s إلى خطوة أخرى. أكملها في المتصفح الذي فُتح، ثم حاول مرة أخرى.</string> <string name="common_close">إغلاق</string> <string name="common_back">رجوع</string> <string name="common_edit">تعديل</string> @@ -3255,7 +3219,7 @@ <string name="hand_camera_done">تم</string> <string name="glasses_xreal_network_missing">في انتظار اتصال USB Ethernet الخاص بالنظارة. قد لا يتيحه هذا الهاتف للتطبيقات.</string> <string name="glasses_xreal_connection_failed">انقطع اتصال XREAL أو أعاد استجابة غير مدعومة. جارٍ إعادة المحاولة…</string> - <string name="glasses_xreal_experimental">دعم تجريبي لـ 1S. استخدم وضع Follow وعطّل تثبيت الصورة من قائمة النظارة. لا تزال اتجاهات التتبّع وأوضاع العرض بحاجة إلى اختبار على الجهاز.</string> + <string name="glasses_xreal_experimental">دعم تجريبي لـ XREAL 1S وOne وOne Pro وOne Pro+ وAura. استخدم وضع Follow وأوقف تثبيت الصورة في قائمة النظارة؛ وعلى Aura، أوقف Spatial Anchor أيضًا. تم اختبار تتبع الرأس والتبديل بين 2D/3D على Aura وOne Pro+.</string> <string name="glasses_pro2_experimental">تتبّع تجريبي لحركة الرأس لنظارة Pro 2. لا يُدعم بعد ضبط السطوع ومستوى الصوت أو تبديل وضع العرض.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">وضع Cardboard</string> @@ -4170,6 +4134,7 @@ <string name="addons_sort_downloads">الأكثر تنزيلًا</string> <string name="addons_category_all">كل الفئات</string> <string name="addons_none_found">لم يتم العثور على إضافات</string> + <string name="addons_curse_busy">أغلق CurseForge أولاً</string> <string name="addons_unreachable">تعذّر الوصول إلى %1$s</string> <string name="addons_no_file">لا يوجد ملف لإصدار اللعبة هذا</string> <string name="input_reset_positions">إعادة تعيين المواضع</string> @@ -4273,4 +4238,6 @@ <string name="theme_custom_signal">الإبرازات</string> <string name="theme_custom_good">نجاح</string> <string name="theme_custom_error">خطأ</string> + <string name="hud_only_during_game">عرض HUD أثناء اللعب فقط</string> + <string name="hud_only_during_game_hint">إخفاء HUD عند عدم اكتشاف إطارات اللعبة.</string> </resources> diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 922b1407f3..c1314a8bd6 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Salida HDR10</string> <string name="mode_hdr_unavailable">No disponible: %1$s.</string> - <string name="mode_hdr_restart">Reinicia la app para aplicarlo.</string> <string name="mode_drivers">Controladores</string> <string name="mode_gpu_drivers">Controladores de GPU</string> <string name="mode_gpu_drivers_hint">Compartidos por Steam y Escritorio. Se definen en la página Componentes.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Inicio</string> <string name="mode_startup_session">Abrir al iniciar</string> <string name="mode_startup_session_hint">Inicia esta sesión cuando se abre DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Buscando versiones…</string> <string name="mode_decky_ready">Listo para instalar %1$s.</string> <string name="mode_decky_none">No se encontró ninguna versión compatible. Inténtalo más tarde.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Al día · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Instalar la última</string> - <string name="decky_channel">Canal de actualizaciones</string> - <string name="decky_channel_hint">Qué versiones de Decky Loader se instalan. El actualizador propio de Decky usa el mismo canal.</string> <string name="decky_channel_stable">Estable</string> <string name="decky_channel_prerelease">Preliminar</string> <string name="decky_channel_testing">Pruebas</string> <string name="decky_channel_failed">No se pudo guardar el canal de actualizaciones de Decky</string> - <string name="mode_decky_on">Se inicia con Steam. Mientras esté activado, otras apps de este dispositivo podrían controlar Steam.</string> - <string name="mode_decky_off">Desactivado. El puerto de depuración remota de Steam permanece cerrado.</string> <string name="mode_decky_remove_title">¿Desinstalar Decky Loader?</string> <string name="mode_decky_remove_text">Elimina el loader. Tus plugins y ajustes se conservan.</string> <string name="mode_client">Cliente</string> @@ -983,13 +977,15 @@ <string name="setup_launcher_orientation_auto">Seguir la rotación del dispositivo</string> <string name="setup_orientation_portrait">Vertical</string> <string name="setup_session_orientation">Orientación de la sesión</string> - <string name="setup_session_orientation_hint">Se aplica a Steam, los juegos, el escritorio y el editor de controles. Los ajustes predefinidos de resolución giran con la sesión; el ancho y el alto personalizados se mantienen como se ingresaron.</string> + <string name="setup_session_orientation_hint">Se aplica a Steam, los juegos, el escritorio y el editor de controles. Los ajustes predefinidos de resolución giran con la sesión; cuando una orientación sigue a la otra, el ancho y el alto personalizados se invierten para coincidir.</string> <string name="setup_orientation_auto">Horizontal automática</string> <string name="setup_orientation_landscape">Horizontal</string> <string name="setup_orientation_reverse">Horizontal invertida</string> <string name="setup_fullscreen">Pantalla completa</string> <string name="setup_fullscreen_on">Oculta las barras de estado y navegación de Android</string> <string name="setup_fullscreen_off">Muestra las barras de estado y navegación de Android</string> + <string name="setup_page_swipe">Deslizar entre páginas</string> + <string name="setup_page_swipe_hint">Desliza sobre una página para cambiar de pestaña.</string> <string name="setup_dual_screen_launcher">Lanzador de doble pantalla</string> <string name="setup_dual_screen_launcher_hint">Automático coloca las secciones del lanzador (Steam, Biblioteca, Tiendas y las demás) en la segunda pantalla integrada de las consolas portátiles que la tienen. Activado usa cualquier segunda pantalla. Desactivado mantiene el lanzador en una sola pantalla.</string> <string name="setup_dual_screen_sessions">Sesiones de doble pantalla</string> @@ -1314,8 +1310,6 @@ <string name="gate_open_dev">Abrir Opciones de desarrollador</string> <string name="gate_no_toggle">Esta versión de Android no tiene un interruptor para ello, así que DroidDeck lo cambia mediante la Depuración inalámbrica. Tarda un minuto y no necesitas una computadora.</string> <string name="gate_needs_wifi">La Depuración inalámbrica necesita Wi-Fi. Sirve cualquier red; no necesita internet.</string> - <string name="gate_needs_notifications">El código de vinculación aparece en una notificación. Permite las notificaciones de DroidDeck o usa Otras formas.</string> - <string name="gate_allow_notifications">Permitir notificaciones</string> <string name="gate_step1">Abre Ajustes → Opciones de desarrollador → Depuración inalámbrica y actívala</string> <string name="gate_step2">Toca “Vincular dispositivo con código de vinculación”</string> <string name="gate_step3">Escribe el código en la notificación de DroidDeck</string> @@ -1332,48 +1326,13 @@ <string name="gate_status">Estado</string> <string name="gate_polling">Se comprueba cada 2 segundos. Esta página se cierra cuando esté desactivado.</string> <string name="gate_other_ways">Otras formas</string> - <string name="gate_other_toggle">Depuración inalámbrica, dirección manual, ADB desde una computadora</string> - <string name="gate_other_no_toggle">Dirección manual, ADB desde una computadora, Opciones de desarrollador</string> <string name="gate_use_wireless_instead">Usar Depuración inalámbrica en su lugar</string> <string name="gate_some_roms">Algunas ROM agregan el interruptor de todos modos. Busca “procesos secundarios” en Opciones de desarrollador.</string> - <string name="gate_manual_hint">Si la notificación no funciona, ingresa manualmente la dirección y el código de la ventana.</string> - <string name="gate_enter_manually">Ingresar dirección manualmente</string> <string name="gate_from_computer">Desde una computadora con ADB:</string> <string name="gate_copy_command">Copiar comando</string> <string name="gate_sidequest_steps">Conecta el visor a una computadora y abre SideQuest. Elige “Run ADB Command” y luego “Custom Command”, escribe el comando que aparece abajo y selecciona “Run Command”.</string> <string name="gate_choose_display">Elige en qué pantalla abrir los Ajustes de Android.</string> <string name="gate_main_screen">Pantalla principal</string> - <string name="wadb_finding_port">Vinculado. Buscando el puerto de la Depuración inalámbrica…</string> - <string name="wadb_enter_port">Vinculado. Ingresa el puerto de Ajustes.</string> - <string name="wadb_applying">Dispositivo encontrado. Aplicando el ajuste…</string> - <string name="wadb_apply_failed">No se pudo aplicar automáticamente. Revisa la dirección de abajo y reintenta. %1$s</string> - <string name="wadb_title_wireless">Depuración inalámbrica</string> - <string name="wadb_title_done">Límite de procesos secundarios actualizado</string> - <string name="wadb_title">Cambiar el límite de procesos secundarios</string> - <string name="wadb_lede_compact0">Si falta la opción, vincula mediante la Depuración inalámbrica.</string> - <string name="wadb_lede_compact1">Vinculado. Revisa la dirección IP y el puerto en Depuración inalámbrica.</string> - <string name="wadb_lede_done">El límite de procesos secundarios se actualizó.</string> - <string name="wadb_lede0">Usa el paso 2 si las Opciones de desarrollador no tienen un ajuste de procesos secundarios. Abre Opciones de desarrollador → Depuración inalámbrica → Vincular dispositivo con código de vinculación.</string> - <string name="wadb_lede1">Vinculado. Usa la dirección de abajo o actualízala desde Depuración inalámbrica → Dirección IP y puerto.</string> - <string name="wadb_lede_done_long">El límite de procesos secundarios se actualizó mediante la Depuración inalámbrica.</string> - <string name="wadb_confirmed_on">Android confirmó que el límite está activado.</string> - <string name="wadb_confirmed_off">Android confirmó que el límite está desactivado.</string> - <string name="wadb_pair_group">2 · Vincular Depuración inalámbrica</string> - <string name="wadb_pair_address">Dirección IP y puerto de la ventana de vinculación</string> - <string name="wadb_pin">Código de vinculación (PIN)</string> - <string name="wadb_pin_placeholder">6 dígitos</string> - <string name="wadb_pair">Vincular</string> - <string name="wadb_apply_group">2 · Aplicar mediante Depuración inalámbrica</string> - <string name="wadb_connect_address">Dirección IP y puerto de conexión</string> - <string name="wadb_pair_again">Vincular de nuevo</string> - <string name="wadb_turn_off">Desactivar límite</string> - <string name="wadb_other_ways">Otras formas de cambiarlo</string> - <string name="wadb_dev_try_first">1 · Opciones de desarrollador (pruébalo primero)</string> - <string name="wadb_restrict_on">Desactiva “Inhabilitar restricciones de procesos secundarios”.</string> - <string name="wadb_restrict_off">Activa “Inhabilitar restricciones de procesos secundarios”.</string> - <string name="wadb_computer_last">3 · ADB desde una computadora (último recurso)</string> - <string name="wadb_only_if">Solo si la Depuración inalámbrica no está disponible.</string> - <string name="wadb_computer_group">3 · ADB desde una computadora (último recurso)</string> <string name="ctrl_color">Color</string> <string name="ctrl_custom">Personalizado</string> <string name="ctrl_opacity">Opacidad</string> @@ -1428,7 +1387,7 @@ <string name="hand_camera_done">Hecho</string> <string name="glasses_xreal_network_missing">Esperando la conexión Ethernet por USB de las gafas. Puede que este teléfono no la ofrezca a las apps.</string> <string name="glasses_xreal_connection_failed">La conexión con las XREAL se interrumpió o devolvió una respuesta no compatible. Reintentando…</string> - <string name="glasses_xreal_experimental">Compatibilidad experimental con las 1S. Usa el modo Follow y desactiva la estabilización en el menú de las gafas. Aún falta probar en el dispositivo las direcciones del seguimiento y los modos de pantalla.</string> + <string name="glasses_xreal_experimental">Compatibilidad experimental con XREAL 1S, One, One Pro, One Pro+ y Aura. Usa el modo Follow y desactiva la estabilización en el menú de las gafas; en Aura, desactiva también Spatial Anchor. El seguimiento de cabeza y el cambio entre 2D/3D se han probado en Aura y One Pro+.</string> <string name="glasses_pro2_experimental">Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles.</string> <string name="setup_animations">Animaciones</string> <string name="setup_low_storage_warning">Avisar cuando queda poco almacenamiento</string> @@ -1710,8 +1669,6 @@ <item quantity="other">Se borraron %1$d carpetas de registros de sesión.</item> <item quantity="many">Se borraron %1$d carpetas de registros de sesión.</item> </plurals> - <string name="main_wadb_pair_failed">Falló la vinculación de la Depuración inalámbrica</string> - <string name="main_wadb_command_failed">Falló el comando de la Depuración inalámbrica</string> <string name="main_wadb_unavailable">La Depuración inalámbrica no está disponible</string> <string name="main_adb_copied">Comando ADB copiado</string> <string name="main_pick_roms">Elige la carpeta de ROMs</string> @@ -2557,10 +2514,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Pantalla de la sesión</string> - <string name="display_resolution">Resolución</string> + <string name="display_zero_copy">Presentación sin copia</string> + <string name="display_resolution_landscape">Resolución horizontal</string> + <string name="display_resolution_portrait">Resolución vertical</string> + <string name="display_follow_landscape">Igual que horizontal (%1$d×%2$d)</string> + <string name="display_follow_portrait">Igual que vertical (%1$d×%2$d)</string> <string name="display_game_fit">Ajuste de juegos 16:9</string> <string name="display_game_fit_hint">Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión.</string> <string name="display_game_fit_unavailable">Elige Igual a la pantalla o un tamaño personalizado más estrecho que 16:9.</string> + <string name="display_avoid_notch">Evitar la muesca</string> + <string name="display_avoid_notch_hint">Mantiene la imagen fuera del recorte de la cámara. Se aplica al volver a la sesión.</string> <string name="display_preserve">Mantener proporciones</string> <string name="display_stretch">Estirar a la pantalla</string> <string name="display_image_scaling">Escalado de imagen</string> @@ -2821,6 +2784,7 @@ <string name="stores_login_error_ssl">La conexión con la página de inicio de sesión no es segura.</string> <string name="stores_login_error_verification">No se pudo verificar el inicio de sesión. Inténtalo de nuevo.</string> <string name="stores_login_error_generic">No se pudo iniciar sesión. Inténtalo de nuevo.</string> + <string name="stores_login_continue_in_browser">%1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo.</string> <string name="common_close">Cerrar</string> <string name="common_back">Atrás</string> <string name="common_edit">Editar</string> @@ -4050,6 +4014,7 @@ <string name="addons_sort_downloads">Más descargados</string> <string name="addons_category_all">Todas las categorías</string> <string name="addons_none_found">No se encontraron complementos</string> + <string name="addons_curse_busy">Cierra CurseForge primero</string> <string name="addons_unreachable">No se pudo conectar con %1$s</string> <string name="addons_no_file">No hay archivo para esta versión del juego</string> <string name="input_reset_positions">Restablecer posiciones</string> @@ -4153,4 +4118,6 @@ <string name="theme_custom_signal">Destacados</string> <string name="theme_custom_good">Éxito</string> <string name="theme_custom_error">Error</string> + <string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string> + <string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string> </resources> diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 57566ec959..2ab13542e9 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 изход</string> <string name="mode_hdr_unavailable">Не е налично: %1$s.</string> - <string name="mode_hdr_restart">Рестартирайте приложението, за да се приложи.</string> <string name="mode_drivers">Драйвери</string> <string name="mode_gpu_drivers">GPU драйвери</string> <string name="mode_gpu_drivers_hint">Общи за Steam и работния плот. Задават се в страницата Компоненти.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Стартиране</string> <string name="mode_startup_session">Отваряне при стартиране</string> <string name="mode_startup_session_hint">Стартира тази сесия, когато DroidDeck се стартира.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Проверка за издания…</string> <string name="mode_decky_ready">Готово за инсталиране на %1$s.</string> <string name="mode_decky_none">Не е намерена съвместима версия. Опитайте по-късно.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Актуално · %1$s</string> <string name="mode_decky_loader">Зареждач</string> <string name="mode_decky_install_latest">Инсталиране на последната версия</string> - <string name="decky_channel">Канал за актуализации</string> - <string name="decky_channel_hint">Кои издания на Decky Loader да се инсталират. Собственият актуализатор на Decky използва същия канал.</string> <string name="decky_channel_stable">Стабилен</string> <string name="decky_channel_prerelease">Предварителен</string> <string name="decky_channel_testing">Тестов</string> <string name="decky_channel_failed">Каналът за актуализации на Decky не можа да бъде запазен</string> - <string name="mode_decky_on">Стартира заедно със Steam. Докато е включено, други приложения на това устройство може да могат да контролират Steam.</string> - <string name="mode_decky_off">Изключено. Портът за отдалечено дебъгване на Steam остава затворен.</string> <string name="mode_decky_remove_title">Деинсталиране на Decky Loader?</string> <string name="mode_decky_remove_text">Премахва зареждащия модул. Плъгините и настройките ви се запазват.</string> <string name="mode_client">Клиент</string> @@ -953,13 +947,15 @@ <string name="setup_launcher_orientation_auto">Следва завъртането на устройството</string> <string name="setup_orientation_portrait">Вертикална</string> <string name="setup_session_orientation">Ориентация на сесията</string> - <string name="setup_session_orientation_hint">Прилага се за Steam, игрите, работния плот и редактора на контролера. Предварително зададените резолюции се завъртат със сесията; персонализираните ширина и височина остават както са въведени.</string> + <string name="setup_session_orientation_hint">Прилага се за Steam, игрите, работния плот и редактора на контролера. Предварително зададените резолюции се завъртат със сесията; когато едната ориентация следва другата, персонализираните ширина и височина се разменят, за да съвпадат.</string> <string name="setup_orientation_auto">Автоматичен хоризонтален</string> <string name="setup_orientation_landscape">Хоризонтална</string> <string name="setup_orientation_reverse">Обърната хоризонтална</string> <string name="setup_fullscreen">Цял екран</string> <string name="setup_fullscreen_on">Скрива лентите за състояние и навигация на Android</string> <string name="setup_fullscreen_off">Показва лентите за състояние и навигация на Android</string> + <string name="setup_page_swipe">Плъзгане между страниците</string> + <string name="setup_page_swipe_hint">Плъзнете по страница, за да смените раздела.</string> <string name="setup_dual_screen_launcher">Лаунчер с два екрана</string> <string name="setup_dual_screen_launcher_hint">Автоматично: секциите на лаунчера (Steam, Библиотека, Магазини и останалите) се показват на втория екран при преносими устройства с вграден такъв. Включено: използва се всеки втори дисплей. Изключено: лаунчерът остава на един екран.</string> <string name="setup_dual_screen_sessions">Сесии с два екрана</string> @@ -1280,8 +1276,6 @@ <string name="gate_open_dev">Отваряне на Опции за програмисти</string> <string name="gate_no_toggle">Тази версия на Android няма превключвател за това, затова DroidDeck го променя чрез безжично отстраняване на грешки. Отнема около минута, не е нужен компютър.</string> <string name="gate_needs_wifi">Безжичното отстраняване на грешки изисква Wi-Fi. Работи с всяка мрежа; не е необходим интернет.</string> - <string name="gate_needs_notifications">Кодът за сдвояване се показва в известие. Разрешете известията за DroidDeck или използвайте „Други начини“.</string> - <string name="gate_allow_notifications">Разрешаване на известията</string> <string name="gate_step1">Отворете Настройки → Опции за програмисти → Безжично отстраняване на грешки и го включете</string> <string name="gate_step2">Докоснете „Сдвояване на устройство с код за сдвояване“</string> <string name="gate_step3">Въведете кода в известието на DroidDeck</string> @@ -1298,48 +1292,13 @@ <string name="gate_status">Състояние</string> <string name="gate_polling">Проверява се на всеки 2 секунди. Тази страница се затваря, когато е изключено.</string> <string name="gate_other_ways">Други начини</string> - <string name="gate_other_toggle">Безжично отстраняване на грешки, ръчен адрес, ADB от компютър</string> - <string name="gate_other_no_toggle">Ръчен адрес, ADB от компютър, Опции за програмисти</string> <string name="gate_use_wireless_instead">Използване на безжично отстраняване на грешки вместо това</string> <string name="gate_some_roms">Някои ROM-и добавят превключвателя въпреки това. Потърсете „child process“ в Опции за програмисти.</string> - <string name="gate_manual_hint">Ако известието не работи, въведете сами адреса и кода от изскачащия прозорец.</string> - <string name="gate_enter_manually">Ръчно въвеждане на адреса</string> <string name="gate_from_computer">От компютър с ADB:</string> <string name="gate_copy_command">Копиране на командата</string> <string name="gate_sidequest_steps">Свържете шлема с компютър и отворете SideQuest. Изберете „Run ADB Command“, после „Custom Command“, въведете командата, показана по-долу, и изберете „Run Command“.</string> <string name="gate_choose_display">Изберете на кой екран да се отворят настройките на Android.</string> <string name="gate_main_screen">Основен екран</string> - <string name="wadb_finding_port">Сдвоено. Търсене на порта за безжично отстраняване на грешки…</string> - <string name="wadb_enter_port">Сдвоено. Въведете порта от Настройки.</string> - <string name="wadb_applying">Устройството е намерено. Прилагане на настройката…</string> - <string name="wadb_apply_failed">Не можа да се приложи автоматично. Проверете адреса по-долу и опитайте отново. %1$s</string> - <string name="wadb_title_wireless">Безжично отстраняване на грешки</string> - <string name="wadb_title_done">Ограничението на дъщерните процеси е актуализирано</string> - <string name="wadb_title">Промяна на ограничението на дъщерните процеси</string> - <string name="wadb_lede_compact0">Ако опцията липсва, сдвоете чрез безжично отстраняване на грешки.</string> - <string name="wadb_lede_compact1">Сдвоено. Проверете IP адреса и порта в безжичното отстраняване на грешки.</string> - <string name="wadb_lede_done">Ограничението на дъщерните процеси беше актуализирано.</string> - <string name="wadb_lede0">Използвайте стъпка 2, ако Опции за програмисти нямат настройка за дъщерни процеси. Отворете Опции за програмисти → Безжично отстраняване на грешки → Сдвояване на устройство с код за сдвояване.</string> - <string name="wadb_lede1">Сдвоено. Използвайте адреса по-долу или го обновете от Безжично отстраняване на грешки → IP адрес и порт.</string> - <string name="wadb_lede_done_long">Ограничението на дъщерните процеси беше актуализирано чрез безжично отстраняване на грешки.</string> - <string name="wadb_confirmed_on">Android потвърди, че ограничението е включено.</string> - <string name="wadb_confirmed_off">Android потвърди, че ограничението е изключено.</string> - <string name="wadb_pair_group">2 · Сдвояване на безжично отстраняване на грешки</string> - <string name="wadb_pair_address">IP адрес и порт на изскачащия прозорец за сдвояване</string> - <string name="wadb_pin">Код за сдвояване (PIN)</string> - <string name="wadb_pin_placeholder">6 цифри</string> - <string name="wadb_pair">Сдвояване</string> - <string name="wadb_apply_group">2 · Прилагане чрез безжично отстраняване на грешки</string> - <string name="wadb_connect_address">IP адрес и порт за връзка</string> - <string name="wadb_pair_again">Сдвояване отново</string> - <string name="wadb_turn_off">Изключване на ограничението</string> - <string name="wadb_other_ways">Други начини за промяна</string> - <string name="wadb_dev_try_first">1 · Опции за програмисти (пробвайте първо)</string> - <string name="wadb_restrict_on">Изключете „Деактивиране на ограниченията за дъщерните процеси“.</string> - <string name="wadb_restrict_off">Включете „Деактивиране на ограниченията за дъщерните процеси“.</string> - <string name="wadb_computer_last">3 · ADB от компютър (последна възможност)</string> - <string name="wadb_only_if">Само ако безжичното отстраняване на грешки не е достъпно.</string> - <string name="wadb_computer_group">3 · ADB от компютър (последна възможност)</string> <string name="ctrl_color">Цвят</string> <string name="ctrl_custom">Персонализиран</string> <string name="ctrl_opacity">Прозрачност</string> @@ -1627,8 +1586,6 @@ <item quantity="one">Изчистена %1$d папка с логове от сесия.</item> <item quantity="other">Изчистени %1$d папки с логове от сесии.</item> </plurals> - <string name="main_wadb_pair_failed">Чифтосването за безжично отстраняване на грешки се провали</string> - <string name="main_wadb_command_failed">Командата за безжично отстраняване на грешки се провали</string> <string name="main_wadb_unavailable">Безжичното отстраняване на грешки не е достъпно</string> <string name="main_adb_copied">Командата за ADB е копирана</string> <string name="main_pick_roms">Избор на папката ROMs</string> @@ -2461,10 +2418,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Екран на сесията</string> - <string name="display_resolution">Разделителна способност</string> + <string name="display_zero_copy">Представяне без копиране</string> + <string name="display_resolution_landscape">Резолюция в пейзажен режим</string> + <string name="display_resolution_portrait">Резолюция в портретен режим</string> + <string name="display_follow_landscape">Като пейзажния (%1$d×%2$d)</string> + <string name="display_follow_portrait">Като портретния (%1$d×%2$d)</string> <string name="display_game_fit">Напасване на игра 16:9</string> <string name="display_game_fit_hint">Как игрите с 16:9 се напасват на този екран. При следващата сесия.</string> <string name="display_game_fit_unavailable">Избери „Напасване на екрана“ или собствен размер, по-тесен от 16:9.</string> + <string name="display_avoid_notch">Избягване на прореза</string> + <string name="display_avoid_notch_hint">Държи картината извън прореза за камерата. Важи при връщане към сесията.</string> <string name="display_preserve">Запазване на пропорциите</string> <string name="display_stretch">Разтягане до екрана</string> <string name="display_image_scaling">Мащабиране на изображението</string> @@ -2751,6 +2714,7 @@ <string name="stores_login_error_ssl">Връзката със страницата за вход не е защитена.</string> <string name="stores_login_error_verification">Входът не можа да бъде потвърден. Опитай отново.</string> <string name="stores_login_error_generic">Входът се провали. Опитай отново.</string> + <string name="stores_login_continue_in_browser">%1$s изисква още една стъпка. Завърши я в браузъра, който се отвори, и опитай отново.</string> <string name="common_close">Затвори</string> <string name="common_back">Назад</string> <string name="common_edit">Редактирай</string> @@ -3135,7 +3099,7 @@ <string name="hand_camera_done">Готово</string> <string name="glasses_xreal_network_missing">Изчаква се USB Ethernet връзката на очилата. Този телефон може да не я предоставя на приложенията.</string> <string name="glasses_xreal_connection_failed">Връзката с XREAL беше прекъсната или върна неподдържан отговор. Нов опит…</string> - <string name="glasses_xreal_experimental">Експериментална поддръжка на 1S. Използвайте режим Follow и изключете стабилизацията в менюто на очилата. Посоките на проследяване и режимите на показване все още трябва да се тестват на устройство.</string> + <string name="glasses_xreal_experimental">Експериментална поддръжка на XREAL 1S, One, One Pro, One Pro+ и Aura. Използвайте режим Follow и изключете стабилизацията в менюто на очилата; при Aura изключете и Spatial Anchor. Проследяването на главата и превключването между 2D/3D са тествани на Aura и One Pro+.</string> <string name="glasses_pro2_experimental">Експериментално проследяване на движенията на главата за Pro 2. Регулирането на яркостта и силата на звука и превключването на режима на показване все още не се поддържат.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Режим Cardboard</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">Най-изтегляни</string> <string name="addons_category_all">Всички категории</string> <string name="addons_none_found">Няма намерени добавки</string> + <string name="addons_curse_busy">Първо затворете CurseForge</string> <string name="addons_unreachable">Няма връзка с %1$s</string> <string name="addons_no_file">Няма файл за тази версия на играта</string> <string name="input_reset_positions">Нулиране на позициите</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">Акценти</string> <string name="theme_custom_good">Успех</string> <string name="theme_custom_error">Грешка</string> + <string name="hud_only_during_game">Показвай HUD само по време на игра</string> + <string name="hud_only_during_game_hint">Скривай HUD, когато не се засичат кадри от играта.</string> </resources> diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index c2b89c6e12..04231de374 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Výstup HDR10</string> <string name="mode_hdr_unavailable">Není k dispozici: %1$s.</string> - <string name="mode_hdr_restart">Pro použití restartujte aplikaci.</string> <string name="mode_drivers">Ovladače</string> <string name="mode_gpu_drivers">Ovladače GPU</string> <string name="mode_gpu_drivers_hint">Společné pro Steam a Plochu. Nastavuje se na stránce Komponenty.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Spouštění</string> <string name="mode_startup_session">Otevřít při spuštění</string> <string name="mode_startup_session_hint">Spustí tuto relaci při spuštění DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Hledání vydání…</string> <string name="mode_decky_ready">Připraveno k instalaci %1$s.</string> <string name="mode_decky_none">Nenalezeno žádné kompatibilní sestavení. Zkuste to později.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Aktuální · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Nainstalovat nejnovější</string> - <string name="decky_channel">Kanál aktualizací</string> - <string name="decky_channel_hint">Která vydání Decky Loader instalovat. Vlastní aktualizátor Decky používá stejný kanál.</string> <string name="decky_channel_stable">Stabilní</string> <string name="decky_channel_prerelease">Předběžné vydání</string> <string name="decky_channel_testing">Testovací</string> <string name="decky_channel_failed">Kanál aktualizací Decky se nepodařilo uložit</string> - <string name="mode_decky_on">Spouští se se Steamem. Když je zapnuto, jiné aplikace na tomto zařízení mohou mít možnost ovládat Steam.</string> - <string name="mode_decky_off">Vypnuto. Port pro vzdálené ladění Steamu zůstává zavřený.</string> <string name="mode_decky_remove_title">Odinstalovat Decky Loader?</string> <string name="mode_decky_remove_text">Odstraní loader. Vaše pluginy a nastavení zůstanou zachovány.</string> <string name="mode_client">Klient</string> @@ -959,13 +953,15 @@ <string name="setup_launcher_orientation_auto">Podle otočení zařízení</string> <string name="setup_orientation_portrait">Na výšku</string> <string name="setup_session_orientation">Orientace relace</string> - <string name="setup_session_orientation_hint">Platí pro Steam, hry, Plochu a editor ovladače. Předvolby rozlišení se otáčejí s relací; vlastní šířka a výška zůstávají, jak jsou zadány.</string> + <string name="setup_session_orientation_hint">Platí pro Steam, hry, Plochu a editor ovladače. Předvolby rozlišení se otáčejí s relací; když jedna orientace sleduje druhou, vlastní šířka a výška se prohodí, aby odpovídaly.</string> <string name="setup_orientation_auto">Automaticky na šířku</string> <string name="setup_orientation_landscape">Na šířku</string> <string name="setup_orientation_reverse">Na šířku obráceně</string> <string name="setup_fullscreen">Celá obrazovka</string> <string name="setup_fullscreen_on">Skryje stavový a navigační panel Androidu</string> <string name="setup_fullscreen_off">Zobrazí stavový a navigační panel Androidu</string> + <string name="setup_page_swipe">Přejíždění mezi stránkami</string> + <string name="setup_page_swipe_hint">Přejetím přes stránku přepnete kartu.</string> <string name="setup_dual_screen_launcher">Spouštěč na dvou obrazovkách</string> <string name="setup_dual_screen_launcher_hint">Automaticky přesune sekce spouštěče (Steam, Knihovna, Obchody a ostatní) na druhou obrazovku handheldů, které ji mají vestavěnou. Zapnuto použije libovolný druhý displej. Vypnuto ponechá spouštěč na jedné obrazovce.</string> <string name="setup_dual_screen_sessions">Relace na dvou obrazovkách</string> @@ -1294,8 +1290,6 @@ <string name="gate_open_dev">Otevřít Možnosti pro vývojáře</string> <string name="gate_no_toggle">Tato verze Androidu pro to nemá přepínač, proto to DroidDeck změní přes Bezdrátové ladění. Zabere to asi minutu, počítač není potřeba.</string> <string name="gate_needs_wifi">Bezdrátové ladění potřebuje Wi-Fi. Funguje jakákoli síť, internet není nutný.</string> - <string name="gate_needs_notifications">Párovací kód se zobrazí v oznámení. Povolte oznámení pro DroidDeck, nebo použijte Jiné způsoby.</string> - <string name="gate_allow_notifications">Povolit oznámení</string> <string name="gate_step1">Otevřete Nastavení → Možnosti pro vývojáře → Bezdrátové ladění a zapněte ho</string> <string name="gate_step2">Klepněte na „Spárovat zařízení pomocí párovacího kódu“</string> <string name="gate_step3">Zadejte kód do oznámení DroidDecku</string> @@ -1312,48 +1306,13 @@ <string name="gate_status">Stav</string> <string name="gate_polling">Kontroluje se každé 2 sekundy. Tato stránka se zavře, až bude vypnuto.</string> <string name="gate_other_ways">Jiné způsoby</string> - <string name="gate_other_toggle">Bezdrátové ladění, ruční adresa, ADB z počítače</string> - <string name="gate_other_no_toggle">Ruční adresa, ADB z počítače, Možnosti pro vývojáře</string> <string name="gate_use_wireless_instead">Použít místo toho Bezdrátové ladění</string> <string name="gate_some_roms">Některé ROM přepínač přidávají i tak. Hledejte v Možnostech pro vývojáře „child process“.</string> - <string name="gate_manual_hint">Pokud oznámení nefunguje, zadejte adresu a kód z okna sami.</string> - <string name="gate_enter_manually">Zadat adresu ručně</string> <string name="gate_from_computer">Z počítače s ADB:</string> <string name="gate_copy_command">Kopírovat příkaz</string> <string name="gate_sidequest_steps">Připojte headset k počítači a otevřete SideQuest. Zvolte „Run ADB Command“, pak „Custom Command“, opište příkaz zobrazený níže a vyberte „Run Command“.</string> <string name="gate_choose_display">Vyberte, na kterém displeji se má otevřít Nastavení Androidu.</string> <string name="gate_main_screen">Hlavní obrazovka</string> - <string name="wadb_finding_port">Spárováno. Hledání portu Bezdrátového ladění…</string> - <string name="wadb_enter_port">Spárováno. Zadejte port z Nastavení.</string> - <string name="wadb_applying">Zařízení nalezeno. Používá se nastavení…</string> - <string name="wadb_apply_failed">Nepodařilo se použít automaticky. Zkontrolujte adresu níže a zkuste to znovu. %1$s</string> - <string name="wadb_title_wireless">Bezdrátové ladění</string> - <string name="wadb_title_done">Omezení pro dětské procesy aktualizováno</string> - <string name="wadb_title">Změnit omezení pro dětské procesy</string> - <string name="wadb_lede_compact0">Pokud volba chybí, spárujte přes Bezdrátové ladění.</string> - <string name="wadb_lede_compact1">Spárováno. Zkontrolujte IP adresu a port v Bezdrátovém ladění.</string> - <string name="wadb_lede_done">Omezení pro dětské procesy bylo aktualizováno.</string> - <string name="wadb_lede0">Krok 2 použijte, pokud Možnosti pro vývojáře nemají nastavení pro dětské procesy. Otevřete Možnosti pro vývojáře → Bezdrátové ladění → Spárovat zařízení pomocí párovacího kódu.</string> - <string name="wadb_lede1">Spárováno. Použijte adresu níže, nebo ji aktualizujte z Bezdrátové ladění → IP adresa a port.</string> - <string name="wadb_lede_done_long">Omezení pro dětské procesy bylo aktualizováno přes Bezdrátové ladění.</string> - <string name="wadb_confirmed_on">Android potvrdil, že omezení je zapnuto.</string> - <string name="wadb_confirmed_off">Android potvrdil, že omezení je vypnuto.</string> - <string name="wadb_pair_group">2 · Spárovat Bezdrátové ladění</string> - <string name="wadb_pair_address">IP adresa a port párovacího okna</string> - <string name="wadb_pin">Párovací kód (PIN)</string> - <string name="wadb_pin_placeholder">6 číslic</string> - <string name="wadb_pair">Spárovat</string> - <string name="wadb_apply_group">2 · Použít přes Bezdrátové ladění</string> - <string name="wadb_connect_address">IP adresa a port pro připojení</string> - <string name="wadb_pair_again">Spárovat znovu</string> - <string name="wadb_turn_off">Vypnout omezení</string> - <string name="wadb_other_ways">Jiné způsoby změny</string> - <string name="wadb_dev_try_first">1 · Možnosti pro vývojáře (zkusit nejdřív)</string> - <string name="wadb_restrict_on">Vypněte „Deaktivace omezení podřízených procesů“.</string> - <string name="wadb_restrict_off">Zapněte „Deaktivace omezení podřízených procesů“.</string> - <string name="wadb_computer_last">3 · ADB z počítače (poslední možnost)</string> - <string name="wadb_only_if">Jen pokud Bezdrátové ladění není k dispozici.</string> - <string name="wadb_computer_group">3 · ADB z počítače (poslední možnost)</string> <string name="ctrl_color">Barva</string> <string name="ctrl_custom">Vlastní</string> <string name="ctrl_opacity">Průhlednost</string> @@ -1653,8 +1612,6 @@ <item quantity="many">Vyčištěno %1$d složek s logy relace.</item> <item quantity="other">Vyčištěno %1$d složek s logy relace.</item> </plurals> - <string name="main_wadb_pair_failed">Párování bezdrátového ladění se nezdařilo</string> - <string name="main_wadb_command_failed">Příkaz bezdrátového ladění se nezdařil</string> <string name="main_wadb_unavailable">Bezdrátové ladění není k dispozici</string> <string name="main_adb_copied">Příkaz ADB zkopírován</string> <string name="main_pick_roms">Vybrat složku ROMs</string> @@ -2513,10 +2470,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Obrazovka relace</string> - <string name="display_resolution">Rozlišení</string> + <string name="display_zero_copy">Zobrazení bez kopírování</string> + <string name="display_resolution_landscape">Rozlišení na šířku</string> + <string name="display_resolution_portrait">Rozlišení na výšku</string> + <string name="display_follow_landscape">Jako na šířku (%1$d×%2$d)</string> + <string name="display_follow_portrait">Jako na výšku (%1$d×%2$d)</string> <string name="display_game_fit">Přizpůsobení hry 16:9</string> <string name="display_game_fit_hint">Jak se hry s poměrem 16:9 přizpůsobí této obrazovce. Příští relace.</string> <string name="display_game_fit_unavailable">Vyberte Podle obrazovky nebo vlastní velikost užší než 16:9.</string> + <string name="display_avoid_notch">Vyhnout se výřezu</string> + <string name="display_avoid_notch_hint">Obraz zůstane mimo výřez kamery. Použije se po návratu do relace.</string> <string name="display_preserve">Zachovat proporce</string> <string name="display_stretch">Roztáhnout na obrazovku</string> <string name="display_image_scaling">Škálování obrazu</string> @@ -2803,6 +2766,7 @@ <string name="stores_login_error_ssl">Spojení s přihlašovací stránkou není zabezpečené.</string> <string name="stores_login_error_verification">Přihlášení se nepodařilo ověřit. Zkuste to znovu.</string> <string name="stores_login_error_generic">Přihlášení se nezdařilo. Zkuste to znovu.</string> + <string name="stores_login_continue_in_browser">%1$s vyžaduje ještě jeden krok. Dokončete ho v prohlížeči, který se otevřel, a zkuste to znovu.</string> <string name="common_close">Zavřít</string> <string name="common_back">Zpět</string> <string name="common_edit">Upravit</string> @@ -3195,7 +3159,7 @@ <string name="hand_camera_done">Hotovo</string> <string name="glasses_xreal_network_missing">Čeká se na připojení USB Ethernet brýlí. Tento telefon ho možná aplikacím nezpřístupňuje.</string> <string name="glasses_xreal_connection_failed">Připojení XREAL bylo přerušeno nebo vrátilo nepodporovanou odpověď. Zkouší se to znovu…</string> - <string name="glasses_xreal_experimental">Experimentální podpora 1S. V nabídce brýlí použijte režim Follow a vypněte stabilizaci. Směry sledování a režimy zobrazení je ještě třeba otestovat na zařízení.</string> + <string name="glasses_xreal_experimental">Experimentální podpora XREAL 1S, One, One Pro, One Pro+ a Aura. V nabídce brýlí použijte režim Follow a vypněte stabilizaci; u modelu Aura vypněte také Spatial Anchor. Sledování hlavy a přepínání 2D/3D bylo otestováno na modelech Aura a One Pro+.</string> <string name="glasses_pro2_experimental">Experimentální sledování pohybu hlavy pro Pro 2. Nastavení jasu, hlasitosti a přepínání režimů zobrazení zatím nejsou podporovány.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Režim Cardboard</string> @@ -4090,6 +4054,7 @@ <string name="addons_sort_downloads">Nejstahovanější</string> <string name="addons_category_all">Všechny kategorie</string> <string name="addons_none_found">Nenalezeny žádné doplňky</string> + <string name="addons_curse_busy">Nejprve zavřete CurseForge</string> <string name="addons_unreachable">Nelze se připojit k %1$s</string> <string name="addons_no_file">Pro tuto verzi hry není k dispozici soubor</string> <string name="input_reset_positions">Obnovit pozice</string> @@ -4193,4 +4158,6 @@ <string name="theme_custom_signal">Zvýraznění</string> <string name="theme_custom_good">Úspěch</string> <string name="theme_custom_error">Chyba</string> + <string name="hud_only_during_game">Zobrazovat HUD pouze během hry</string> + <string name="hud_only_during_game_hint">Skrýt HUD, když nejsou detekovány snímky hry.</string> </resources> diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 67037ab952..609965ad7f 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-output</string> <string name="mode_hdr_unavailable">Ikke tilgængelig: %1$s.</string> - <string name="mode_hdr_restart">Genstart appen for at anvende ændringen.</string> <string name="mode_drivers">Drivere</string> <string name="mode_gpu_drivers">GPU-drivere</string> <string name="mode_gpu_drivers_hint">Delt mellem Steam og Skrivebord. Indstilles på siden Komponenter.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Opstart</string> <string name="mode_startup_session">Åbn ved start</string> <string name="mode_startup_session_hint">Starter denne session, når DroidDeck startes.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Søger efter udgivelser…</string> <string name="mode_decky_ready">Klar til at installere %1$s.</string> <string name="mode_decky_none">Ingen kompatibel build fundet. Prøv igen senere.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Opdateret · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Installer nyeste</string> - <string name="decky_channel">Opdateringskanal</string> - <string name="decky_channel_hint">Hvilke Decky Loader-udgivelser der installeres. Deckys egen opdatering bruger samme kanal.</string> <string name="decky_channel_stable">Stabil</string> <string name="decky_channel_prerelease">Forhåndsudgivelse</string> <string name="decky_channel_testing">Test</string> <string name="decky_channel_failed">Kunne ikke gemme Decky-opdateringskanalen</string> - <string name="mode_decky_on">Starter med Steam. Mens den er til, kan andre apps på denne enhed muligvis styre Steam.</string> - <string name="mode_decky_off">Fra. Steams fjerndebugport forbliver lukket.</string> <string name="mode_decky_remove_title">Afinstaller Decky Loader?</string> <string name="mode_decky_remove_text">Fjerner loaderen. Dine plugins og indstillinger bevares.</string> <string name="mode_client">Klient</string> @@ -953,13 +947,15 @@ <string name="setup_launcher_orientation_auto">Følg enhedens rotation</string> <string name="setup_orientation_portrait">Stående</string> <string name="setup_session_orientation">Sessionens retning</string> - <string name="setup_session_orientation_hint">Gælder Steam, spil, skrivebordet og controllereditoren. Opløsningsforudindstillinger roterer med sessionen; brugerdefineret bredde og højde forbliver som angivet.</string> + <string name="setup_session_orientation_hint">Gælder Steam, spil, skrivebordet og controllereditoren. Opløsningsforudindstillinger roterer med sessionen; når den ene orientering følger den anden, byttes brugerdefineret bredde og højde, så de passer.</string> <string name="setup_orientation_auto">Automatisk liggende</string> <string name="setup_orientation_landscape">Liggende</string> <string name="setup_orientation_reverse">Omvendt liggende</string> <string name="setup_fullscreen">Fuldskærm</string> <string name="setup_fullscreen_on">Skjuler Androids status- og navigationsbjælker</string> <string name="setup_fullscreen_off">Viser Androids status- og navigationsbjælker</string> + <string name="setup_page_swipe">Stryg mellem sider</string> + <string name="setup_page_swipe_hint">Stryg hen over en side for at skifte fane.</string> <string name="setup_dual_screen_launcher">Launcher til to skærme</string> <string name="setup_dual_screen_launcher_hint">Automatisk placerer launcherens sektioner (Steam, Bibliotek, Butikker og resten) på den anden skærm på håndholdte enheder med en indbygget anden skærm. Til bruger enhver ekstra skærm. Fra holder launcheren på én skærm.</string> <string name="setup_dual_screen_sessions">Sessioner på to skærme</string> @@ -1280,8 +1276,6 @@ <string name="gate_open_dev">Åbn Udviklerindstillinger</string> <string name="gate_no_toggle">Denne Android-version har ingen kontakt til det, så DroidDeck ændrer det via Trådløs fejlretning. Tager omkring et minut, ingen computer nødvendig.</string> <string name="gate_needs_wifi">Trådløs fejlretning kræver Wi-Fi. Alle netværk fungerer; det kræver ikke internet.</string> - <string name="gate_needs_notifications">Parringskoden kommer i en notifikation. Tillad notifikationer for DroidDeck, eller brug Andre måder.</string> - <string name="gate_allow_notifications">Tillad notifikationer</string> <string name="gate_step1">Åbn Indstillinger → Udviklerindstillinger → Trådløs fejlretning, og slå den til</string> <string name="gate_step2">Tryk på “Par enhed med parringskode”</string> <string name="gate_step3">Indtast koden i DroidDeck-notifikationen</string> @@ -1298,48 +1292,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Kontrollerer hvert 2. sekund. Denne side lukker, når den er fra.</string> <string name="gate_other_ways">Andre måder</string> - <string name="gate_other_toggle">Trådløs fejlretning, manuel adresse, computer-ADB</string> - <string name="gate_other_no_toggle">Manuel adresse, computer-ADB, Udviklerindstillinger</string> <string name="gate_use_wireless_instead">Brug Trådløs fejlretning i stedet</string> <string name="gate_some_roms">Nogle ROM’er tilføjer kontakten alligevel. Kig efter “underprocesser” i Udviklerindstillinger.</string> - <string name="gate_manual_hint">Hvis notifikationen ikke virker, kan du selv indtaste vinduets adresse og kode.</string> - <string name="gate_enter_manually">Indtast adresse manuelt</string> <string name="gate_from_computer">Fra en computer med ADB:</string> <string name="gate_copy_command">Kopier kommando</string> <string name="gate_sidequest_steps">Slut headsettet til en computer, og åbn SideQuest. Vælg “Run ADB Command” og derefter “Custom Command”, skriv kommandoen vist nedenfor, og vælg “Run Command”.</string> <string name="gate_choose_display">Vælg, hvilken skærm Android-indstillinger skal åbnes på.</string> <string name="gate_main_screen">Hovedskærm</string> - <string name="wadb_finding_port">Parret. Finder porten for Trådløs fejlretning…</string> - <string name="wadb_enter_port">Parret. Indtast porten fra Indstillinger.</string> - <string name="wadb_applying">Enhed fundet. Anvender indstillingen…</string> - <string name="wadb_apply_failed">Kunne ikke anvendes automatisk. Kontroller adressen nedenfor, og prøv igen. %1$s</string> - <string name="wadb_title_wireless">Trådløs fejlretning</string> - <string name="wadb_title_done">Grænsen for underprocesser opdateret</string> - <string name="wadb_title">Ændr grænsen for underprocesser</string> - <string name="wadb_lede_compact0">Hvis indstillingen mangler, skal du parre via Trådløs fejlretning.</string> - <string name="wadb_lede_compact1">Parret. Kontroller IP-adressen og porten i Trådløs fejlretning.</string> - <string name="wadb_lede_done">Grænsen for underprocesser blev opdateret.</string> - <string name="wadb_lede0">Brug trin 2, hvis Udviklerindstillinger ikke har en indstilling for underprocesser. Åbn Udviklerindstillinger → Trådløs fejlretning → Par enhed med parringskode.</string> - <string name="wadb_lede1">Parret. Brug adressen nedenfor, eller opdater den fra Trådløs fejlretning → IP-adresse og port.</string> - <string name="wadb_lede_done_long">Grænsen for underprocesser blev opdateret via Trådløs fejlretning.</string> - <string name="wadb_confirmed_on">Android bekræftede, at grænsen er til.</string> - <string name="wadb_confirmed_off">Android bekræftede, at grænsen er fra.</string> - <string name="wadb_pair_group">2 · Par Trådløs fejlretning</string> - <string name="wadb_pair_address">Parringsvinduets IP-adresse og port</string> - <string name="wadb_pin">Parringskode (PIN)</string> - <string name="wadb_pin_placeholder">6 cifre</string> - <string name="wadb_pair">Par</string> - <string name="wadb_apply_group">2 · Anvend via Trådløs fejlretning</string> - <string name="wadb_connect_address">Forbindelsens IP-adresse og port</string> - <string name="wadb_pair_again">Par igen</string> - <string name="wadb_turn_off">Slå grænsen fra</string> - <string name="wadb_other_ways">Andre måder at ændre det</string> - <string name="wadb_dev_try_first">1 · Udviklerindstillinger (prøv først)</string> - <string name="wadb_restrict_on">Slå “Deaktiver begrænsningerne for underprocesser” fra.</string> - <string name="wadb_restrict_off">Slå “Deaktiver begrænsningerne for underprocesser” til.</string> - <string name="wadb_computer_last">3 · Computer-ADB (sidste udvej)</string> - <string name="wadb_only_if">Kun hvis Trådløs fejlretning ikke er tilgængelig.</string> - <string name="wadb_computer_group">3 · Computer-ADB (sidste udvej)</string> <string name="ctrl_color">Farve</string> <string name="ctrl_custom">Brugerdefineret</string> <string name="ctrl_opacity">Gennemsigtighed</string> @@ -1627,8 +1586,6 @@ <item quantity="one">Ryddede %1$d sessionslogmappe.</item> <item quantity="other">Ryddede %1$d sessionslogmapper.</item> </plurals> - <string name="main_wadb_pair_failed">Parring til trådløs fejlretning mislykkedes</string> - <string name="main_wadb_command_failed">Kommando til trådløs fejlretning mislykkedes</string> <string name="main_wadb_unavailable">Trådløs fejlretning er ikke tilgængelig</string> <string name="main_adb_copied">ADB-kommando kopieret</string> <string name="main_pick_roms">Vælg ROMs-mappen</string> @@ -2461,10 +2418,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Sessionsskærm</string> - <string name="display_resolution">Opløsning</string> + <string name="display_zero_copy">Præsentation uden kopiering</string> + <string name="display_resolution_landscape">Opløsning i landskab</string> + <string name="display_resolution_portrait">Opløsning i portræt</string> + <string name="display_follow_landscape">Følg landskab (%1$d×%2$d)</string> + <string name="display_follow_portrait">Følg portræt (%1$d×%2$d)</string> <string name="display_game_fit">16:9-spiltilpasning</string> <string name="display_game_fit_hint">Hvordan 16:9-spil tilpasses denne skærm. Fra næste session.</string> <string name="display_game_fit_unavailable">Vælg Match skærm eller en brugerdefineret størrelse, der er smallere end 16:9.</string> + <string name="display_avoid_notch">Undgå notch</string> + <string name="display_avoid_notch_hint">Holder billedet uden for kameraudskæringen. Træder i kraft, når du vender tilbage til sessionen.</string> <string name="display_preserve">Bevar proportioner</string> <string name="display_stretch">Stræk til skærm</string> <string name="display_image_scaling">Billedskalering</string> @@ -2751,6 +2714,7 @@ <string name="stores_login_error_ssl">Forbindelsen til loginsiden er ikke sikker.</string> <string name="stores_login_error_verification">Login kunne ikke bekræftes. Forsøg igen.</string> <string name="stores_login_error_generic">Login mislykkedes. Forsøg igen.</string> + <string name="stores_login_continue_in_browser">%1$s kræver et trin mere. Fuldfør det i browseren, der blev åbnet, og prøv igen.</string> <string name="common_close">Luk</string> <string name="common_back">Tilbage</string> <string name="common_edit">Rediger</string> @@ -3135,7 +3099,7 @@ <string name="hand_camera_done">Udført</string> <string name="glasses_xreal_network_missing">Venter på brillens USB-Ethernet-forbindelse. Denne telefon gør den muligvis ikke tilgængelig for apps.</string> <string name="glasses_xreal_connection_failed">XREAL-forbindelsen blev afbrudt eller returnerede et svar, der ikke understøttes. Prøver igen…</string> - <string name="glasses_xreal_experimental">Eksperimentel understøttelse af 1S. Brug Follow-tilstand, og slå stabilisering fra i brillens menu. Sporingsretninger og visningstilstande mangler stadig test på enheden.</string> + <string name="glasses_xreal_experimental">Eksperimentel understøttelse af XREAL 1S, One, One Pro, One Pro+ og Aura. Brug Follow-tilstand, og slå stabilisering fra i brillernes menu; på Aura skal du også slå Spatial Anchor fra. Hovedsporing og skift mellem 2D/3D er testet på Aura og One Pro+.</string> <string name="glasses_pro2_experimental">Eksperimentel hovedsporing til Pro 2. Justering af lysstyrke og lydstyrke samt skift af visningstilstand understøttes endnu ikke.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-tilstand</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">Mest downloadet</string> <string name="addons_category_all">Alle kategorier</string> <string name="addons_none_found">Ingen tilføjelser fundet</string> + <string name="addons_curse_busy">Luk CurseForge først</string> <string name="addons_unreachable">Kunne ikke nå %1$s</string> <string name="addons_no_file">Ingen fil til denne spilversion</string> <string name="input_reset_positions">Nulstil placeringer</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">Fremhævninger</string> <string name="theme_custom_good">Succes</string> <string name="theme_custom_error">Fejl</string> + <string name="hud_only_during_game">Vis kun HUD under spil</string> + <string name="hud_only_during_game_hint">Skjul HUD, når der ikke registreres spilbilleder.</string> </resources> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index c913e57c78..f803d555bd 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-Ausgabe</string> <string name="mode_hdr_unavailable">Nicht verfügbar: %1$s.</string> - <string name="mode_hdr_restart">Starte die App neu, um dies anzuwenden.</string> <string name="mode_drivers">Treiber</string> <string name="mode_gpu_drivers">GPU-Treiber</string> <string name="mode_gpu_drivers_hint">Für Steam und Desktop gemeinsam. Wird auf der Seite „Komponenten“ festgelegt.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Start</string> <string name="mode_startup_session">Beim Start öffnen</string> <string name="mode_startup_session_hint">Startet diese Sitzung, wenn DroidDeck startet.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Suche nach Releases…</string> <string name="mode_decky_ready">Bereit zur Installation von %1$s.</string> <string name="mode_decky_none">Kein kompatibler Build gefunden. Versuch es später noch einmal.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Aktuell · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Neueste Version installieren</string> - <string name="decky_channel">Update-Kanal</string> - <string name="decky_channel_hint">Welche Decky-Loader-Releases installiert werden. Deckys eigener Updater nutzt denselben Kanal.</string> <string name="decky_channel_stable">Stabil</string> <string name="decky_channel_prerelease">Vorabversion</string> <string name="decky_channel_testing">Test</string> <string name="decky_channel_failed">Decky-Update-Kanal konnte nicht gespeichert werden</string> - <string name="mode_decky_on">Startet mit Steam. Solange aktiv, können andere Apps auf diesem Gerät Steam möglicherweise steuern.</string> - <string name="mode_decky_off">Aus. Der Remote-Debugging-Port von Steam bleibt geschlossen.</string> <string name="mode_decky_remove_title">Decky Loader deinstallieren?</string> <string name="mode_decky_remove_text">Entfernt den Loader. Deine Plugins und Einstellungen bleiben erhalten.</string> <string name="mode_client">Client</string> @@ -945,13 +939,15 @@ <string name="setup_launcher_orientation_auto">Gerätedrehung folgen</string> <string name="setup_orientation_portrait">Hochformat</string> <string name="setup_session_orientation">Sitzungsausrichtung</string> - <string name="setup_session_orientation_hint">Gilt für Steam, Spiele, Desktop und den Controller-Editor. Auflösungsvoreinstellungen drehen sich mit der Sitzung; eigene Breite und Höhe bleiben wie eingegeben.</string> + <string name="setup_session_orientation_hint">Gilt für Steam, Spiele, Desktop und den Controller-Editor. Auflösungsvoreinstellungen drehen sich mit der Sitzung; folgt eine Ausrichtung der anderen, werden eigene Breite und Höhe passend vertauscht.</string> <string name="setup_orientation_auto">Automatisch Querformat</string> <string name="setup_orientation_landscape">Querformat</string> <string name="setup_orientation_reverse">Umgekehrtes Querformat</string> <string name="setup_fullscreen">Vollbild</string> <string name="setup_fullscreen_on">Blendet die Status- und Navigationsleiste von Android aus</string> <string name="setup_fullscreen_off">Zeigt die Status- und Navigationsleiste von Android an</string> + <string name="setup_page_swipe">Zwischen Seiten wischen</string> + <string name="setup_page_swipe_hint">Über eine Seite wischen, um den Tab zu wechseln.</string> <string name="setup_dual_screen_launcher">Dual-Screen-Launcher</string> <string name="setup_dual_screen_launcher_hint">Bei Automatisch liegen die Launcher-Bereiche (Steam, Bibliothek, Shops und die übrigen) auf dem zweiten Bildschirm von Handhelds mit integriertem zweitem Bildschirm. Ein nutzt einen beliebigen zweiten Bildschirm. Aus belässt den Launcher auf einem Bildschirm.</string> <string name="setup_dual_screen_sessions">Dual-Screen-Sitzungen</string> @@ -1272,8 +1268,6 @@ <string name="gate_open_dev">Entwickleroptionen öffnen</string> <string name="gate_no_toggle">Diese Android-Version hat dafür keinen Schalter, deshalb ändert DroidDeck es über „Debugging über WLAN“. Dauert etwa eine Minute, kein Computer nötig.</string> <string name="gate_needs_wifi">„Debugging über WLAN“ braucht eine Wi-Fi-Verbindung. Jedes Netzwerk geht; Internet ist nicht nötig.</string> - <string name="gate_needs_notifications">Der Kopplungscode wird in eine Benachrichtigung eingegeben. Erlaube Benachrichtigungen für DroidDeck oder nutze „Andere Wege“.</string> - <string name="gate_allow_notifications">Benachrichtigungen erlauben</string> <string name="gate_step1">Öffne Einstellungen → Entwickleroptionen → Debugging über WLAN und aktiviere es</string> <string name="gate_step2">Tippe auf „Gerät über einen Kopplungscode koppeln“</string> <string name="gate_step3">Gib den Code in die DroidDeck-Benachrichtigung ein</string> @@ -1290,48 +1284,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Prüft alle 2 Sekunden. Diese Seite schließt sich, sobald es aus ist.</string> <string name="gate_other_ways">Andere Wege</string> - <string name="gate_other_toggle">Debugging über WLAN, manuelle Adresse, ADB am Computer</string> - <string name="gate_other_no_toggle">Manuelle Adresse, ADB am Computer, Entwickleroptionen</string> <string name="gate_use_wireless_instead">Stattdessen „Debugging über WLAN“ verwenden</string> <string name="gate_some_roms">Manche ROMs haben den Schalter trotzdem. Suche in den Entwickleroptionen nach „untergeordnete Prozesse“.</string> - <string name="gate_manual_hint">Falls die Benachrichtigung nicht funktioniert, gib Adresse und Code des Pop-ups selbst ein.</string> - <string name="gate_enter_manually">Adresse manuell eingeben</string> <string name="gate_from_computer">Von einem Computer mit ADB:</string> <string name="gate_copy_command">Befehl kopieren</string> <string name="gate_sidequest_steps">Verbinde das Headset mit einem Computer und öffne SideQuest. Wähle „Run ADB Command“, dann „Custom Command“, tippe den unten gezeigten Befehl ein und wähle „Run Command“.</string> <string name="gate_choose_display">Wähle, auf welchem Display die Android-Einstellungen geöffnet werden.</string> <string name="gate_main_screen">Hauptbildschirm</string> - <string name="wadb_finding_port">Gekoppelt. Suche den Port für Debugging über WLAN…</string> - <string name="wadb_enter_port">Gekoppelt. Gib den Port aus den Einstellungen ein.</string> - <string name="wadb_applying">Gerät gefunden. Einstellung wird angewendet…</string> - <string name="wadb_apply_failed">Automatisches Anwenden fehlgeschlagen. Prüfe die Adresse unten und versuch es erneut. %1$s</string> - <string name="wadb_title_wireless">Debugging über WLAN</string> - <string name="wadb_title_done">Limit für untergeordnete Prozesse aktualisiert</string> - <string name="wadb_title">Limit für untergeordnete Prozesse ändern</string> - <string name="wadb_lede_compact0">Fehlt die Option, kopple über „Debugging über WLAN“.</string> - <string name="wadb_lede_compact1">Gekoppelt. Prüfe IP-Adresse und Port unter „Debugging über WLAN“.</string> - <string name="wadb_lede_done">Das Limit für untergeordnete Prozesse wurde aktualisiert.</string> - <string name="wadb_lede0">Nutze Schritt 2, wenn die Entwickleroptionen keine Einstellung für untergeordnete Prozesse haben. Öffne Entwickleroptionen → Debugging über WLAN → Gerät über einen Kopplungscode koppeln.</string> - <string name="wadb_lede1">Gekoppelt. Nutze die Adresse unten oder aktualisiere sie über Debugging über WLAN → IP-Adresse und Port.</string> - <string name="wadb_lede_done_long">Das Limit für untergeordnete Prozesse wurde über „Debugging über WLAN“ aktualisiert.</string> - <string name="wadb_confirmed_on">Android hat bestätigt, dass das Limit aktiv ist.</string> - <string name="wadb_confirmed_off">Android hat bestätigt, dass das Limit aus ist.</string> - <string name="wadb_pair_group">2 · Für Debugging über WLAN koppeln</string> - <string name="wadb_pair_address">IP-Adresse und Port aus dem Kopplungs-Pop-up</string> - <string name="wadb_pin">Kopplungscode (PIN)</string> - <string name="wadb_pin_placeholder">6 Ziffern</string> - <string name="wadb_pair">Koppeln</string> - <string name="wadb_apply_group">2 · Per Debugging über WLAN anwenden</string> - <string name="wadb_connect_address">IP-Adresse und Port für die Verbindung</string> - <string name="wadb_pair_again">Erneut koppeln</string> - <string name="wadb_turn_off">Limit deaktivieren</string> - <string name="wadb_other_ways">Andere Wege, es zu ändern</string> - <string name="wadb_dev_try_first">1 · Entwickleroptionen (zuerst versuchen)</string> - <string name="wadb_restrict_on">Schalte „Beschränkungen für Unterprozesse deaktivieren“ aus.</string> - <string name="wadb_restrict_off">Schalte „Beschränkungen für Unterprozesse deaktivieren“ ein.</string> - <string name="wadb_computer_last">3 · ADB am Computer (letzter Ausweg)</string> - <string name="wadb_only_if">Nur wenn „Debugging über WLAN“ nicht verfügbar ist.</string> - <string name="wadb_computer_group">3 · ADB am Computer (letzter Ausweg)</string> <string name="ctrl_color">Farbe</string> <string name="ctrl_custom">Benutzerdefiniert</string> <string name="ctrl_opacity">Deckkraft</string> @@ -1619,8 +1578,6 @@ <item quantity="one">%1$d Ordner mit Sitzungsprotokollen gelöscht.</item> <item quantity="other">%1$d Ordner mit Sitzungsprotokollen gelöscht.</item> </plurals> - <string name="main_wadb_pair_failed">Kopplung für Debugging über WLAN fehlgeschlagen</string> - <string name="main_wadb_command_failed">Befehl für Debugging über WLAN fehlgeschlagen</string> <string name="main_wadb_unavailable">Debugging über WLAN ist nicht verfügbar</string> <string name="main_adb_copied">ADB-Befehl kopiert</string> <string name="main_pick_roms">ROMs-Ordner auswählen</string> @@ -2453,10 +2410,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Sitzungsanzeige</string> - <string name="display_resolution">Auflösung</string> + <string name="display_zero_copy">Kopierfreie Darstellung</string> + <string name="display_resolution_landscape">Auflösung im Querformat</string> + <string name="display_resolution_portrait">Auflösung im Hochformat</string> + <string name="display_follow_landscape">Wie Querformat (%1$d×%2$d)</string> + <string name="display_follow_portrait">Wie Hochformat (%1$d×%2$d)</string> <string name="display_game_fit">16:9-Spielanpassung</string> <string name="display_game_fit_hint">Wie 16:9-Spiele auf dieses Display passen. Ab der nächsten Sitzung.</string> <string name="display_game_fit_unavailable">Wähle „An Bildschirm anpassen“ oder eine eigene Größe schmaler als 16:9.</string> + <string name="display_avoid_notch">Notch aussparen</string> + <string name="display_avoid_notch_hint">Hält das Bild aus der Kameraaussparung heraus. Gilt, sobald du zur Sitzung zurückkehrst.</string> <string name="display_preserve">Seitenverhältnis beibehalten</string> <string name="display_stretch">Auf Display strecken</string> <string name="display_image_scaling">Bildskalierung</string> @@ -2740,6 +2703,7 @@ <string name="stores_login_error_ssl">Die Verbindung zur Anmeldeseite ist nicht sicher.</string> <string name="stores_login_error_verification">Die Anmeldung konnte nicht bestätigt werden. Versuche es erneut.</string> <string name="stores_login_error_generic">Anmeldung fehlgeschlagen. Versuche es erneut.</string> + <string name="stores_login_continue_in_browser">%1$s braucht noch einen Schritt. Schließe ihn im geöffneten Browser ab und versuche es dann erneut.</string> <string name="common_close">Schließen</string> <string name="common_back">Zurück</string> <string name="common_edit">Bearbeiten</string> @@ -3124,7 +3088,7 @@ <string name="hand_camera_done">Fertig</string> <string name="glasses_xreal_network_missing">Warte auf die USB-Ethernet-Verbindung der Brille. Dieses Smartphone stellt sie Apps möglicherweise nicht bereit.</string> <string name="glasses_xreal_connection_failed">Die XREAL-Verbindung wurde unterbrochen oder hat eine nicht unterstützte Antwort geliefert. Neuer Versuch …</string> - <string name="glasses_xreal_experimental">Experimentelle Unterstützung für die 1S. Nutze den Follow-Modus und deaktiviere die Stabilisierung im Menü der Brille. Tracking-Richtungen und Anzeigemodi müssen noch auf Geräten getestet werden.</string> + <string name="glasses_xreal_experimental">Experimentelle Unterstützung für XREAL 1S, One, One Pro, One Pro+ und Aura. Nutze den Follow-Modus und deaktiviere die Stabilisierung im Menü der Brille; deaktiviere bei der Aura auch Spatial Anchor. Kopftracking und 2D/3D-Umschaltung wurden auf der Aura und der One Pro+ getestet.</string> <string name="glasses_pro2_experimental">Experimentelles Kopftracking für Pro 2. Das Einstellen von Helligkeit und Lautstärke sowie das Umschalten des Anzeigemodus werden noch nicht unterstützt.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-Modus</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">Meistgeladen</string> <string name="addons_category_all">Alle Kategorien</string> <string name="addons_none_found">Keine Addons gefunden</string> + <string name="addons_curse_busy">Schließe zuerst CurseForge</string> <string name="addons_unreachable">%1$s ist nicht erreichbar</string> <string name="addons_no_file">Keine Datei für diese Spielversion</string> <string name="input_reset_positions">Positionen zurücksetzen</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">Hervorhebungen</string> <string name="theme_custom_good">Erfolg</string> <string name="theme_custom_error">Fehler</string> + <string name="hud_only_during_game">HUD nur während eines Spiels anzeigen</string> + <string name="hud_only_during_game_hint">HUD ausblenden, wenn keine Spielframes erkannt werden.</string> </resources> diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index c1e1ffcb79..08d647886a 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Έξοδος HDR10</string> <string name="mode_hdr_unavailable">Μη διαθέσιμο: %1$s.</string> - <string name="mode_hdr_restart">Κάντε επανεκκίνηση της εφαρμογής για να εφαρμοστεί.</string> <string name="mode_drivers">Προγράμματα οδήγησης</string> <string name="mode_gpu_drivers">Προγράμματα οδήγησης GPU</string> <string name="mode_gpu_drivers_hint">Κοινά για το Steam και την Επιφάνεια εργασίας. Ορίζονται στη σελίδα Στοιχεία.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Εκκίνηση</string> <string name="mode_startup_session">Άνοιγμα κατά την εκκίνηση</string> <string name="mode_startup_session_hint">Ξεκινά αυτή τη συνεδρία όταν ανοίγει το DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Έλεγχος για εκδόσεις…</string> <string name="mode_decky_ready">Έτοιμο για εγκατάσταση %1$s.</string> <string name="mode_decky_none">Δεν βρέθηκε συμβατό build. Δοκιμάστε ξανά αργότερα.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Ενημερωμένο · %1$s</string> <string name="mode_decky_loader">Φορτωτής</string> <string name="mode_decky_install_latest">Εγκατάσταση τελευταίας έκδοσης</string> - <string name="decky_channel">Κανάλι ενημερώσεων</string> - <string name="decky_channel_hint">Ποιες εκδόσεις του Decky Loader θα εγκατασταθούν. Το πρόγραμμα ενημέρωσης του Decky χρησιμοποιεί το ίδιο κανάλι.</string> <string name="decky_channel_stable">Σταθερό</string> <string name="decky_channel_prerelease">Προέκδοση</string> <string name="decky_channel_testing">Δοκιμαστικό</string> <string name="decky_channel_failed">Δεν ήταν δυνατή η αποθήκευση του καναλιού ενημερώσεων του Decky</string> - <string name="mode_decky_on">Ξεκινά με το Steam. Όσο είναι ενεργό, άλλες εφαρμογές σε αυτή τη συσκευή μπορεί να είναι σε θέση να ελέγξουν το Steam.</string> - <string name="mode_decky_off">Ανενεργό. Η θύρα απομακρυσμένου εντοπισμού σφαλμάτων του Steam παραμένει κλειστή.</string> <string name="mode_decky_remove_title">Κατάργηση εγκατάστασης του Decky Loader;</string> <string name="mode_decky_remove_text">Καταργεί τον loader. Τα plugins και οι ρυθμίσεις σας διατηρούνται.</string> <string name="mode_client">Πελάτης</string> @@ -953,13 +947,15 @@ <string name="setup_launcher_orientation_auto">Ακολουθεί την περιστροφή της συσκευής</string> <string name="setup_orientation_portrait">Κατακόρυφος</string> <string name="setup_session_orientation">Προσανατολισμός συνεδρίας</string> - <string name="setup_session_orientation_hint">Ισχύει για το Steam, τα παιχνίδια, την επιφάνεια εργασίας και τον επεξεργαστή χειριστηρίου. Οι προκαθορισμένες αναλύσεις περιστρέφονται με τη συνεδρία· το προσαρμοσμένο πλάτος και ύψος μένουν όπως καταχωρίστηκαν.</string> + <string name="setup_session_orientation_hint">Ισχύει για το Steam, τα παιχνίδια, την επιφάνεια εργασίας και τον επεξεργαστή χειριστηρίου. Οι προκαθορισμένες αναλύσεις περιστρέφονται με τη συνεδρία· όταν ένας προσανατολισμός ακολουθεί τον άλλον, το προσαρμοσμένο πλάτος και ύψος αντιστρέφονται ώστε να ταιριάζουν.</string> <string name="setup_orientation_auto">Αυτόματος οριζόντιος προσανατολισμός</string> <string name="setup_orientation_landscape">Οριζόντιος προσανατολισμός</string> <string name="setup_orientation_reverse">Αντίστροφος οριζόντιος προσανατολισμός</string> <string name="setup_fullscreen">Πλήρης οθόνη</string> <string name="setup_fullscreen_on">Αποκρύπτει τις γραμμές κατάστασης και πλοήγησης του Android</string> <string name="setup_fullscreen_off">Εμφανίζει τις γραμμές κατάστασης και πλοήγησης του Android</string> + <string name="setup_page_swipe">Σάρωση μεταξύ σελίδων</string> + <string name="setup_page_swipe_hint">Σαρώστε κατά μήκος μιας σελίδας για να αλλάξετε καρτέλα.</string> <string name="setup_dual_screen_launcher">Εκκινητής διπλής οθόνης</string> <string name="setup_dual_screen_launcher_hint">Η επιλογή Αυτόματα τοποθετεί τις ενότητες του εκκινητή (Steam, Βιβλιοθήκη, Καταστήματα και τις υπόλοιπες) στη δεύτερη οθόνη των φορητών κονσολών με ενσωματωμένη δεύτερη οθόνη. Η επιλογή Ενεργό χρησιμοποιεί οποιαδήποτε δεύτερη οθόνη. Η επιλογή Ανενεργό κρατά τον εκκινητή σε μία οθόνη.</string> <string name="setup_dual_screen_sessions">Συνεδρίες διπλής οθόνης</string> @@ -1280,8 +1276,6 @@ <string name="gate_open_dev">Άνοιγμα Επιλογών προγραμματιστή</string> <string name="gate_no_toggle">Αυτή η έκδοση Android δεν έχει διακόπτη για αυτό, οπότε το DroidDeck το αλλάζει μέσω Ασύρματου εντοπισμού σφαλμάτων. Διαρκεί περίπου ένα λεπτό, χωρίς υπολογιστή.</string> <string name="gate_needs_wifi">Ο Ασύρματος εντοπισμός σφαλμάτων απαιτεί Wi-Fi. Οποιοδήποτε δίκτυο λειτουργεί· δεν απαιτείται σύνδεση στο διαδίκτυο.</string> - <string name="gate_needs_notifications">Ο κωδικός σύζευξης εμφανίζεται σε ειδοποίηση. Επιτρέψτε ειδοποιήσεις για το DroidDeck, ή χρησιμοποιήστε Άλλοι τρόποι.</string> - <string name="gate_allow_notifications">Αποδοχή ειδοποιήσεων</string> <string name="gate_step1">Ανοίξτε Ρυθμίσεις → Επιλογές προγραμματιστή → Ασύρματος εντοπισμός σφαλμάτων και ενεργοποιήστε τον</string> <string name="gate_step2">Πατήστε «Σύζευξη συσκευής με κωδικό σύζευξης»</string> <string name="gate_step3">Πληκτρολογήστε τον κωδικό στην ειδοποίηση του DroidDeck</string> @@ -1298,48 +1292,13 @@ <string name="gate_status">Κατάσταση</string> <string name="gate_polling">Έλεγχος κάθε 2 δευτερόλεπτα. Αυτή η σελίδα κλείνει όταν είναι απενεργοποιημένο.</string> <string name="gate_other_ways">Άλλοι τρόποι</string> - <string name="gate_other_toggle">Ασύρματος εντοπισμός σφαλμάτων, μη αυτόματη διεύθυνση, ADB υπολογιστή</string> - <string name="gate_other_no_toggle">Μη αυτόματη διεύθυνση, ADB υπολογιστή, Επιλογές προγραμματιστή</string> <string name="gate_use_wireless_instead">Χρήση Ασύρματου εντοπισμού σφαλμάτων αντ\' αυτού</string> <string name="gate_some_roms">Ορισμένες ROM προσθέτουν τον διακόπτη ούτως ή άλλως. Αναζητήστε «θυγατρική διαδικασία» στις Επιλογές προγραμματιστή.</string> - <string name="gate_manual_hint">Αν η ειδοποίηση δεν λειτουργεί, εισαγάγετε τη διεύθυνση και τον κωδικό του αναδυόμενου παραθύρου εσείς.</string> - <string name="gate_enter_manually">Μη αυτόματη εισαγωγή διεύθυνσης</string> <string name="gate_from_computer">Από υπολογιστή με ADB:</string> <string name="gate_copy_command">Αντιγραφή εντολής</string> <string name="gate_sidequest_steps">Συνδέστε το headset σε υπολογιστή και ανοίξτε το SideQuest. Επιλέξτε «Run ADB Command», μετά «Custom Command», πληκτρολογήστε την εντολή που εμφανίζεται παρακάτω και επιλέξτε «Run Command».</string> <string name="gate_choose_display">Επιλέξτε σε ποια οθόνη θα ανοίξουν οι Ρυθμίσεις Android.</string> <string name="gate_main_screen">Κύρια οθόνη</string> - <string name="wadb_finding_port">Έγινε σύζευξη. Αναζήτηση θύρας Ασύρματου εντοπισμού σφαλμάτων…</string> - <string name="wadb_enter_port">Έγινε σύζευξη. Εισαγάγετε τη θύρα από τις Ρυθμίσεις.</string> - <string name="wadb_applying">Η συσκευή βρέθηκε. Εφαρμογή της ρύθμισης…</string> - <string name="wadb_apply_failed">Δεν ήταν δυνατή η αυτόματη εφαρμογή. Ελέγξτε την παρακάτω διεύθυνση και δοκιμάστε ξανά. %1$s</string> - <string name="wadb_title_wireless">Ασύρματος εντοπισμός σφαλμάτων</string> - <string name="wadb_title_done">Το όριο θυγατρικών διαδικασιών ενημερώθηκε</string> - <string name="wadb_title">Αλλαγή του ορίου θυγατρικών διαδικασιών</string> - <string name="wadb_lede_compact0">Αν η επιλογή λείπει, κάντε σύζευξη μέσω Ασύρματου εντοπισμού σφαλμάτων.</string> - <string name="wadb_lede_compact1">Έγινε σύζευξη. Ελέγξτε τη διεύθυνση IP και τη θύρα στον Ασύρματο εντοπισμό σφαλμάτων.</string> - <string name="wadb_lede_done">Το όριο θυγατρικών διαδικασιών ενημερώθηκε.</string> - <string name="wadb_lede0">Χρησιμοποιήστε το βήμα 2 αν οι Επιλογές προγραμματιστή δεν έχουν ρύθμιση θυγατρικών διαδικασιών. Ανοίξτε Επιλογές προγραμματιστή → Ασύρματος εντοπισμός σφαλμάτων → Σύζευξη συσκευής με κωδικό σύζευξης.</string> - <string name="wadb_lede1">Έγινε σύζευξη. Χρησιμοποιήστε την παρακάτω διεύθυνση, ή ενημερώστε την από Ασύρματος εντοπισμός σφαλμάτων → Διεύθυνση IP & θύρα.</string> - <string name="wadb_lede_done_long">Το όριο θυγατρικών διαδικασιών ενημερώθηκε μέσω Ασύρματου εντοπισμού σφαλμάτων.</string> - <string name="wadb_confirmed_on">Το Android επιβεβαίωσε ότι το όριο είναι ενεργό.</string> - <string name="wadb_confirmed_off">Το Android επιβεβαίωσε ότι το όριο είναι ανενεργό.</string> - <string name="wadb_pair_group">2 · Σύζευξη Ασύρματου εντοπισμού σφαλμάτων</string> - <string name="wadb_pair_address">Διεύθυνση IP & θύρα αναδυόμενου παραθύρου σύζευξης</string> - <string name="wadb_pin">Κωδικός σύζευξης (PIN)</string> - <string name="wadb_pin_placeholder">6 ψηφία</string> - <string name="wadb_pair">Σύζευξη</string> - <string name="wadb_apply_group">2 · Εφαρμογή μέσω Ασύρματου εντοπισμού σφαλμάτων</string> - <string name="wadb_connect_address">Διεύθυνση IP & θύρα σύνδεσης</string> - <string name="wadb_pair_again">Σύζευξη ξανά</string> - <string name="wadb_turn_off">Απενεργοποίηση ορίου</string> - <string name="wadb_other_ways">Άλλοι τρόποι αλλαγής</string> - <string name="wadb_dev_try_first">1 · Επιλογές προγραμματιστή (δοκιμάστε πρώτα)</string> - <string name="wadb_restrict_on">Απενεργοποιήστε «Απενεργοπ. περιορισμών σε θυγατρικές διεργασίες».</string> - <string name="wadb_restrict_off">Ενεργοποιήστε «Απενεργοπ. περιορισμών σε θυγατρικές διεργασίες».</string> - <string name="wadb_computer_last">3 · ADB υπολογιστή (τελευταία λύση)</string> - <string name="wadb_only_if">Μόνο αν ο Ασύρματος εντοπισμός σφαλμάτων δεν είναι διαθέσιμος.</string> - <string name="wadb_computer_group">3 · ADB υπολογιστή (τελευταία λύση)</string> <string name="ctrl_color">Χρώμα</string> <string name="ctrl_custom">Προσαρμοσμένο</string> <string name="ctrl_opacity">Διαφάνεια</string> @@ -1627,8 +1586,6 @@ <item quantity="one">Έγινε εκκαθάριση %1$d φακέλου αρχείων καταγραφής συνεδρίας.</item> <item quantity="other">Έγινε εκκαθάριση %1$d φακέλων αρχείων καταγραφής συνεδρίας.</item> </plurals> - <string name="main_wadb_pair_failed">Η σύζευξη ασύρματου εντοπισμού σφαλμάτων απέτυχε</string> - <string name="main_wadb_command_failed">Η εντολή ασύρματου εντοπισμού σφαλμάτων απέτυχε</string> <string name="main_wadb_unavailable">Ο ασύρματος εντοπισμός σφαλμάτων δεν είναι διαθέσιμος</string> <string name="main_adb_copied">Η εντολή ADB αντιγράφηκε</string> <string name="main_pick_roms">Επιλέξτε τον φάκελο ROMs</string> @@ -2461,10 +2418,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Οθόνη συνεδρίας</string> - <string name="display_resolution">Ανάλυση</string> + <string name="display_zero_copy">Παρουσίαση χωρίς αντιγραφή</string> + <string name="display_resolution_landscape">Ανάλυση σε οριζόντιο προσανατολισμό</string> + <string name="display_resolution_portrait">Ανάλυση σε κατακόρυφο προσανατολισμό</string> + <string name="display_follow_landscape">Ίδια με οριζόντιο (%1$d×%2$d)</string> + <string name="display_follow_portrait">Ίδια με κατακόρυφο (%1$d×%2$d)</string> <string name="display_game_fit">Προσαρμογή παιχνιδιού 16:9</string> <string name="display_game_fit_hint">Πώς προσαρμόζονται τα παιχνίδια 16:9 σε αυτή την οθόνη. Από την επόμενη συνεδρία.</string> <string name="display_game_fit_unavailable">Επιλέξτε Αντιστοίχιση οθόνης ή ένα προσαρμοσμένο μέγεθος πιο στενό από 16:9.</string> + <string name="display_avoid_notch">Αποφυγή εγκοπής</string> + <string name="display_avoid_notch_hint">Κρατά την εικόνα μακριά από την εγκοπή της κάμερας. Εφαρμόζεται όταν επιστρέψεις στη συνεδρία.</string> <string name="display_preserve">Διατήρηση αναλογιών</string> <string name="display_stretch">Διάταση στην οθόνη</string> <string name="display_image_scaling">Κλιμάκωση εικόνας</string> @@ -2751,6 +2714,7 @@ <string name="stores_login_error_ssl">Η σύνδεση με τη σελίδα σύνδεσης δεν είναι ασφαλής.</string> <string name="stores_login_error_verification">Δεν ήταν δυνατή η επαλήθευση της σύνδεσης. Δοκιμάστε ξανά.</string> <string name="stores_login_error_generic">Η σύνδεση απέτυχε. Δοκιμάστε ξανά.</string> + <string name="stores_login_continue_in_browser">Το %1$s χρειάζεται ένα ακόμη βήμα. Ολοκληρώστε το στο πρόγραμμα περιήγησης που άνοιξε και δοκιμάστε ξανά.</string> <string name="common_close">Κλείσιμο</string> <string name="common_back">Πίσω</string> <string name="common_edit">Επεξεργασία</string> @@ -3135,7 +3099,7 @@ <string name="hand_camera_done">Τέλος</string> <string name="glasses_xreal_network_missing">Αναμονή για τη σύνδεση USB Ethernet των γυαλιών. Αυτό το τηλέφωνο ίσως δεν τη διαθέτει στις εφαρμογές.</string> <string name="glasses_xreal_connection_failed">Η σύνδεση XREAL διακόπηκε ή επέστρεψε μη υποστηριζόμενη απόκριση. Νέα προσπάθεια…</string> - <string name="glasses_xreal_experimental">Πειραματική υποστήριξη για 1S. Χρησιμοποιήστε τη λειτουργία Follow και απενεργοποιήστε τη σταθεροποίηση στο μενού των γυαλιών. Οι κατευθύνσεις παρακολούθησης και οι λειτουργίες οθόνης χρειάζονται ακόμα δοκιμή σε συσκευή.</string> + <string name="glasses_xreal_experimental">Πειραματική υποστήριξη για XREAL 1S, One, One Pro, One Pro+ και Aura. Χρησιμοποιήστε τη λειτουργία Follow και απενεργοποιήστε τη σταθεροποίηση στο μενού των γυαλιών· στα Aura απενεργοποιήστε επίσης το Spatial Anchor. Η παρακολούθηση κεφαλής και η εναλλαγή 2D/3D έχουν δοκιμαστεί στα Aura και One Pro+.</string> <string name="glasses_pro2_experimental">Πειραματική παρακολούθηση κεφαλής για Pro 2. Η ρύθμιση της φωτεινότητας και της έντασης ήχου και η αλλαγή λειτουργίας οθόνης δεν υποστηρίζονται ακόμη.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Λειτουργία Cardboard</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">Περισσότερες λήψεις</string> <string name="addons_category_all">Όλες οι κατηγορίες</string> <string name="addons_none_found">Δεν βρέθηκαν πρόσθετα</string> + <string name="addons_curse_busy">Κλείστε πρώτα το CurseForge</string> <string name="addons_unreachable">Δεν ήταν δυνατή η σύνδεση με %1$s</string> <string name="addons_no_file">Δεν υπάρχει αρχείο για αυτή την έκδοση του παιχνιδιού</string> <string name="input_reset_positions">Επαναφορά θέσεων</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">Επισημάνσεις</string> <string name="theme_custom_good">Επιτυχία</string> <string name="theme_custom_error">Σφάλμα</string> + <string name="hud_only_during_game">Εμφάνιση HUD μόνο κατά τη διάρκεια παιχνιδιού</string> + <string name="hud_only_during_game_hint">Απόκρυψη HUD όταν δεν ανιχνεύονται καρέ παιχνιδιού.</string> </resources> diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 124192c1a2..d1859b029a 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Salida HDR10</string> <string name="mode_hdr_unavailable">No disponible: %1$s.</string> - <string name="mode_hdr_restart">Reinicia la app para aplicarlo.</string> <string name="mode_drivers">Controladores</string> <string name="mode_gpu_drivers">Controladores de GPU</string> <string name="mode_gpu_drivers_hint">Compartidos por Steam y Escritorio. Se definen en la página Componentes.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Inicio</string> <string name="mode_startup_session">Abrir al iniciar</string> <string name="mode_startup_session_hint">Inicia esta sesión cuando se abre DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Buscando versiones…</string> <string name="mode_decky_ready">Listo para instalar %1$s.</string> <string name="mode_decky_none">No se encontró ninguna versión compatible. Inténtalo más tarde.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Al día · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Instalar la última</string> - <string name="decky_channel">Canal de actualizaciones</string> - <string name="decky_channel_hint">Qué versiones de Decky Loader se instalan. El actualizador propio de Decky usa el mismo canal.</string> <string name="decky_channel_stable">Estable</string> <string name="decky_channel_prerelease">Preliminar</string> <string name="decky_channel_testing">Pruebas</string> <string name="decky_channel_failed">No se ha podido guardar el canal de actualizaciones de Decky</string> - <string name="mode_decky_on">Se inicia con Steam. Mientras esté activado, otras apps de este dispositivo podrían controlar Steam.</string> - <string name="mode_decky_off">Desactivado. El puerto de depuración remota de Steam permanece cerrado.</string> <string name="mode_decky_remove_title">¿Desinstalar Decky Loader?</string> <string name="mode_decky_remove_text">Elimina el loader. Tus plugins y ajustes se conservan.</string> <string name="mode_client">Cliente</string> @@ -956,13 +950,15 @@ <string name="setup_launcher_orientation_auto">Seguir la rotación del dispositivo</string> <string name="setup_orientation_portrait">Vertical</string> <string name="setup_session_orientation">Orientación de la sesión</string> - <string name="setup_session_orientation_hint">Se aplica a Steam, los juegos, el escritorio y el editor de mandos. Los ajustes predefinidos de resolución giran con la sesión; el ancho y el alto personalizados se mantienen como se introdujeron.</string> + <string name="setup_session_orientation_hint">Se aplica a Steam, los juegos, el escritorio y el editor de mandos. Los ajustes predefinidos de resolución giran con la sesión; cuando una orientación sigue a la otra, el ancho y el alto personalizados se invierten para coincidir.</string> <string name="setup_orientation_auto">Horizontal automática</string> <string name="setup_orientation_landscape">Horizontal</string> <string name="setup_orientation_reverse">Horizontal invertida</string> <string name="setup_fullscreen">Pantalla completa</string> <string name="setup_fullscreen_on">Oculta las barras de estado y navegación de Android</string> <string name="setup_fullscreen_off">Muestra las barras de estado y navegación de Android</string> + <string name="setup_page_swipe">Deslizar entre páginas</string> + <string name="setup_page_swipe_hint">Desliza sobre una página para cambiar de pestaña.</string> <string name="setup_dual_screen_launcher">Lanzador de doble pantalla</string> <string name="setup_dual_screen_launcher_hint">Automático coloca las secciones del lanzador (Steam, Biblioteca, Tiendas y el resto) en la segunda pantalla de las consolas portátiles que la llevan integrada. Activado usa cualquier segunda pantalla. Desactivado mantiene el lanzador en una sola pantalla.</string> <string name="setup_dual_screen_sessions">Sesiones de doble pantalla</string> @@ -1287,8 +1283,6 @@ <string name="gate_open_dev">Abrir Opciones de desarrollador</string> <string name="gate_no_toggle">Esta versión de Android no tiene un interruptor para ello, así que DroidDeck lo cambia mediante la Depuración inalámbrica. Tarda un minuto y no necesitas ordenador.</string> <string name="gate_needs_wifi">La Depuración inalámbrica necesita Wi-Fi. Sirve cualquier red; no necesita internet.</string> - <string name="gate_needs_notifications">El código de vinculación aparece en una notificación. Permite las notificaciones de DroidDeck o usa Otras formas.</string> - <string name="gate_allow_notifications">Permitir notificaciones</string> <string name="gate_step1">Abre Ajustes → Opciones de desarrollador → Depuración inalámbrica y actívala</string> <string name="gate_step2">Toca “Vincular dispositivo con código de vinculación”</string> <string name="gate_step3">Escribe el código en la notificación de DroidDeck</string> @@ -1305,48 +1299,13 @@ <string name="gate_status">Estado</string> <string name="gate_polling">Se comprueba cada 2 segundos. Esta página se cierra cuando esté desactivado.</string> <string name="gate_other_ways">Otras formas</string> - <string name="gate_other_toggle">Depuración inalámbrica, dirección manual, ADB desde ordenador</string> - <string name="gate_other_no_toggle">Dirección manual, ADB desde ordenador, Opciones de desarrollador</string> <string name="gate_use_wireless_instead">Usar Depuración inalámbrica en su lugar</string> <string name="gate_some_roms">Algunas ROM añaden el interruptor de todos modos. Busca “procesos secundarios” en Opciones de desarrollador.</string> - <string name="gate_manual_hint">Si la notificación no funciona, introduce manualmente la dirección y el código de la ventana.</string> - <string name="gate_enter_manually">Introducir dirección manualmente</string> <string name="gate_from_computer">Desde un ordenador con ADB:</string> <string name="gate_copy_command">Copiar comando</string> <string name="gate_sidequest_steps">Conecta el visor a un ordenador y abre SideQuest. Elige «Run ADB Command» y luego «Custom Command», escribe el comando que aparece abajo y selecciona «Run Command».</string> <string name="gate_choose_display">Elige en qué pantalla abrir los Ajustes de Android.</string> <string name="gate_main_screen">Pantalla principal</string> - <string name="wadb_finding_port">Vinculado. Buscando el puerto de la Depuración inalámbrica…</string> - <string name="wadb_enter_port">Vinculado. Introduce el puerto de Ajustes.</string> - <string name="wadb_applying">Dispositivo encontrado. Aplicando el ajuste…</string> - <string name="wadb_apply_failed">No se pudo aplicar automáticamente. Revisa la dirección de abajo y reintenta. %1$s</string> - <string name="wadb_title_wireless">Depuración inalámbrica</string> - <string name="wadb_title_done">Límite de procesos secundarios actualizado</string> - <string name="wadb_title">Cambiar el límite de procesos secundarios</string> - <string name="wadb_lede_compact0">Si falta la opción, vincula mediante la Depuración inalámbrica.</string> - <string name="wadb_lede_compact1">Vinculado. Revisa la dirección IP y el puerto en Depuración inalámbrica.</string> - <string name="wadb_lede_done">El límite de procesos secundarios se actualizó.</string> - <string name="wadb_lede0">Usa el paso 2 si las Opciones de desarrollador no tienen un ajuste de procesos secundarios. Abre Opciones de desarrollador → Depuración inalámbrica → Vincular dispositivo con código de vinculación.</string> - <string name="wadb_lede1">Vinculado. Usa la dirección de abajo o actualízala desde Depuración inalámbrica → Dirección IP y puerto.</string> - <string name="wadb_lede_done_long">El límite de procesos secundarios se actualizó mediante la Depuración inalámbrica.</string> - <string name="wadb_confirmed_on">Android confirmó que el límite está activado.</string> - <string name="wadb_confirmed_off">Android confirmó que el límite está desactivado.</string> - <string name="wadb_pair_group">2 · Vincular Depuración inalámbrica</string> - <string name="wadb_pair_address">Dirección IP y puerto de la ventana de vinculación</string> - <string name="wadb_pin">Código de vinculación (PIN)</string> - <string name="wadb_pin_placeholder">6 dígitos</string> - <string name="wadb_pair">Vincular</string> - <string name="wadb_apply_group">2 · Aplicar mediante Depuración inalámbrica</string> - <string name="wadb_connect_address">Dirección IP y puerto de conexión</string> - <string name="wadb_pair_again">Vincular de nuevo</string> - <string name="wadb_turn_off">Desactivar límite</string> - <string name="wadb_other_ways">Otras formas de cambiarlo</string> - <string name="wadb_dev_try_first">1 · Opciones de desarrollador (pruébalo primero)</string> - <string name="wadb_restrict_on">Desactiva “Inhabilitar restricciones de procesos secundarios”.</string> - <string name="wadb_restrict_off">Activa “Inhabilitar restricciones de procesos secundarios”.</string> - <string name="wadb_computer_last">3 · ADB desde ordenador (último recurso)</string> - <string name="wadb_only_if">Solo si la Depuración inalámbrica no está disponible.</string> - <string name="wadb_computer_group">3 · ADB desde ordenador (último recurso)</string> <string name="ctrl_color">Color</string> <string name="ctrl_custom">Personalizado</string> <string name="ctrl_opacity">Opacidad</string> @@ -1640,8 +1599,6 @@ <item quantity="many">Se borraron %1$d carpetas de registros de sesión.</item> <item quantity="other">Se borraron %1$d carpetas de registros de sesión.</item> </plurals> - <string name="main_wadb_pair_failed">Falló la vinculación de la Depuración inalámbrica</string> - <string name="main_wadb_command_failed">Falló el comando de la Depuración inalámbrica</string> <string name="main_wadb_unavailable">La Depuración inalámbrica no está disponible</string> <string name="main_adb_copied">Comando ADB copiado</string> <string name="main_pick_roms">Elige la carpeta de ROMs</string> @@ -2487,10 +2444,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Pantalla de la sesión</string> - <string name="display_resolution">Resolución</string> + <string name="display_zero_copy">Presentación sin copia</string> + <string name="display_resolution_landscape">Resolución horizontal</string> + <string name="display_resolution_portrait">Resolución vertical</string> + <string name="display_follow_landscape">Igual que horizontal (%1$d×%2$d)</string> + <string name="display_follow_portrait">Igual que vertical (%1$d×%2$d)</string> <string name="display_game_fit">Ajuste de juegos 16:9</string> <string name="display_game_fit_hint">Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión.</string> <string name="display_game_fit_unavailable">Elige Igual a la pantalla o un tamaño personalizado más estrecho que 16:9.</string> + <string name="display_avoid_notch">Evitar la muesca</string> + <string name="display_avoid_notch_hint">Mantiene la imagen fuera del recorte de la cámara. Se aplica al volver a la sesión.</string> <string name="display_preserve">Mantener proporciones</string> <string name="display_stretch">Estirar a la pantalla</string> <string name="display_image_scaling">Escalado de imagen</string> @@ -2774,6 +2737,7 @@ <string name="stores_login_error_ssl">La conexión con la página de inicio de sesión no es segura.</string> <string name="stores_login_error_verification">No se pudo verificar el inicio de sesión. Inténtalo de nuevo.</string> <string name="stores_login_error_generic">No se pudo iniciar sesión. Inténtalo de nuevo.</string> + <string name="stores_login_continue_in_browser">%1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo.</string> <string name="common_close">Cerrar</string> <string name="common_back">Atrás</string> <string name="common_edit">Editar</string> @@ -3151,7 +3115,7 @@ <string name="hand_camera_done">Hecho</string> <string name="glasses_xreal_network_missing">Esperando la conexión Ethernet por USB de las gafas. Puede que este teléfono no la ofrezca a las apps.</string> <string name="glasses_xreal_connection_failed">La conexión con las XREAL se interrumpió o devolvió una respuesta no compatible. Reintentando…</string> - <string name="glasses_xreal_experimental">Compatibilidad experimental con las 1S. Usa el modo Follow y desactiva la estabilización en el menú de las gafas. Aún falta probar en el dispositivo las direcciones del seguimiento y los modos de pantalla.</string> + <string name="glasses_xreal_experimental">Compatibilidad experimental con XREAL 1S, One, One Pro, One Pro+ y Aura. Usa el modo Follow y desactiva la estabilización en el menú de las gafas; en Aura, desactiva también Spatial Anchor. El seguimiento de cabeza y el cambio entre 2D/3D se han probado en Aura y One Pro+.</string> <string name="glasses_pro2_experimental">Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles.</string> <string name="stores_fact_developer">Desarrollador</string> <string name="stores_fact_publisher">Distribuidor</string> @@ -4050,6 +4014,7 @@ <string name="addons_sort_downloads">Más descargados</string> <string name="addons_category_all">Todas las categorías</string> <string name="addons_none_found">No se han encontrado complementos</string> + <string name="addons_curse_busy">Cierra CurseForge primero</string> <string name="addons_unreachable">No se pudo conectar con %1$s</string> <string name="addons_no_file">No hay ningún archivo para esta versión del juego</string> <string name="input_reset_positions">Restablecer posiciones</string> @@ -4153,4 +4118,6 @@ <string name="theme_custom_signal">Destacados</string> <string name="theme_custom_good">Éxito</string> <string name="theme_custom_error">Error</string> + <string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string> + <string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string> </resources> diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 2d7ea36c72..4cf72f1674 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-lähtö</string> <string name="mode_hdr_unavailable">Ei käytettävissä: %1$s.</string> - <string name="mode_hdr_restart">Käynnistä sovellus uudelleen, jotta muutos tulee voimaan.</string> <string name="mode_drivers">Ajurit</string> <string name="mode_gpu_drivers">GPU-ajurit</string> <string name="mode_gpu_drivers_hint">Jaettu Steamin ja Työpöydän kesken. Asetetaan Komponentit-sivulla.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Käynnistys</string> <string name="mode_startup_session">Avaa käynnistyksessä</string> <string name="mode_startup_session_hint">Käynnistää tämän istunnon, kun DroidDeck avataan.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Tarkistetaan julkaisuja…</string> <string name="mode_decky_ready">Valmiina asentamaan %1$s.</string> <string name="mode_decky_none">Yhteensopivaa versiota ei löytynyt. Yritä myöhemmin uudelleen.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Ajan tasalla · %1$s</string> <string name="mode_decky_loader">Lataaja</string> <string name="mode_decky_install_latest">Asenna uusin</string> - <string name="decky_channel">Päivityskanava</string> - <string name="decky_channel_hint">Mitkä Decky Loader -julkaisut asennetaan. Deckyn oma päivitysohjelma käyttää samaa kanavaa.</string> <string name="decky_channel_stable">Vakaa</string> <string name="decky_channel_prerelease">Esijulkaisu</string> <string name="decky_channel_testing">Testaus</string> <string name="decky_channel_failed">Deckyn päivityskanavaa ei voitu tallentaa</string> - <string name="mode_decky_on">Käynnistyy Steamin kanssa. Päällä ollessaan muut tämän laitteen sovellukset voivat pystyä ohjaamaan Steamia.</string> - <string name="mode_decky_off">Pois. Steamin etävianmääritysportti pysyy suljettuna.</string> <string name="mode_decky_remove_title">Poistetaanko Decky Loader?</string> <string name="mode_decky_remove_text">Poistaa loaderin. Laajennuksesi ja asetuksesi säilyvät.</string> <string name="mode_client">Asiakasohjelma</string> @@ -953,13 +947,15 @@ <string name="setup_launcher_orientation_auto">Seuraa laitteen kiertoa</string> <string name="setup_orientation_portrait">Pystysuunta</string> <string name="setup_session_orientation">Istunnon suunta</string> - <string name="setup_session_orientation_hint">Koskee Steamia, pelejä, työpöytää ja ohjainmuokkainta. Resoluution esiasetukset kääntyvät istunnon mukana; mukautettu leveys ja korkeus pysyvät syötetyn mukaisina.</string> + <string name="setup_session_orientation_hint">Koskee Steamia, pelejä, työpöytää ja ohjainmuokkainta. Resoluution esiasetukset kääntyvät istunnon mukana; kun toinen suunta seuraa toista, mukautettu leveys ja korkeus vaihtavat paikkaa vastaamaan toisiaan.</string> <string name="setup_orientation_auto">Automaattinen vaakasuunta</string> <string name="setup_orientation_landscape">Vaakasuunta</string> <string name="setup_orientation_reverse">Käänteinen vaakasuunta</string> <string name="setup_fullscreen">Koko näyttö</string> <string name="setup_fullscreen_on">Piilottaa Androidin tila- ja navigointipalkit</string> <string name="setup_fullscreen_off">Näyttää Androidin tila- ja navigointipalkit</string> + <string name="setup_page_swipe">Pyyhkäise sivujen välillä</string> + <string name="setup_page_swipe_hint">Vaihda välilehteä pyyhkäisemällä sivun poikki.</string> <string name="setup_dual_screen_launcher">Kahden näytön käynnistin</string> <string name="setup_dual_screen_launcher_hint">Automaattinen siirtää käynnistimen osiot (Steam, Kirjasto, Kaupat ja muut) käsikonsolin sisäänrakennetulle toiselle näytölle. Päällä käyttää mitä tahansa toista näyttöä. Pois päältä pitää käynnistimen yhdellä näytöllä.</string> <string name="setup_dual_screen_sessions">Kahden näytön istunnot</string> @@ -1280,8 +1276,6 @@ <string name="gate_open_dev">Avaa Kehittäjäasetukset</string> <string name="gate_no_toggle">Tässä Android-versiossa ei ole kytkintä tälle, niin DroidDeck muuttaa sen Langattoman virheenkorjauksen kautta. Kestää noin minuutin, ei tarvita tietokonetta.</string> <string name="gate_needs_wifi">Langaton virheenkorjaus vaatii Wi-Fi-yhteyden. Mikä tahansa verkko käy; internet-yhteyttä ei tarvita.</string> - <string name="gate_needs_notifications">Pariutuskoodi tulee ilmoitukseen. Salli ilmoitukset DroidDeckille, tai käytä Muita tapoja.</string> - <string name="gate_allow_notifications">Salli ilmoitukset</string> <string name="gate_step1">Avaa Asetukset → Kehittäjäasetukset → Langaton virheenkorjaus ja kytke se päälle</string> <string name="gate_step2">Napauta ”Pariuta laite pariutuskoodilla”</string> <string name="gate_step3">Kirjoita koodi DroidDeckin ilmoitukseen</string> @@ -1298,48 +1292,13 @@ <string name="gate_status">Tila</string> <string name="gate_polling">Tarkistetaan 2 sekunnin välein. Tämä sivu sulkeutuu, kun se on pois päältä.</string> <string name="gate_other_ways">Muita tapoja</string> - <string name="gate_other_toggle">Langaton virheenkorjaus, manuaalinen osoite, tietokoneen ADB</string> - <string name="gate_other_no_toggle">Manuaalinen osoite, tietokoneen ADB, Kehittäjäasetukset</string> <string name="gate_use_wireless_instead">Käytä sen sijaan Langatonta virheenkorjausta</string> <string name="gate_some_roms">Jotkin ROM-versiot lisäävät kytkimen joka tapauksessa. Etsi ”child process” Kehittäjäasetuksista.</string> - <string name="gate_manual_hint">Jos ilmoitus ei toimi, syötä ponnahdusikkunan osoite ja koodi itse.</string> - <string name="gate_enter_manually">Syötä osoite manuaalisesti</string> <string name="gate_from_computer">Tietokoneelta ADB:llä:</string> <string name="gate_copy_command">Kopioi komento</string> <string name="gate_sidequest_steps">Liitä lasit tietokoneeseen ja avaa SideQuest. Valitse ”Run ADB Command” ja sitten ”Custom Command”, kirjoita alla näkyvä komento ja valitse ”Run Command”.</string> <string name="gate_choose_display">Valitse, millä näytöllä Android-asetukset avataan.</string> <string name="gate_main_screen">Päänäyttö</string> - <string name="wadb_finding_port">Pariutui. Etsitään Langattoman virheenkorjauksen porttia…</string> - <string name="wadb_enter_port">Pariutui. Syötä portti Asetuksista.</string> - <string name="wadb_applying">Laite löytyi. Otetaan asetus käyttöön…</string> - <string name="wadb_apply_failed">Automaattinen käyttöönotto epäonnistui. Tarkista alla oleva osoite ja yritä uudelleen. %1$s</string> - <string name="wadb_title_wireless">Langaton virheenkorjaus</string> - <string name="wadb_title_done">Lapsiprosessien raja päivitetty</string> - <string name="wadb_title">Muuta lapsiprosessien rajaa</string> - <string name="wadb_lede_compact0">Jos asetus puuttuu, pariuta Langattoman virheenkorjauksen kautta.</string> - <string name="wadb_lede_compact1">Pariutui. Tarkista IP-osoite ja portti Langattomasta virheenkorjauksesta.</string> - <string name="wadb_lede_done">Lapsiprosessien raja päivitettiin.</string> - <string name="wadb_lede0">Käytä vaihetta 2, jos Kehittäjäasetuksissa ei ole lapsiprosessiasetusta. Avaa Kehittäjäasetukset → Langaton virheenkorjaus → Pariuta laite pariutuskoodilla.</string> - <string name="wadb_lede1">Pariutui. Käytä alla olevaa osoitetta, tai päivitä se Langaton virheenkorjaus → IP-osoite ja portti -kohdasta.</string> - <string name="wadb_lede_done_long">Lapsiprosessien raja päivitettiin Langattoman virheenkorjauksen kautta.</string> - <string name="wadb_confirmed_on">Android vahvisti, että raja on päällä.</string> - <string name="wadb_confirmed_off">Android vahvisti, että raja on pois päältä.</string> - <string name="wadb_pair_group">2 · Pariuta Langaton virheenkorjaus</string> - <string name="wadb_pair_address">Pariutuksen ponnahdusikkunan IP-osoite ja portti</string> - <string name="wadb_pin">Pariutuskoodi (PIN)</string> - <string name="wadb_pin_placeholder">6 numeroa</string> - <string name="wadb_pair">Pariuta</string> - <string name="wadb_apply_group">2 · Ota käyttöön Langattoman virheenkorjauksen kautta</string> - <string name="wadb_connect_address">Yhteyden IP-osoite ja portti</string> - <string name="wadb_pair_again">Pariuta uudelleen</string> - <string name="wadb_turn_off">Kytke raja pois päältä</string> - <string name="wadb_other_ways">Muita tapoja muuttaa sitä</string> - <string name="wadb_dev_try_first">1 · Kehittäjäasetukset (kokeile ensin)</string> - <string name="wadb_restrict_on">Aseta ”Poista käytöstä alatason prosessirajoitukset” pois päältä.</string> - <string name="wadb_restrict_off">Aseta ”Poista käytöstä alatason prosessirajoitukset” päälle.</string> - <string name="wadb_computer_last">3 · Tietokoneen ADB (viimeinen keino)</string> - <string name="wadb_only_if">Vain jos Langaton virheenkorjaus ei ole käytettävissä.</string> - <string name="wadb_computer_group">3 · Tietokoneen ADB (viimeinen keino)</string> <string name="ctrl_color">Väri</string> <string name="ctrl_custom">Mukautettu</string> <string name="ctrl_opacity">Peittävyys</string> @@ -1627,8 +1586,6 @@ <item quantity="one">Tyhjennettiin %1$d istuntolokikansio.</item> <item quantity="other">Tyhjennettiin %1$d istuntolokikansiota.</item> </plurals> - <string name="main_wadb_pair_failed">Langattoman virheenkorjauksen laitepariutus epäonnistui</string> - <string name="main_wadb_command_failed">Langattoman virheenkorjauksen komento epäonnistui</string> <string name="main_wadb_unavailable">Langaton virheenkorjaus ei ole käytettävissä</string> <string name="main_adb_copied">ADB-komento kopioitu</string> <string name="main_pick_roms">Valitse ROMs-kansio</string> @@ -2461,10 +2418,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Istunnon näyttö</string> - <string name="display_resolution">Tarkkuus</string> + <string name="display_zero_copy">Kopioimaton esitys</string> + <string name="display_resolution_landscape">Vaakatilan resoluutio</string> + <string name="display_resolution_portrait">Pystytilan resoluutio</string> + <string name="display_follow_landscape">Seuraa vaakaa (%1$d×%2$d)</string> + <string name="display_follow_portrait">Seuraa pystyä (%1$d×%2$d)</string> <string name="display_game_fit">16:9-pelin sovitus</string> <string name="display_game_fit_hint">Miten 16:9-pelit sovitetaan tähän näyttöön. Seuraava istunto.</string> <string name="display_game_fit_unavailable">Valitse Sovita näyttöön tai mukautettu koko, joka on 16:9:ää kapeampi.</string> + <string name="display_avoid_notch">Vältä lovea</string> + <string name="display_avoid_notch_hint">Pitää kuvan poissa kameran lovesta. Tulee voimaan, kun palaat istuntoon.</string> <string name="display_preserve">Säilytä kuvasuhde</string> <string name="display_stretch">Venytä näyttöön</string> <string name="display_image_scaling">Kuvan skaalaus</string> @@ -2751,6 +2714,7 @@ <string name="stores_login_error_ssl">Yhteys kirjautumissivulle ei ole suojattu.</string> <string name="stores_login_error_verification">Kirjautumista ei voitu vahvistaa. Yritä uudelleen.</string> <string name="stores_login_error_generic">Kirjautuminen epäonnistui. Yritä uudelleen.</string> + <string name="stores_login_continue_in_browser">%1$s vaatii vielä yhden vaiheen. Viimeistele se avautuneessa selaimessa ja yritä sitten uudelleen.</string> <string name="common_close">Sulje</string> <string name="common_back">Takaisin</string> <string name="common_edit">Muokkaa</string> @@ -3135,7 +3099,7 @@ <string name="hand_camera_done">Valmis</string> <string name="glasses_xreal_network_missing">Odotetaan lasien USB-Ethernet-yhteyttä. Tämä puhelin ei ehkä tarjoa sitä sovelluksille.</string> <string name="glasses_xreal_connection_failed">XREAL-yhteys katkesi tai palautti vastauksen, jota ei tueta. Yritetään uudelleen…</string> - <string name="glasses_xreal_experimental">Kokeellinen 1S-tuki. Käytä Follow-tilaa ja poista vakautus käytöstä lasien valikosta. Seurannan suunnat ja näyttötilat vaativat vielä testausta laitteella.</string> + <string name="glasses_xreal_experimental">Kokeellinen tuki XREAL 1S-, One-, One Pro-, One Pro+- ja Aura-laseille. Käytä Follow-tilaa ja poista vakautus käytöstä lasien valikosta. Poista Aura-laseissa myös Spatial Anchor käytöstä. Päänseuranta ja 2D/3D-vaihto on testattu Aura- ja One Pro+ -laseilla.</string> <string name="glasses_pro2_experimental">Kokeellinen päänliikkeiden seuranta Pro 2:lle. Kirkkauden ja äänenvoimakkuuden säätöä sekä näyttötilan vaihtamista ei vielä tueta.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-tila</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">Ladatuimmat</string> <string name="addons_category_all">Kaikki luokat</string> <string name="addons_none_found">Lisäosia ei löytynyt</string> + <string name="addons_curse_busy">Sulje CurseForge ensin</string> <string name="addons_unreachable">Yhteyttä palveluun %1$s ei saatu</string> <string name="addons_no_file">Tälle peliversiolle ei ole tiedostoa</string> <string name="input_reset_positions">Palauta sijainnit</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">Korostukset</string> <string name="theme_custom_good">Onnistuminen</string> <string name="theme_custom_error">Virhe</string> + <string name="hud_only_during_game">Näytä HUD vain pelin aikana</string> + <string name="hud_only_during_game_hint">Piilota HUD, kun pelin ruutuja ei havaita.</string> </resources> diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f21ab1e3a2..c735507d40 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Sortie HDR10</string> <string name="mode_hdr_unavailable">Non disponible : %1$s.</string> - <string name="mode_hdr_restart">Prendra effet après le redémarrage de l\'application.</string> <string name="mode_drivers">Pilotes</string> <string name="mode_gpu_drivers">Pilotes GPU</string> <string name="mode_gpu_drivers_hint">Partagés entre Steam et le bureau. À configurer dans la page « Composants ».</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Démarrage</string> <string name="mode_startup_session">Ouvrir au démarrage</string> <string name="mode_startup_session_hint">Lance cette session au démarrage de DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Vérification des versions…</string> <string name="mode_decky_ready">Prêt à installer %1$s.</string> <string name="mode_decky_none">Aucune version compatible trouvée. Veuillez réessayer plus tard.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">À jour · %1$s</string> <string name="mode_decky_loader">Chargeur</string> <string name="mode_decky_install_latest">Installer la dernière version</string> - <string name="decky_channel">Canal de mise à jour</string> - <string name="decky_channel_hint">Les versions de Decky Loader à installer. Le programme de mise à jour de Decky utilise le même canal.</string> <string name="decky_channel_stable">Stable</string> <string name="decky_channel_prerelease">Préversion</string> <string name="decky_channel_testing">Test</string> <string name="decky_channel_failed">Impossible d\'enregistrer le canal de mise à jour de Decky</string> - <string name="mode_decky_on">Démarre avec Steam. Une fois activé, d\'autres applications sur cet appareil peuvent contrôler Steam.</string> - <string name="mode_decky_off">Désactivé. Le port de débogage distant de Steam reste fermé.</string> <string name="mode_decky_remove_title">Désinstaller Decky Loader ?</string> <string name="mode_decky_remove_text">Supprime le chargeur. Vos plugins et paramètres seront conservés.</string> <string name="mode_client">Client</string> @@ -956,13 +950,15 @@ <string name="setup_launcher_orientation_auto">Suivre la rotation de l\'appareil</string> <string name="setup_orientation_portrait">Portrait</string> <string name="setup_session_orientation">Orientation de la session</string> - <string name="setup_session_orientation_hint">S\'applique à Steam, aux jeux, au bureau et à l\'éditeur de manette. Les préréglages de résolution pivotent avec la session ; la largeur et la hauteur personnalisées restent telles que saisies.</string> + <string name="setup_session_orientation_hint">S\'applique à Steam, aux jeux, au bureau et à l\'éditeur de manette. Les préréglages de résolution pivotent avec la session ; lorsqu\'une orientation suit l\'autre, la largeur et la hauteur personnalisées sont inversées pour correspondre.</string> <string name="setup_orientation_auto">Paysage automatique</string> <string name="setup_orientation_landscape">Paysage</string> <string name="setup_orientation_reverse">Paysage inversé</string> <string name="setup_fullscreen">Plein écran</string> <string name="setup_fullscreen_on">Masquer la barre d\'état et la barre de navigation Android</string> <string name="setup_fullscreen_off">Afficher la barre d\'état et la barre de navigation Android</string> + <string name="setup_page_swipe">Balayer entre les pages</string> + <string name="setup_page_swipe_hint">Balayez une page pour changer d\'onglet.</string> <string name="setup_dual_screen_launcher">Lanceur double écran</string> <string name="setup_dual_screen_launcher_hint">Automatique place les sections du lanceur (Steam, Bibliothèque, Boutiques et les autres) sur le second écran intégré des consoles portables qui en sont équipées. Activé utilise n\'importe quel écran secondaire. Désactivé conserve le lanceur sur un seul écran.</string> <string name="setup_dual_screen_sessions">Sessions double écran</string> @@ -1286,8 +1282,6 @@ <string name="gate_open_dev">Ouvrir les options pour les développeurs</string> <string name="gate_no_toggle">Cette version d\'Android ne dispose pas de cet interrupteur, DroidDeck effectuera donc la modification via le débogage sans fil. Cela prend environ une minute, sans ordinateur.</string> <string name="gate_needs_wifi">Le débogage sans fil nécessite un Wi-Fi. N\'importe quel réseau convient, Internet n\'est pas nécessaire.</string> - <string name="gate_needs_notifications">Le code d\'appairage s\'affichera dans une notification. Veuillez autoriser DroidDeck à envoyer des notifications, ou utilisez « Autre méthode ».</string> - <string name="gate_allow_notifications">Autoriser les notifications</string> <string name="gate_step1">Ouvrez Paramètres → Options pour les développeurs → Débogage sans fil, et activez-le</string> <string name="gate_step2">Appuyez sur « Associer l\'appareil avec un code d\'appairage »</string> <string name="gate_step3">Saisissez le code d\'appairage dans la notification DroidDeck</string> @@ -1304,48 +1298,13 @@ <string name="gate_status">État</string> <string name="gate_polling">Vérification toutes les 2 secondes. Cette page se fermera automatiquement une fois cet interrupteur désactivé.</string> <string name="gate_other_ways">Autres méthodes</string> - <string name="gate_other_toggle">Débogage sans fil, saisie manuelle de l\'adresse, ADB sur PC</string> - <string name="gate_other_no_toggle">Saisie manuelle de l\'adresse, ADB sur PC, options pour les développeurs</string> <string name="gate_use_wireless_instead">Utiliser plutôt le débogage sans fil</string> <string name="gate_some_roms">Certaines ROM proposent encore cet interrupteur. Recherchez « processus enfants » dans les options pour les développeurs.</string> - <string name="gate_manual_hint">Si la méthode par notification ne fonctionne pas, saisissez manuellement l\'adresse et le code d\'appairage de la fenêtre.</string> - <string name="gate_enter_manually">Saisir l\'adresse manuellement</string> <string name="gate_from_computer">Utiliser ADB depuis un ordinateur :</string> <string name="gate_copy_command">Copier la commande</string> <string name="gate_sidequest_steps">Branchez le casque à un ordinateur et ouvrez SideQuest. Choisissez « Run ADB Command », puis « Custom Command », saisissez la commande affichée ci-dessous et sélectionnez « Run Command ».</string> <string name="gate_choose_display">Choisissez l\'écran sur lequel ouvrir les paramètres Android.</string> <string name="gate_main_screen">Écran principal</string> - <string name="wadb_finding_port">Appairé. Recherche du port de débogage sans fil…</string> - <string name="wadb_enter_port">Appairé. Veuillez saisir le port indiqué dans les paramètres.</string> - <string name="wadb_applying">Appareil trouvé. Application des paramètres…</string> - <string name="wadb_apply_failed">Impossible d\'appliquer automatiquement. Veuillez vérifier l\'adresse ci-dessous et réessayer. %1$s</string> - <string name="wadb_title_wireless">Débogage sans fil</string> - <string name="wadb_title_done">Limite des processus enfants mise à jour</string> - <string name="wadb_title">Modifier la limite des processus enfants</string> - <string name="wadb_lede_compact0">Si cette option n\'est pas disponible, appairez via le débogage sans fil.</string> - <string name="wadb_lede_compact1">Appairé. Veuillez vérifier l\'adresse IP et le port dans le débogage sans fil.</string> - <string name="wadb_lede_done">La limite des processus enfants a été mise à jour.</string> - <string name="wadb_lede0">Si l\'option de processus enfants n\'est pas disponible dans les options pour les développeurs, utilisez l\'étape 2. Ouvrez Options pour les développeurs → Débogage sans fil → Associer l\'appareil avec un code d\'appairage.</string> - <string name="wadb_lede1">Appairé. Utilisez l\'adresse ci-dessous, ou mettez-la à jour dans Débogage sans fil → Adresse IP et port.</string> - <string name="wadb_lede_done_long">Limite des processus enfants mise à jour via le débogage sans fil.</string> - <string name="wadb_confirmed_on">Android a confirmé que la limite est activée.</string> - <string name="wadb_confirmed_off">Android a confirmé que la limite est désactivée.</string> - <string name="wadb_pair_group">2 · Appairer le débogage sans fil</string> - <string name="wadb_pair_address">Adresse IP et port dans la fenêtre d\'appairage</string> - <string name="wadb_pin">Code d\'appairage (PIN)</string> - <string name="wadb_pin_placeholder">6 chiffres</string> - <string name="wadb_pair">Appairer</string> - <string name="wadb_apply_group">2 · Appliquer via le débogage sans fil</string> - <string name="wadb_connect_address">Adresse IP et port de connexion</string> - <string name="wadb_pair_again">Réappairer</string> - <string name="wadb_turn_off">Désactiver la limite</string> - <string name="wadb_other_ways">Autres méthodes de modification</string> - <string name="wadb_dev_try_first">1 · Options pour les développeurs (à essayer en premier)</string> - <string name="wadb_restrict_on">Désactivez « Désactiver les limites pour les processus enfant ».</string> - <string name="wadb_restrict_off">Activez « Désactiver les limites pour les processus enfant ».</string> - <string name="wadb_computer_last">3 · ADB sur PC (en dernier recours)</string> - <string name="wadb_only_if">À utiliser uniquement si le débogage sans fil n\'est pas disponible.</string> - <string name="wadb_computer_group">3 · ADB sur PC (en dernier recours)</string> <string name="ctrl_color">Couleur</string> <string name="ctrl_custom">Personnalisée</string> <string name="ctrl_opacity">Opacité</string> @@ -1639,8 +1598,6 @@ <item quantity="many">%1$d dossiers de journaux de session effacés.</item> <item quantity="other">%1$d dossiers de journaux de session effacés.</item> </plurals> - <string name="main_wadb_pair_failed">Échec de l\'appairage du débogage sans fil</string> - <string name="main_wadb_command_failed">Échec de la commande de débogage sans fil</string> <string name="main_wadb_unavailable">Le débogage sans fil n\'est pas disponible</string> <string name="main_adb_copied">Commande ADB copiée</string> <string name="main_pick_roms">Choisir le dossier ROM</string> @@ -2486,10 +2443,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Affichage de la session</string> - <string name="display_resolution">Résolution</string> + <string name="display_zero_copy">Affichage sans copie</string> + <string name="display_resolution_landscape">Résolution en paysage</string> + <string name="display_resolution_portrait">Résolution en portrait</string> + <string name="display_follow_landscape">Comme le paysage (%1$d×%2$d)</string> + <string name="display_follow_portrait">Comme le portrait (%1$d×%2$d)</string> <string name="display_game_fit">Ajustement des jeux 16:9</string> <string name="display_game_fit_hint">Comment les jeux 16:9 s\'adaptent à cet écran. À la prochaine session.</string> <string name="display_game_fit_unavailable">Choisissez « Adapter à l\'écran » ou une taille personnalisée plus étroite que 16:9.</string> + <string name="display_avoid_notch">Éviter l\'encoche</string> + <string name="display_avoid_notch_hint">Garde l\'image hors de la découpe de la caméra. S\'applique au retour dans la session.</string> <string name="display_preserve">Conserver les proportions</string> <string name="display_stretch">Étirer sur l\'écran</string> <string name="display_image_scaling">Mise à l\'échelle de l\'image</string> @@ -2773,6 +2736,7 @@ <string name="stores_login_error_ssl">La liaison avec la page de connexion n\'est pas sécurisée.</string> <string name="stores_login_error_verification">Impossible de vérifier la connexion. Réessayez.</string> <string name="stores_login_error_generic">Échec de la connexion. Réessayez.</string> + <string name="stores_login_continue_in_browser">%1$s demande une étape de plus. Terminez-la dans le navigateur qui s\'est ouvert, puis réessayez.</string> <string name="common_close">Fermer</string> <string name="common_back">Retour</string> <string name="common_edit">Modifier</string> @@ -3161,7 +3125,7 @@ <string name="hand_camera_done">Terminé</string> <string name="glasses_xreal_network_missing">En attente de la connexion Ethernet USB des lunettes. Ce téléphone ne la rend peut-être pas accessible aux applications.</string> <string name="glasses_xreal_connection_failed">La connexion XREAL a été interrompue ou a renvoyé une réponse non prise en charge. Nouvelle tentative…</string> - <string name="glasses_xreal_experimental">Prise en charge expérimentale des 1S. Utilisez le mode Follow et désactivez la stabilisation dans le menu des lunettes. Le sens du suivi et les modes d\'affichage restent à tester sur l\'appareil.</string> + <string name="glasses_xreal_experimental">Prise en charge expérimentale des XREAL 1S, One, One Pro, One Pro+ et Aura. Utilisez le mode Follow et désactivez la stabilisation dans le menu des lunettes ; sur les Aura, désactivez aussi Spatial Anchor. Le suivi de la tête et le passage entre 2D/3D ont été testés sur les Aura et les One Pro+.</string> <string name="glasses_pro2_experimental">Suivi expérimental des mouvements de la tête pour Pro 2. Le réglage de la luminosité et du volume ainsi que le changement de mode d\'affichage ne sont pas encore pris en charge.</string> <string name="stores_fact_developer">Développeur</string> <string name="stores_fact_publisher">Éditeur</string> @@ -4049,6 +4013,7 @@ <string name="addons_sort_downloads">Les plus téléchargés</string> <string name="addons_category_all">Toutes les catégories</string> <string name="addons_none_found">Aucun addon trouvé</string> + <string name="addons_curse_busy">Fermez d\'abord CurseForge</string> <string name="addons_unreachable">Impossible de joindre %1$s</string> <string name="addons_no_file">Aucun fichier pour cette version du jeu</string> <string name="input_reset_positions">Réinitialiser les positions</string> @@ -4152,4 +4117,6 @@ <string name="theme_custom_signal">Mises en évidence</string> <string name="theme_custom_good">Succès</string> <string name="theme_custom_error">Erreur</string> + <string name="hud_only_during_game">Afficher le HUD uniquement pendant une partie</string> + <string name="hud_only_during_game_hint">Masquer le HUD lorsqu’aucune image du jeu n’est détectée.</string> </resources> diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index d322fa0d01..c3b71210f6 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 आउटपुट</string> <string name="mode_hdr_unavailable">उपलब्ध नहीं: %1$s।</string> - <string name="mode_hdr_restart">लागू करने के लिए ऐप रीस्टार्ट करें।</string> <string name="mode_drivers">ड्राइवर</string> <string name="mode_gpu_drivers">GPU ड्राइवर</string> <string name="mode_gpu_drivers_hint">Steam और डेस्कटॉप दोनों में साझा। Components पेज पर सेट करें।</string> @@ -333,7 +332,6 @@ <string name="mode_startup">स्टार्टअप</string> <string name="mode_startup_session">लॉन्च पर खोलें</string> <string name="mode_startup_session_hint">DroidDeck खुलने पर यह सेशन शुरू करता है।</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">रिलीज़ देखी जा रही हैं…</string> <string name="mode_decky_ready">%1$s इंस्टॉल करने के लिए तैयार।</string> <string name="mode_decky_none">कोई कम्पैटिबल बिल्ड नहीं मिला। बाद में फिर कोशिश करें।</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">नवीनतम · %1$s</string> <string name="mode_decky_loader">लोडर</string> <string name="mode_decky_install_latest">नवीनतम इंस्टॉल करें</string> - <string name="decky_channel">अपडेट चैनल</string> - <string name="decky_channel_hint">कौन-सी Decky Loader रिलीज़ इंस्टॉल करनी हैं। Decky का अपना अपडेटर भी यही चैनल इस्तेमाल करता है।</string> <string name="decky_channel_stable">स्टेबल</string> <string name="decky_channel_prerelease">प्री-रिलीज़</string> <string name="decky_channel_testing">टेस्टिंग</string> <string name="decky_channel_failed">Decky अपडेट चैनल सेव नहीं हो सका</string> - <string name="mode_decky_on">Steam के साथ शुरू होता है। चालू रहते हुए, इस डिवाइस के दूसरे ऐप Steam को नियंत्रित कर सकते हैं।</string> - <string name="mode_decky_off">बंद। Steam का रिमोट डिबगिंग पोर्ट बंद रहता है।</string> <string name="mode_decky_remove_title">Decky Loader अनइंस्टॉल करें?</string> <string name="mode_decky_remove_text">लोडर हटाता है। आपके प्लगइन और सेटिंग बनी रहती हैं।</string> <string name="mode_client">क्लाइंट</string> @@ -953,13 +947,15 @@ <string name="setup_launcher_orientation_auto">डिवाइस रोटेशन के अनुसार</string> <string name="setup_orientation_portrait">पोर्ट्रेट</string> <string name="setup_session_orientation">सेशन ओरिएंटेशन</string> - <string name="setup_session_orientation_hint">Steam, गेम, डेस्कटॉप और कंट्रोलर एडिटर पर लागू होता है। रिज़ॉल्यूशन प्रीसेट सेशन के साथ घूमते हैं; कस्टम चौड़ाई और ऊंचाई जैसी डाली गई वैसी ही रहती हैं।</string> + <string name="setup_session_orientation_hint">Steam, गेम, डेस्कटॉप और कंट्रोलर एडिटर पर लागू होता है। रिज़ॉल्यूशन प्रीसेट सेशन के साथ घूमते हैं; जब एक ओरिएंटेशन दूसरे को फ़ॉलो करता है, तो कस्टम चौड़ाई और ऊंचाई बदलकर मेल खाती हैं।</string> <string name="setup_orientation_auto">ऑटोमैटिक लैंडस्केप</string> <string name="setup_orientation_landscape">लैंडस्केप</string> <string name="setup_orientation_reverse">उलटा लैंडस्केप</string> <string name="setup_fullscreen">फ़ुलस्क्रीन</string> <string name="setup_fullscreen_on">Android स्टेटस और नेविगेशन बार छिपाता है</string> <string name="setup_fullscreen_off">Android स्टेटस और नेविगेशन बार दिखाता है</string> + <string name="setup_page_swipe">पेजों के बीच स्वाइप करें</string> + <string name="setup_page_swipe_hint">टैब बदलने के लिए किसी पेज पर स्वाइप करें।</string> <string name="setup_dual_screen_launcher">डुअल स्क्रीन लॉन्चर</string> <string name="setup_dual_screen_launcher_hint">स्वचालित पर, बिल्ट-इन दूसरी स्क्रीन वाले हैंडहेल्ड में लॉन्चर के सेक्शन (Steam, लाइब्रेरी, स्टोर्स और बाकी) दूसरी स्क्रीन पर चले जाते हैं। चालू पर कोई भी दूसरी डिस्प्ले इस्तेमाल होती है। बंद पर लॉन्चर एक ही स्क्रीन पर रहता है।</string> <string name="setup_dual_screen_sessions">डुअल स्क्रीन सत्र</string> @@ -1280,8 +1276,6 @@ <string name="gate_open_dev">डेवलपर विकल्प खोलें</string> <string name="gate_no_toggle">इस Android वर्शन में इसके लिए कोई स्विच नहीं है, इसलिए DroidDeck इसे वायरलेस डीबगिंग के ज़रिए बदलता है। इसमें लगभग एक मिनट लगता है, किसी कंप्यूटर की ज़रूरत नहीं।</string> <string name="gate_needs_wifi">वायरलेस डीबगिंग के लिए Wi-Fi चाहिए। कोई भी नेटवर्क काम करेगा; इंटरनेट की ज़रूरत नहीं है।</string> - <string name="gate_needs_notifications">पेयरिंग कोड एक नोटिफ़िकेशन में आता है। DroidDeck के लिए नोटिफ़िकेशन की अनुमति दें, या अन्य तरीके इस्तेमाल करें।</string> - <string name="gate_allow_notifications">नोटिफ़िकेशन की अनुमति दें</string> <string name="gate_step1">Settings → डेवलपर विकल्प → वायरलेस डीबगिंग खोलें और उसे चालू करें</string> <string name="gate_step2">“Pair device with pairing code” पर टैप करें</string> <string name="gate_step3">DroidDeck नोटिफ़िकेशन में कोड टाइप करें</string> @@ -1298,48 +1292,13 @@ <string name="gate_status">स्थिति</string> <string name="gate_polling">हर 2 सेकंड में जांच हो रही है। यह बंद होने पर यह पेज बंद हो जाता है।</string> <string name="gate_other_ways">अन्य तरीके</string> - <string name="gate_other_toggle">वायरलेस डीबगिंग, मैनुअल एड्रेस, कंप्यूटर ADB</string> - <string name="gate_other_no_toggle">मैनुअल एड्रेस, कंप्यूटर ADB, डेवलपर विकल्प</string> <string name="gate_use_wireless_instead">इसके बदले वायरलेस डीबगिंग इस्तेमाल करें</string> <string name="gate_some_roms">कुछ ROM फिर भी यह स्विच जोड़ देते हैं। डेवलपर विकल्प में “child process” देखें।</string> - <string name="gate_manual_hint">अगर नोटिफ़िकेशन काम न करे, तो पॉप-अप का एड्रेस और कोड खुद डालें।</string> - <string name="gate_enter_manually">एड्रेस खुद डालें</string> <string name="gate_from_computer">ADB वाले कंप्यूटर से:</string> <string name="gate_copy_command">कमांड कॉपी करें</string> <string name="gate_sidequest_steps">हेडसेट को कंप्यूटर से जोड़ें और SideQuest खोलें। “Run ADB Command”, फिर “Custom Command” चुनें, नीचे दिखाया गया कमांड टाइप करें और “Run Command” चुनें।</string> <string name="gate_choose_display">Android Settings किस डिस्प्ले पर खोलना है चुनें।</string> <string name="gate_main_screen">मुख्य स्क्रीन</string> - <string name="wadb_finding_port">पेयर हो गया। वायरलेस डीबगिंग का पोर्ट खोजा जा रहा है…</string> - <string name="wadb_enter_port">पेयर हो गया। Settings से पोर्ट डालें।</string> - <string name="wadb_applying">डिवाइस मिल गया। सेटिंग लागू की जा रही है…</string> - <string name="wadb_apply_failed">खुद लागू नहीं हो सका। नीचे दिया एड्रेस जांचें और फिर कोशिश करें। %1$s</string> - <string name="wadb_title_wireless">वायरलेस डीबगिंग</string> - <string name="wadb_title_done">चाइल्ड-प्रोसेस सीमा अपडेट हुई</string> - <string name="wadb_title">चाइल्ड-प्रोसेस सीमा बदलें</string> - <string name="wadb_lede_compact0">अगर यह विकल्प न हो, तो वायरलेस डीबगिंग से पेयर करें।</string> - <string name="wadb_lede_compact1">पेयर हो गया। वायरलेस डीबगिंग में IP एड्रेस और पोर्ट जांचें।</string> - <string name="wadb_lede_done">चाइल्ड-प्रोसेस सीमा अपडेट हो गई।</string> - <string name="wadb_lede0">अगर डेवलपर विकल्प में चाइल्ड-प्रोसेस सेटिंग न हो तो स्टेप 2 इस्तेमाल करें। डेवलपर विकल्प → वायरलेस डीबगिंग → Pair device with pairing code खोलें।</string> - <string name="wadb_lede1">पेयर हो गया। नीचे दिया एड्रेस इस्तेमाल करें, या इसे वायरलेस डीबगिंग → IP address & Port से अपडेट करें।</string> - <string name="wadb_lede_done_long">चाइल्ड-प्रोसेस सीमा वायरलेस डीबगिंग के ज़रिए अपडेट हो गई।</string> - <string name="wadb_confirmed_on">Android ने पुष्टि की कि सीमा चालू है।</string> - <string name="wadb_confirmed_off">Android ने पुष्टि की कि सीमा बंद है।</string> - <string name="wadb_pair_group">2 · वायरलेस डीबगिंग पेयर करें</string> - <string name="wadb_pair_address">पेयरिंग पॉप-अप का IP एड्रेस और पोर्ट</string> - <string name="wadb_pin">पेयरिंग कोड (PIN)</string> - <string name="wadb_pin_placeholder">6 अंक</string> - <string name="wadb_pair">पेयर करें</string> - <string name="wadb_apply_group">2 · वायरलेस डीबगिंग के ज़रिए लागू करें</string> - <string name="wadb_connect_address">कनेक्शन का IP एड्रेस और पोर्ट</string> - <string name="wadb_pair_again">फिर से पेयर करें</string> - <string name="wadb_turn_off">सीमा बंद करें</string> - <string name="wadb_other_ways">इसे बदलने के अन्य तरीके</string> - <string name="wadb_dev_try_first">1 · डेवलपर विकल्प (पहले आज़माएं)</string> - <string name="wadb_restrict_on">“चाइल्ड प्रोसेस से जुड़ी पाबंदियां हटाएं” बंद करें।</string> - <string name="wadb_restrict_off">“चाइल्ड प्रोसेस से जुड़ी पाबंदियां हटाएं” चालू करें।</string> - <string name="wadb_computer_last">3 · कंप्यूटर ADB (आख़िरी विकल्प)</string> - <string name="wadb_only_if">सिर्फ़ तब जब वायरलेस डीबगिंग उपलब्ध न हो।</string> - <string name="wadb_computer_group">3 · कंप्यूटर ADB (आख़िरी विकल्प)</string> <string name="ctrl_color">रंग</string> <string name="ctrl_custom">कस्टम</string> <string name="ctrl_opacity">ओपैसिटी</string> @@ -1627,8 +1586,6 @@ <item quantity="one">%1$d सेशन लॉग फ़ोल्डर हटाया गया।</item> <item quantity="other">%1$d सेशन लॉग फ़ोल्डर हटाए गए।</item> </plurals> - <string name="main_wadb_pair_failed">वायरलेस डीबगिंग पेयरिंग विफल रही</string> - <string name="main_wadb_command_failed">वायरलेस डीबगिंग कमांड विफल रहा</string> <string name="main_wadb_unavailable">वायरलेस डीबगिंग उपलब्ध नहीं है</string> <string name="main_adb_copied">ADB कमांड कॉपी हो गया</string> <string name="main_pick_roms">ROM फ़ोल्डर चुनें</string> @@ -2461,10 +2418,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s। %2$s\n\n%3$s</string> <string name="display_session">सेशन डिस्प्ले</string> - <string name="display_resolution">रिज़ॉल्यूशन</string> + <string name="display_zero_copy">बिना कॉपी प्रस्तुति</string> + <string name="display_resolution_landscape">लैंडस्केप रेज़ोल्यूशन</string> + <string name="display_resolution_portrait">पोर्ट्रेट रेज़ोल्यूशन</string> + <string name="display_follow_landscape">लैंडस्केप जैसा (%1$d×%2$d)</string> + <string name="display_follow_portrait">पोर्ट्रेट जैसा (%1$d×%2$d)</string> <string name="display_game_fit">16:9 गेम फ़िट</string> <string name="display_game_fit_hint">16:9 गेम इस डिस्प्ले में कैसे फ़िट होते हैं। अगले सेशन से।</string> <string name="display_game_fit_unavailable">Match screen चुनें या 16:9 से पतला कस्टम आकार चुनें।</string> + <string name="display_avoid_notch">नॉच से बचें</string> + <string name="display_avoid_notch_hint">तस्वीर को कैमरा कटआउट से दूर रखता है। सेशन में लौटने पर लागू होता है।</string> <string name="display_preserve">अनुपात बनाए रखें</string> <string name="display_stretch">डिस्प्ले में स्ट्रेच करें</string> <string name="display_image_scaling">इमेज स्केलिंग</string> @@ -2751,6 +2714,7 @@ <string name="stores_login_error_ssl">साइन-इन पेज से कनेक्शन सुरक्षित नहीं है।</string> <string name="stores_login_error_verification">साइन-इन सत्यापित नहीं हो सका। फिर कोशिश करें।</string> <string name="stores_login_error_generic">साइन-इन विफल रहा। फिर कोशिश करें।</string> + <string name="stores_login_continue_in_browser">%1$s को एक और चरण चाहिए। खुले हुए ब्राउज़र में इसे पूरा करें, फिर दोबारा कोशिश करें।</string> <string name="common_close">बंद करें</string> <string name="common_back">बैक</string> <string name="common_edit">संपादित करें</string> @@ -3135,7 +3099,7 @@ <string name="hand_camera_done">हो गया</string> <string name="glasses_xreal_network_missing">चश्मे के USB Ethernet कनेक्शन का इंतज़ार है। हो सकता है यह फ़ोन इसे ऐप्स को उपलब्ध न कराए।</string> <string name="glasses_xreal_connection_failed">XREAL कनेक्शन टूट गया या उसने ऐसा जवाब दिया जो समर्थित नहीं है। फिर से कोशिश हो रही है…</string> - <string name="glasses_xreal_experimental">1S के लिए प्रायोगिक सपोर्ट। चश्मे के मेनू में Follow मोड चुनें और स्टेबिलाइज़ेशन बंद करें। ट्रैकिंग की दिशाएं और डिस्प्ले मोड अभी डिवाइस पर टेस्ट होने बाकी हैं।</string> + <string name="glasses_xreal_experimental">XREAL 1S, One, One Pro, One Pro+ और Aura के लिए प्रायोगिक सपोर्ट। चश्मे के मेनू में Follow मोड चुनें और स्टेबिलाइज़ेशन बंद करें; Aura पर Spatial Anchor भी बंद करें। Aura और One Pro+ पर हेड ट्रैकिंग और 2D/3D स्विचिंग का परीक्षण किया गया है।</string> <string name="glasses_pro2_experimental">Pro 2 के लिए प्रायोगिक हेड ट्रैकिंग। चमक और वॉल्यूम बदलना और डिस्प्ले मोड स्विच करना अभी समर्थित नहीं है।</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard मोड</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">सबसे ज़्यादा डाउनलोड</string> <string name="addons_category_all">सभी श्रेणियाँ</string> <string name="addons_none_found">कोई ऐडऑन नहीं मिला</string> + <string name="addons_curse_busy">पहले CurseForge बंद करें</string> <string name="addons_unreachable">%1$s तक नहीं पहुँच सके</string> <string name="addons_no_file">गेम के इस संस्करण के लिए कोई फ़ाइल नहीं है</string> <string name="input_reset_positions">स्थितियाँ रीसेट करें</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">हाइलाइट</string> <string name="theme_custom_good">सफलता</string> <string name="theme_custom_error">त्रुटि</string> + <string name="hud_only_during_game">HUD केवल गेम के दौरान दिखाएँ</string> + <string name="hud_only_during_game_hint">गेम के फ़्रेम का पता न चलने पर HUD छिपाएँ।</string> </resources> diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 4f7ad2c7c6..8c51e3cf8a 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-kimenet</string> <string name="mode_hdr_unavailable">Nem elérhető: %1$s.</string> - <string name="mode_hdr_restart">Indítsa újra az alkalmazást az érvényesítéshez.</string> <string name="mode_drivers">Illesztőprogramok</string> <string name="mode_gpu_drivers">GPU-illesztőprogramok</string> <string name="mode_gpu_drivers_hint">A Steam és az Asztal közösen használja. Az Összetevők oldalon állítható be.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Indítás</string> <string name="mode_startup_session">Megnyitás indításkor</string> <string name="mode_startup_session_hint">A DroidDeck indulásakor elindítja ezt a munkamenetet.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Kiadások keresése…</string> <string name="mode_decky_ready">Készen áll a %1$s telepítésére.</string> <string name="mode_decky_none">Nem található kompatibilis build. Próbálja újra később.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Naprakész · %1$s</string> <string name="mode_decky_loader">Betöltő</string> <string name="mode_decky_install_latest">Legújabb telepítése</string> - <string name="decky_channel">Frissítési csatorna</string> - <string name="decky_channel_hint">Mely Decky Loader-kiadások települjenek. A Decky saját frissítője ugyanezt a csatornát használja.</string> <string name="decky_channel_stable">Stabil</string> <string name="decky_channel_prerelease">Előzetes kiadás</string> <string name="decky_channel_testing">Tesztelés</string> <string name="decky_channel_failed">Nem sikerült menteni a Decky frissítési csatornáját</string> - <string name="mode_decky_on">A Steammel együtt indul. Amíg be van kapcsolva, az eszközön lévő más alkalmazások is irányíthatják a Steamet.</string> - <string name="mode_decky_off">Ki. A Steam távoli hibakeresési portja zárva marad.</string> <string name="mode_decky_remove_title">Eltávolítja a Decky Loadert?</string> <string name="mode_decky_remove_text">Eltávolítja a betöltőt. A bővítményei és beállításai megmaradnak.</string> <string name="mode_client">Kliens</string> @@ -953,13 +947,15 @@ <string name="setup_launcher_orientation_auto">Az eszköz elforgatásának követése</string> <string name="setup_orientation_portrait">Álló</string> <string name="setup_session_orientation">Munkamenet tájolása</string> - <string name="setup_session_orientation_hint">A Steamre, a játékokra, az asztalra és a kontrollerszerkesztőre vonatkozik. A felbontás-előbeállítások a munkamenettel együtt forognak; az egyéni szélesség és magasság a megadott módon marad.</string> + <string name="setup_session_orientation_hint">A Steamre, a játékokra, az asztalra és a kontrollerszerkesztőre vonatkozik. A felbontás-előbeállítások a munkamenettel együtt forognak; ha az egyik tájolás a másikat követi, az egyéni szélesség és magasság felcserélődik.</string> <string name="setup_orientation_auto">Automatikus fekvő</string> <string name="setup_orientation_landscape">Fekvő</string> <string name="setup_orientation_reverse">Fordított fekvő</string> <string name="setup_fullscreen">Teljes képernyő</string> <string name="setup_fullscreen_on">Elrejti az Android állapot- és navigációs sávokat</string> <string name="setup_fullscreen_off">Megjeleníti az Android állapot- és navigációs sávokat</string> + <string name="setup_page_swipe">Lapozás csúsztatással</string> + <string name="setup_page_swipe_hint">Csúsztasson végig egy oldalon a lapváltáshoz.</string> <string name="setup_dual_screen_launcher">Kétképernyős indító</string> <string name="setup_dual_screen_launcher_hint">Az Automatikus mód a beépített második képernyővel rendelkező kézi eszközökön a második képernyőre helyezi az indító szakaszait (Steam, Könyvtár, Áruházak és a többi). A Be mód bármely második kijelzőt használ. A Ki mód egy képernyőn tartja az indítót.</string> <string name="setup_dual_screen_sessions">Kétképernyős munkamenetek</string> @@ -1280,8 +1276,6 @@ <string name="gate_open_dev">Fejlesztői beállítások megnyitása</string> <string name="gate_no_toggle">Ehhez az Android-verzióhoz nincs kapcsoló, ezért a DroidDeck a vezeték nélküli hibakeresésen keresztül módosítja. Körülbelül egy percet vesz igénybe, számítógép nélkül.</string> <string name="gate_needs_wifi">A vezeték nélküli hibakereséshez Wi-Fi szükséges. Bármelyik hálózat megfelel; internetkapcsolat nem szükséges.</string> - <string name="gate_needs_notifications">A párosítási kód egy értesítésben jelenik meg. Engedélyezze az értesítéseket a DroidDecknek, vagy használja az Egyéb módokat.</string> - <string name="gate_allow_notifications">Értesítések engedélyezése</string> <string name="gate_step1">Nyissa meg: Beállítások → Fejlesztői beállítások → Vezeték nélküli hibakeresés, és kapcsolja be</string> <string name="gate_step2">Koppintson az „Eszköz párosítása párosítási kóddal” lehetőségre</string> <string name="gate_step3">Írja be a kódot a DroidDeck értesítésébe</string> @@ -1298,48 +1292,13 @@ <string name="gate_status">Állapot</string> <string name="gate_polling">Ellenőrzés 2 másodpercenként. Ez az oldal bezárul, amikor kikapcsol.</string> <string name="gate_other_ways">Egyéb módok</string> - <string name="gate_other_toggle">Vezeték nélküli hibakeresés, manuális cím, számítógépes ADB</string> - <string name="gate_other_no_toggle">Manuális cím, számítógépes ADB, Fejlesztői beállítások</string> <string name="gate_use_wireless_instead">Vezeték nélküli hibakeresés használata helyette</string> <string name="gate_some_roms">Néhány ROM mindenképpen hozzáadja a kapcsolót. Keresse a „gyermekfolyamat” kifejezést a Fejlesztői beállításokban.</string> - <string name="gate_manual_hint">Ha az értesítés nem működik, írja be saját kezűleg a felugró ablak címét és kódját.</string> - <string name="gate_enter_manually">Cím kézi megadása</string> <string name="gate_from_computer">Egy ADB-vel rendelkező számítógépről:</string> <string name="gate_copy_command">Parancs másolása</string> <string name="gate_sidequest_steps">Csatlakoztasd a headsetet egy számítógéphez, és nyisd meg a SideQuestet. Válaszd a „Run ADB Command”, majd a „Custom Command” lehetőséget, írd be az alább látható parancsot, és válaszd a „Run Command” gombot.</string> <string name="gate_choose_display">Válassza ki, melyik kijelzőn nyíljon meg az Android Beállítások.</string> <string name="gate_main_screen">Fő képernyő</string> - <string name="wadb_finding_port">Párosítva. A vezeték nélküli hibakeresés portjának keresése…</string> - <string name="wadb_enter_port">Párosítva. Adja meg a portot a Beállításokból.</string> - <string name="wadb_applying">Eszköz megtalálva. A beállítás alkalmazása…</string> - <string name="wadb_apply_failed">Nem sikerült automatikusan alkalmazni. Ellenőrizze az alábbi címet, és próbálja újra. %1$s</string> - <string name="wadb_title_wireless">Vezeték nélküli hibakeresés</string> - <string name="wadb_title_done">A gyermekfolyamat-korlát frissítve</string> - <string name="wadb_title">A gyermekfolyamat-korlát módosítása</string> - <string name="wadb_lede_compact0">Ha a beállítás hiányzik, párosítson a vezeték nélküli hibakeresésen keresztül.</string> - <string name="wadb_lede_compact1">Párosítva. Ellenőrizze az IP-címet és a portot a vezeték nélküli hibakeresésben.</string> - <string name="wadb_lede_done">A gyermekfolyamat-korlát frissítve.</string> - <string name="wadb_lede0">Használja a 2. lépést, ha a Fejlesztői beállításokban nincs gyermekfolyamat-beállítás. Nyissa meg: Fejlesztői beállítások → Vezeték nélküli hibakeresés → Eszköz párosítása párosítási kóddal.</string> - <string name="wadb_lede1">Párosítva. Használja az alábbi címet, vagy frissítse a Vezeték nélküli hibakeresés → IP-cím és port menüből.</string> - <string name="wadb_lede_done_long">A gyermekfolyamat-korlát frissítve a vezeték nélküli hibakeresésen keresztül.</string> - <string name="wadb_confirmed_on">Az Android megerősítette, hogy a korlát be van kapcsolva.</string> - <string name="wadb_confirmed_off">Az Android megerősítette, hogy a korlát ki van kapcsolva.</string> - <string name="wadb_pair_group">2 · Vezeték nélküli hibakeresés párosítása</string> - <string name="wadb_pair_address">A párosítási felugró ablak IP-címe és portja</string> - <string name="wadb_pin">Párosítási kód (PIN)</string> - <string name="wadb_pin_placeholder">6 számjegy</string> - <string name="wadb_pair">Párosítás</string> - <string name="wadb_apply_group">2 · Alkalmazás vezeték nélküli hibakeresésen keresztül</string> - <string name="wadb_connect_address">Kapcsolat IP-címe és portja</string> - <string name="wadb_pair_again">Párosítás újra</string> - <string name="wadb_turn_off">Korlát kikapcsolása</string> - <string name="wadb_other_ways">Egyéb módok a módosítására</string> - <string name="wadb_dev_try_first">1 · Fejlesztői beállítások (próbálja ezt először)</string> - <string name="wadb_restrict_on">Kapcsolja ki az „Alárendelt folyamatok korlátozásának kikapcsolása” lehetőséget.</string> - <string name="wadb_restrict_off">Kapcsolja be az „Alárendelt folyamatok korlátozásának kikapcsolása” lehetőséget.</string> - <string name="wadb_computer_last">3 · Számítógépes ADB (végső megoldás)</string> - <string name="wadb_only_if">Csak ha a vezeték nélküli hibakeresés nem elérhető.</string> - <string name="wadb_computer_group">3 · Számítógépes ADB (végső megoldás)</string> <string name="ctrl_color">Szín</string> <string name="ctrl_custom">Egyéni</string> <string name="ctrl_opacity">Átlátszatlanság</string> @@ -1627,8 +1586,6 @@ <item quantity="one">%1$d munkamenet-naplómappa törölve.</item> <item quantity="other">%1$d munkamenet-naplómappa törölve.</item> </plurals> - <string name="main_wadb_pair_failed">A vezeték nélküli hibakeresés párosítása sikertelen</string> - <string name="main_wadb_command_failed">A vezeték nélküli hibakeresés parancsa sikertelen</string> <string name="main_wadb_unavailable">A vezeték nélküli hibakeresés nem áll rendelkezésre</string> <string name="main_adb_copied">ADB-parancs másolva</string> <string name="main_pick_roms">ROMs mappa kiválasztása</string> @@ -2461,10 +2418,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Munkamenet kijelzője</string> - <string name="display_resolution">Felbontás</string> + <string name="display_zero_copy">Másolásmentes megjelenítés</string> + <string name="display_resolution_landscape">Fekvő felbontás</string> + <string name="display_resolution_portrait">Álló felbontás</string> + <string name="display_follow_landscape">Mint a fekvő (%1$d×%2$d)</string> + <string name="display_follow_portrait">Mint az álló (%1$d×%2$d)</string> <string name="display_game_fit">16:9 játék illesztése</string> <string name="display_game_fit_hint">Hogyan illeszkednek a 16:9 játékok ehhez a kijelzőhöz. A következő munkamenettől.</string> <string name="display_game_fit_unavailable">Válassza a Képernyőhöz illesztést, vagy egy 16:9-nél szűkebb egyéni méretet.</string> + <string name="display_avoid_notch">Kamera-kivágás kerülése</string> + <string name="display_avoid_notch_hint">A képet távol tartja a kameralyuktól. A munkamenetbe való visszatéréskor lép életbe.</string> <string name="display_preserve">Arányok megtartása</string> <string name="display_stretch">Nyújtás a kijelzőhöz</string> <string name="display_image_scaling">Képméretezés</string> @@ -2751,6 +2714,7 @@ <string name="stores_login_error_ssl">A kapcsolat a bejelentkezési oldalhoz nem biztonságos.</string> <string name="stores_login_error_verification">A bejelentkezést nem sikerült ellenőrizni. Próbálja újra.</string> <string name="stores_login_error_generic">A bejelentkezés sikertelen. Próbálja újra.</string> + <string name="stores_login_continue_in_browser">A(z) %1$s még egy lépést kér. Fejezze be a megnyílt böngészőben, majd próbálja újra.</string> <string name="common_close">Bezárás</string> <string name="common_back">Vissza</string> <string name="common_edit">Szerkesztés</string> @@ -3135,7 +3099,7 @@ <string name="hand_camera_done">Kész</string> <string name="glasses_xreal_network_missing">Várakozás a szemüveg USB-s Ethernet-kapcsolatára. Lehet, hogy ez a telefon nem teszi elérhetővé az alkalmazások számára.</string> <string name="glasses_xreal_connection_failed">Az XREAL-kapcsolat megszakadt, vagy nem támogatott választ adott. Újrapróbálkozás…</string> - <string name="glasses_xreal_experimental">Kísérleti 1S-támogatás. Használja a Follow módot, és kapcsolja ki a stabilizálást a szemüveg menüjében. A követési irányokat és a megjelenítési módokat még tesztelni kell az eszközön.</string> + <string name="glasses_xreal_experimental">Az XREAL 1S, One, One Pro, One Pro+ és Aura kísérleti támogatása. Használja a Follow módot, és kapcsolja ki a stabilizálást a szemüveg menüjében; az Aura esetén a Spatial Anchor funkciót is kapcsolja ki. A fejkövetést és a 2D/3D-váltást az Aura és a One Pro+ modelleken teszteltük.</string> <string name="glasses_pro2_experimental">Kísérleti fejkövetés a Pro 2-höz. A fényerő és a hangerő beállítása, valamint a megjelenítési mód váltása még nem támogatott.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard mód</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">Legtöbbet letöltött</string> <string name="addons_category_all">Minden kategória</string> <string name="addons_none_found">Nem található kiegészítő</string> + <string name="addons_curse_busy">Előbb zárd be a CurseForge-ot</string> <string name="addons_unreachable">A(z) %1$s nem érhető el</string> <string name="addons_no_file">Nincs fájl ehhez a játékverzióhoz</string> <string name="input_reset_positions">Pozíciók visszaállítása</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">Kiemelések</string> <string name="theme_custom_good">Siker</string> <string name="theme_custom_error">Hiba</string> + <string name="hud_only_during_game">HUD megjelenítése csak játék közben</string> + <string name="hud_only_during_game_hint">HUD elrejtése, ha nem észlelhetők játék képkockái.</string> </resources> diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 4ea3788f5f..d067290684 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Output HDR10</string> <string name="mode_hdr_unavailable">Tidak tersedia: %1$s.</string> - <string name="mode_hdr_restart">Mulai ulang aplikasi untuk menerapkannya.</string> <string name="mode_drivers">Driver</string> <string name="mode_gpu_drivers">Driver GPU</string> <string name="mode_gpu_drivers_hint">Digunakan bersama oleh Steam dan Desktop. Diatur di halaman Komponen.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Mulai</string> <string name="mode_startup_session">Buka saat peluncuran</string> <string name="mode_startup_session_hint">Memulai sesi ini saat DroidDeck diluncurkan.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Memeriksa rilis…</string> <string name="mode_decky_ready">Siap menginstal %1$s.</string> <string name="mode_decky_none">Tidak ditemukan build yang kompatibel. Coba lagi nanti.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Terbaru · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Instal versi terbaru</string> - <string name="decky_channel">Saluran Pembaruan</string> - <string name="decky_channel_hint">Rilis Decky Loader mana yang akan diinstal. Pembaru bawaan Decky menggunakan saluran yang sama.</string> <string name="decky_channel_stable">Stabil</string> <string name="decky_channel_prerelease">Prarilis</string> <string name="decky_channel_testing">Pengujian</string> <string name="decky_channel_failed">Tidak dapat menyimpan saluran pembaruan Decky</string> - <string name="mode_decky_on">Dimulai bersama Steam. Saat aktif, aplikasi lain di perangkat ini mungkin dapat mengendalikan Steam.</string> - <string name="mode_decky_off">Nonaktif. Port debugging jarak jauh Steam tetap tertutup.</string> <string name="mode_decky_remove_title">Hapus instalasi Decky Loader?</string> <string name="mode_decky_remove_text">Menghapus loader. Plugin dan setelan Anda tetap disimpan.</string> <string name="mode_client">Klien</string> @@ -950,13 +944,15 @@ <string name="setup_launcher_orientation_auto">Ikuti rotasi perangkat</string> <string name="setup_orientation_portrait">Potret</string> <string name="setup_session_orientation">Orientasi sesi</string> - <string name="setup_session_orientation_hint">Berlaku untuk Steam, gim, desktop, dan editor pengontrol. Preset resolusi ikut berputar dengan sesi; lebar dan tinggi kustom tetap seperti yang dimasukkan.</string> + <string name="setup_session_orientation_hint">Berlaku untuk Steam, gim, desktop, dan editor pengontrol. Preset resolusi ikut berputar dengan sesi; saat satu orientasi mengikuti yang lain, lebar dan tinggi kustom ditukar agar sesuai.</string> <string name="setup_orientation_auto">Lanskap otomatis</string> <string name="setup_orientation_landscape">Lanskap</string> <string name="setup_orientation_reverse">Lanskap terbalik</string> <string name="setup_fullscreen">Layar penuh</string> <string name="setup_fullscreen_on">Menyembunyikan bilah status dan navigasi Android</string> <string name="setup_fullscreen_off">Menampilkan bilah status dan navigasi Android</string> + <string name="setup_page_swipe">Geser antarhalaman</string> + <string name="setup_page_swipe_hint">Geser melintasi halaman untuk berganti tab.</string> <string name="setup_dual_screen_launcher">Peluncur layar ganda</string> <string name="setup_dual_screen_launcher_hint">Otomatis menempatkan bagian peluncur (Steam, Pustaka, Toko, dan bagian lainnya) pada layar kedua bawaan perangkat genggam. Aktif memakai layar kedua mana pun. Nonaktif membuat peluncur tetap di satu layar saja.</string> <string name="setup_dual_screen_sessions">Sesi layar ganda</string> @@ -1274,8 +1270,6 @@ <string name="gate_open_dev">Buka Opsi pengembang</string> <string name="gate_no_toggle">Versi Android ini tidak memiliki sakelar untuk itu, sehingga DroidDeck mengubahnya melalui Debugging nirkabel. Membutuhkan waktu sekitar satu menit, tanpa komputer.</string> <string name="gate_needs_wifi">Debugging nirkabel memerlukan Wi-Fi. Jaringan apa pun berfungsi; tidak perlu internet.</string> - <string name="gate_needs_notifications">Kode pemasangan muncul di notifikasi. Izinkan notifikasi untuk DroidDeck, atau gunakan Cara lain.</string> - <string name="gate_allow_notifications">Izinkan notifikasi</string> <string name="gate_step1">Buka Setelan → Opsi pengembang → Debugging nirkabel dan aktifkan</string> <string name="gate_step2">Ketuk “Pasangkan perangkat dengan kode pemasangan”</string> <string name="gate_step3">Masukkan kode ke notifikasi DroidDeck</string> @@ -1292,48 +1286,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Memeriksa setiap 2 detik. Halaman ini akan tertutup saat statusnya nonaktif.</string> <string name="gate_other_ways">Cara lain</string> - <string name="gate_other_toggle">Debugging nirkabel, alamat manual, ADB komputer</string> - <string name="gate_other_no_toggle">Alamat manual, ADB komputer, Opsi pengembang</string> <string name="gate_use_wireless_instead">Gunakan Debugging nirkabel sebagai gantinya</string> <string name="gate_some_roms">Beberapa ROM menambahkan sakelar ini juga. Cari “child process” di Opsi pengembang.</string> - <string name="gate_manual_hint">Jika notifikasinya tidak berfungsi, masukkan sendiri alamat dan kode dari jendela pemasangan.</string> - <string name="gate_enter_manually">Masukkan alamat secara manual</string> <string name="gate_from_computer">Dari komputer dengan ADB:</string> <string name="gate_copy_command">Salin perintah</string> <string name="gate_sidequest_steps">Hubungkan headset ke komputer dan buka SideQuest. Pilih “Run ADB Command”, lalu “Custom Command”, ketik perintah yang ditampilkan di bawah, dan pilih “Run Command”.</string> <string name="gate_choose_display">Pilih tampilan tempat membuka Setelan Android.</string> <string name="gate_main_screen">Layar utama</string> - <string name="wadb_finding_port">Berhasil dipasangkan. Mencari port Debugging nirkabel…</string> - <string name="wadb_enter_port">Berhasil dipasangkan. Masukkan port dari Setelan.</string> - <string name="wadb_applying">Perangkat ditemukan. Menerapkan setelan…</string> - <string name="wadb_apply_failed">Tidak dapat menerapkan secara otomatis. Periksa alamat di bawah dan coba lagi. %1$s</string> - <string name="wadb_title_wireless">Debugging nirkabel</string> - <string name="wadb_title_done">Batas proses turunan diperbarui</string> - <string name="wadb_title">Ubah batas proses turunan</string> - <string name="wadb_lede_compact0">Jika opsinya tidak ada, pasangkan melalui Debugging nirkabel.</string> - <string name="wadb_lede_compact1">Berhasil dipasangkan. Periksa alamat IP dan port di Debugging nirkabel.</string> - <string name="wadb_lede_done">Batas proses turunan telah diperbarui.</string> - <string name="wadb_lede0">Gunakan langkah 2 jika Opsi pengembang tidak memiliki setelan proses turunan. Buka Opsi pengembang → Debugging nirkabel → Pasangkan perangkat dengan kode pemasangan.</string> - <string name="wadb_lede1">Berhasil dipasangkan. Gunakan alamat di bawah, atau perbarui dari Debugging nirkabel → Alamat IP & Port.</string> - <string name="wadb_lede_done_long">Batas proses turunan telah diperbarui melalui Debugging nirkabel.</string> - <string name="wadb_confirmed_on">Android mengonfirmasi batas ini aktif.</string> - <string name="wadb_confirmed_off">Android mengonfirmasi batas ini nonaktif.</string> - <string name="wadb_pair_group">2 · Pasangkan Debugging nirkabel</string> - <string name="wadb_pair_address">Alamat IP & port jendela pemasangan</string> - <string name="wadb_pin">Kode pemasangan (PIN)</string> - <string name="wadb_pin_placeholder">6 digit</string> - <string name="wadb_pair">Pasangkan</string> - <string name="wadb_apply_group">2 · Terapkan melalui Debugging nirkabel</string> - <string name="wadb_connect_address">Alamat IP & port koneksi</string> - <string name="wadb_pair_again">Pasangkan lagi</string> - <string name="wadb_turn_off">Nonaktifkan batas</string> - <string name="wadb_other_ways">Cara lain untuk mengubahnya</string> - <string name="wadb_dev_try_first">1 · Opsi pengembang (coba dahulu)</string> - <string name="wadb_restrict_on">Nonaktifkan “Nonaktifkan batasan proses turunan”.</string> - <string name="wadb_restrict_off">Aktifkan “Nonaktifkan batasan proses turunan”.</string> - <string name="wadb_computer_last">3 · ADB komputer (upaya terakhir)</string> - <string name="wadb_only_if">Hanya jika Debugging nirkabel tidak tersedia.</string> - <string name="wadb_computer_group">3 · ADB komputer (upaya terakhir)</string> <string name="ctrl_color">Warna</string> <string name="ctrl_custom">Khusus</string> <string name="ctrl_opacity">Opasitas</string> @@ -1615,8 +1574,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">%1$d folder log sesi dihapus.</item> </plurals> - <string name="main_wadb_pair_failed">Penyambungan debugging nirkabel gagal</string> - <string name="main_wadb_command_failed">Perintah debugging nirkabel gagal</string> <string name="main_wadb_unavailable">Debugging nirkabel tidak tersedia</string> <string name="main_adb_copied">Perintah ADB disalin</string> <string name="main_pick_roms">Pilih folder ROMs</string> @@ -2436,10 +2393,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Tampilan sesi</string> - <string name="display_resolution">Resolusi</string> + <string name="display_zero_copy">Presentasi tanpa salin</string> + <string name="display_resolution_landscape">Resolusi lanskap</string> + <string name="display_resolution_portrait">Resolusi potret</string> + <string name="display_follow_landscape">Ikuti lanskap (%1$d×%2$d)</string> + <string name="display_follow_portrait">Ikuti potret (%1$d×%2$d)</string> <string name="display_game_fit">Penyesuaian gim 16:9</string> <string name="display_game_fit_hint">Cara gim 16:9 disesuaikan dengan tampilan ini. Berlaku pada sesi berikutnya.</string> <string name="display_game_fit_unavailable">Pilih Sesuaikan layar atau ukuran khusus yang lebih sempit dari 16:9.</string> + <string name="display_avoid_notch">Hindari poni</string> + <string name="display_avoid_notch_hint">Menjauhkan gambar dari lubang kamera. Berlaku saat Anda kembali ke sesi.</string> <string name="display_preserve">Pertahankan proporsi</string> <string name="display_stretch">Bentangkan ke tampilan</string> <string name="display_image_scaling">Penskalaan gambar</string> @@ -2726,6 +2689,7 @@ <string name="stores_login_error_ssl">Koneksi ke halaman masuk tidak aman.</string> <string name="stores_login_error_verification">Proses masuk tidak dapat diverifikasi. Coba lagi.</string> <string name="stores_login_error_generic">Proses masuk gagal. Coba lagi.</string> + <string name="stores_login_continue_in_browser">%1$s memerlukan satu langkah lagi. Selesaikan di browser yang terbuka, lalu coba lagi.</string> <string name="common_close">Tutup</string> <string name="common_back">Kembali</string> <string name="common_edit">Edit</string> @@ -3106,7 +3070,7 @@ <string name="hand_camera_done">Selesai</string> <string name="glasses_xreal_network_missing">Menunggu koneksi Ethernet USB dari kacamata. Ponsel ini mungkin tidak menyediakannya untuk aplikasi.</string> <string name="glasses_xreal_connection_failed">Koneksi XREAL terputus atau memberikan respons yang tidak didukung. Mencoba lagi…</string> - <string name="glasses_xreal_experimental">Dukungan 1S eksperimental. Gunakan mode Follow dan nonaktifkan stabilisasi di menu kacamata. Arah pelacakan dan mode tampilan masih perlu diuji di perangkat.</string> + <string name="glasses_xreal_experimental">Dukungan eksperimental untuk XREAL 1S, One, One Pro, One Pro+, dan Aura. Gunakan mode Follow dan nonaktifkan stabilisasi di menu kacamata; pada Aura, nonaktifkan juga Spatial Anchor. Pelacakan kepala dan peralihan 2D/3D telah diuji pada Aura dan One Pro+.</string> <string name="glasses_pro2_experimental">Pelacakan kepala Pro 2 eksperimental. Pengaturan kecerahan, volume, dan pergantian mode tampilan belum didukung.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Mode Cardboard</string> @@ -3980,6 +3944,7 @@ <string name="addons_sort_downloads">Paling banyak diunduh</string> <string name="addons_category_all">Semua kategori</string> <string name="addons_none_found">Tidak ada addon ditemukan</string> + <string name="addons_curse_busy">Tutup CurseForge terlebih dahulu</string> <string name="addons_unreachable">Tidak dapat menjangkau %1$s</string> <string name="addons_no_file">Tidak ada file untuk versi game ini</string> <string name="input_reset_positions">Atur ulang posisi</string> @@ -4083,4 +4048,6 @@ <string name="theme_custom_signal">Sorotan</string> <string name="theme_custom_good">Berhasil</string> <string name="theme_custom_error">Kesalahan</string> + <string name="hud_only_during_game">Tampilkan HUD hanya saat bermain</string> + <string name="hud_only_during_game_hint">Sembunyikan HUD saat tidak ada frame game yang terdeteksi.</string> </resources> diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 4e7fdf08d1..2dfa1da981 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Uscita HDR10</string> <string name="mode_hdr_unavailable">Non disponibile: %1$s.</string> - <string name="mode_hdr_restart">Riavvia l\'app per applicare.</string> <string name="mode_drivers">Driver</string> <string name="mode_gpu_drivers">Driver GPU</string> <string name="mode_gpu_drivers_hint">Condivisi da Steam e Desktop. Si impostano nella pagina Componenti.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Avvio</string> <string name="mode_startup_session">Apri all\'avvio</string> <string name="mode_startup_session_hint">Avvia questa sessione all\'avvio di DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Ricerca di release…</string> <string name="mode_decky_ready">Pronto per installare %1$s.</string> <string name="mode_decky_none">Nessuna build compatibile trovata. Riprova più tardi.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Ultima versione · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Installa l\'ultima versione</string> - <string name="decky_channel">Canale di aggiornamento</string> - <string name="decky_channel_hint">Quali release di Decky Loader installare. Anche l\'aggiornamento integrato di Decky usa lo stesso canale.</string> <string name="decky_channel_stable">Stabile</string> <string name="decky_channel_prerelease">Pre-release</string> <string name="decky_channel_testing">Test</string> <string name="decky_channel_failed">Impossibile salvare il canale di aggiornamento di Decky</string> - <string name="mode_decky_on">Si avvia con Steam. Quando è attivo, altre app su questo dispositivo potrebbero controllare Steam.</string> - <string name="mode_decky_off">Disattivato. La porta di debug remoto di Steam resta chiusa.</string> <string name="mode_decky_remove_title">Disinstallare Decky Loader?</string> <string name="mode_decky_remove_text">Rimuove il loader. I tuoi plugin e le impostazioni vengono mantenuti.</string> <string name="mode_client">Client</string> @@ -948,13 +942,15 @@ <string name="setup_launcher_orientation_auto">Segui la rotazione del dispositivo</string> <string name="setup_orientation_portrait">Verticale</string> <string name="setup_session_orientation">Orientamento della sessione</string> - <string name="setup_session_orientation_hint">Si applica a Steam, ai giochi, al desktop e all\'editor del controller. I preset di risoluzione ruotano con la sessione; larghezza e altezza personalizzate restano come inserite.</string> + <string name="setup_session_orientation_hint">Si applica a Steam, ai giochi, al desktop e all\'editor del controller. I preset di risoluzione ruotano con la sessione; quando un\'orientamento segue l\'altro, larghezza e altezza personalizzate vengono invertite per corrispondere.</string> <string name="setup_orientation_auto">Orizzontale automatico</string> <string name="setup_orientation_landscape">Orizzontale</string> <string name="setup_orientation_reverse">Orizzontale invertito</string> <string name="setup_fullscreen">Schermo intero</string> <string name="setup_fullscreen_on">Nasconde la barra di stato e la barra di navigazione di Android</string> <string name="setup_fullscreen_off">Mostra la barra di stato e la barra di navigazione di Android</string> + <string name="setup_page_swipe">Scorri tra le pagine</string> + <string name="setup_page_swipe_hint">Scorri su una pagina per cambiare scheda.</string> <string name="setup_dual_screen_launcher">Launcher a doppio schermo</string> <string name="setup_dual_screen_launcher_hint">Automatico colloca le sezioni del launcher (Steam, Libreria, Store e le altre) sullo schermo secondario integrato delle console portatili che ne hanno uno. Con Attivo si usa qualsiasi display secondario. Con Disattivo il launcher resta su un solo schermo.</string> <string name="setup_dual_screen_sessions">Sessioni a doppio schermo</string> @@ -1278,8 +1274,6 @@ <string name="gate_open_dev">Apri Opzioni sviluppatore</string> <string name="gate_no_toggle">Questa versione di Android non ha un interruttore per questo, quindi DroidDeck lo cambia tramite il Debug wireless. Richiede circa un minuto, senza bisogno di un computer.</string> <string name="gate_needs_wifi">Il Debug wireless richiede il Wi-Fi. Va bene qualsiasi rete; non serve l\'accesso a internet.</string> - <string name="gate_needs_notifications">Il codice di accoppiamento arriva in una notifica. Consenti le notifiche per DroidDeck, oppure usa Altri modi.</string> - <string name="gate_allow_notifications">Consenti notifiche</string> <string name="gate_step1">Apri Impostazioni → Opzioni sviluppatore → Debug wireless e attivalo</string> <string name="gate_step2">Tocca “Accoppia dispositivo con codice di accoppiamento”</string> <string name="gate_step3">Digita il codice nella notifica di DroidDeck</string> @@ -1296,48 +1290,13 @@ <string name="gate_status">Stato</string> <string name="gate_polling">Controllo ogni 2 secondi. Questa pagina si chiude quando è disattivato.</string> <string name="gate_other_ways">Altri modi</string> - <string name="gate_other_toggle">Debug wireless, indirizzo manuale, ADB da computer</string> - <string name="gate_other_no_toggle">Indirizzo manuale, ADB da computer, Opzioni sviluppatore</string> <string name="gate_use_wireless_instead">Usa invece il Debug wireless</string> <string name="gate_some_roms">Alcune ROM aggiungono comunque l\'interruttore. Cerca “processi figlio” nelle Opzioni sviluppatore.</string> - <string name="gate_manual_hint">Se la notifica non funziona, inserisci tu l\'indirizzo e il codice del popup.</string> - <string name="gate_enter_manually">Inserisci l\'indirizzo manualmente</string> <string name="gate_from_computer">Da un computer con ADB:</string> <string name="gate_copy_command">Copia comando</string> <string name="gate_sidequest_steps">Collega il visore a un computer e apri SideQuest. Scegli “Run ADB Command”, poi “Custom Command”, digita il comando mostrato sotto e seleziona “Run Command”.</string> <string name="gate_choose_display">Scegli su quale schermo aprire le Impostazioni di Android.</string> <string name="gate_main_screen">Schermo principale</string> - <string name="wadb_finding_port">Accoppiato. Ricerca della porta del Debug wireless…</string> - <string name="wadb_enter_port">Accoppiato. Inserisci la porta dalle Impostazioni.</string> - <string name="wadb_applying">Dispositivo trovato. Applicazione dell\'impostazione…</string> - <string name="wadb_apply_failed">Impossibile applicare automaticamente. Controlla l\'indirizzo qui sotto e riprova. %1$s</string> - <string name="wadb_title_wireless">Debug wireless</string> - <string name="wadb_title_done">Limite dei processi figlio aggiornato</string> - <string name="wadb_title">Cambia il limite dei processi figlio</string> - <string name="wadb_lede_compact0">Se l\'opzione non è presente, accoppia tramite il Debug wireless.</string> - <string name="wadb_lede_compact1">Accoppiato. Controlla l\'indirizzo IP e la porta nel Debug wireless.</string> - <string name="wadb_lede_done">Il limite dei processi figlio è stato aggiornato.</string> - <string name="wadb_lede0">Usa il passaggio 2 se le Opzioni sviluppatore non hanno un\'impostazione per i processi figlio. Apri Opzioni sviluppatore → Debug wireless → Accoppia dispositivo con codice di accoppiamento.</string> - <string name="wadb_lede1">Accoppiato. Usa l\'indirizzo qui sotto, oppure aggiornalo da Debug wireless → Indirizzo IP e porta.</string> - <string name="wadb_lede_done_long">Il limite dei processi figlio è stato aggiornato tramite il Debug wireless.</string> - <string name="wadb_confirmed_on">Android ha confermato che il limite è attivo.</string> - <string name="wadb_confirmed_off">Android ha confermato che il limite è disattivato.</string> - <string name="wadb_pair_group">2 · Accoppia il Debug wireless</string> - <string name="wadb_pair_address">Indirizzo IP e porta del popup di accoppiamento</string> - <string name="wadb_pin">Codice di accoppiamento (PIN)</string> - <string name="wadb_pin_placeholder">6 cifre</string> - <string name="wadb_pair">Accoppia</string> - <string name="wadb_apply_group">2 · Applica tramite il Debug wireless</string> - <string name="wadb_connect_address">Indirizzo IP e porta di connessione</string> - <string name="wadb_pair_again">Accoppia di nuovo</string> - <string name="wadb_turn_off">Disattiva il limite</string> - <string name="wadb_other_ways">Altri modi per cambiarlo</string> - <string name="wadb_dev_try_first">1 · Opzioni sviluppatore (da provare prima)</string> - <string name="wadb_restrict_on">Disattiva “Disattiva limitazioni per i processi secondari”.</string> - <string name="wadb_restrict_off">Attiva “Disattiva limitazioni per i processi secondari”.</string> - <string name="wadb_computer_last">3 · ADB da computer (ultima risorsa)</string> - <string name="wadb_only_if">Solo se il Debug wireless non è disponibile.</string> - <string name="wadb_computer_group">3 · ADB da computer (ultima risorsa)</string> <string name="ctrl_color">Colore</string> <string name="ctrl_custom">Personalizzato</string> <string name="ctrl_opacity">Opacità</string> @@ -1631,8 +1590,6 @@ <item quantity="many">%1$d cartelle di log di sessione cancellate.</item> <item quantity="other">%1$d cartelle di log di sessione cancellate.</item> </plurals> - <string name="main_wadb_pair_failed">Accoppiamento per il debug wireless non riuscito</string> - <string name="main_wadb_command_failed">Comando di debug wireless non riuscito</string> <string name="main_wadb_unavailable">Il debug wireless non è disponibile</string> <string name="main_adb_copied">Comando ADB copiato</string> <string name="main_pick_roms">Scegli la cartella delle ROM</string> @@ -2478,10 +2435,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Schermo della sessione</string> - <string name="display_resolution">Risoluzione</string> + <string name="display_zero_copy">Presentazione senza copia</string> + <string name="display_resolution_landscape">Risoluzione orizzontale</string> + <string name="display_resolution_portrait">Risoluzione verticale</string> + <string name="display_follow_landscape">Come orizzontale (%1$d×%2$d)</string> + <string name="display_follow_portrait">Come verticale (%1$d×%2$d)</string> <string name="display_game_fit">Adattamento giochi 16:9</string> <string name="display_game_fit_hint">Come i giochi 16:9 si adattano a questo schermo. Dalla prossima sessione.</string> <string name="display_game_fit_unavailable">Scegli Adatta allo schermo o una dimensione personalizzata più stretta di 16:9.</string> + <string name="display_avoid_notch">Evita il notch</string> + <string name="display_avoid_notch_hint">Tiene l\'immagine fuori dal ritaglio della fotocamera. Si applica al ritorno alla sessione.</string> <string name="display_preserve">Mantieni proporzioni</string> <string name="display_stretch">Estendi allo schermo</string> <string name="display_image_scaling">Ridimensionamento immagine</string> @@ -2765,6 +2728,7 @@ <string name="stores_login_error_ssl">La connessione alla pagina di accesso non è sicura.</string> <string name="stores_login_error_verification">Impossibile verificare l\'accesso. Riprova.</string> <string name="stores_login_error_generic">Accesso non riuscito. Riprova.</string> + <string name="stores_login_continue_in_browser">%1$s richiede un altro passaggio. Completalo nel browser che si è aperto, poi riprova.</string> <string name="common_close">Chiudi</string> <string name="common_back">Indietro</string> <string name="common_edit">Modifica</string> @@ -3153,7 +3117,7 @@ <string name="hand_camera_done">Fine</string> <string name="glasses_xreal_network_missing">In attesa della connessione USB Ethernet degli occhiali. Questo telefono potrebbe non renderla disponibile alle app.</string> <string name="glasses_xreal_connection_failed">La connessione XREAL si è interrotta o ha restituito una risposta non supportata. Nuovo tentativo…</string> - <string name="glasses_xreal_experimental">Supporto sperimentale per 1S. Usa la modalità Follow e disattiva la stabilizzazione nel menu degli occhiali. Direzioni del tracciamento e modalità di visualizzazione devono ancora essere testate sul dispositivo.</string> + <string name="glasses_xreal_experimental">Supporto sperimentale per XREAL 1S, One, One Pro, One Pro+ e Aura. Usa la modalità Follow e disattiva la stabilizzazione nel menu degli occhiali; su Aura, disattiva anche Spatial Anchor. Il tracciamento della testa e il passaggio tra 2D/3D sono stati testati su Aura e One Pro+.</string> <string name="glasses_pro2_experimental">Tracciamento sperimentale della testa per Pro 2. La regolazione di luminosità e volume e il cambio della modalità di visualizzazione non sono ancora supportati.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Modalità Cardboard</string> @@ -4049,6 +4013,7 @@ <string name="addons_sort_downloads">Più scaricati</string> <string name="addons_category_all">Tutte le categorie</string> <string name="addons_none_found">Nessun addon trovato</string> + <string name="addons_curse_busy">Chiudi prima CurseForge</string> <string name="addons_unreachable">Impossibile raggiungere %1$s</string> <string name="addons_no_file">Nessun file per questa versione del gioco</string> <string name="input_reset_positions">Ripristina posizioni</string> @@ -4152,4 +4117,6 @@ <string name="theme_custom_signal">Evidenziazioni</string> <string name="theme_custom_good">Successo</string> <string name="theme_custom_error">Errore</string> + <string name="hud_only_during_game">Mostra l’HUD solo durante il gioco</string> + <string name="hud_only_during_game_hint">Nascondi l’HUD quando non vengono rilevati fotogrammi del gioco.</string> </resources> diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index e74e3e706a..b51efa75a8 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10出力</string> <string name="mode_hdr_unavailable">利用不可:%1$s。</string> - <string name="mode_hdr_restart">アプリの再起動後に有効になります。</string> <string name="mode_drivers">ドライバー</string> <string name="mode_gpu_drivers">GPUドライバー</string> <string name="mode_gpu_drivers_hint">Steamとデスクトップで共有されます。「コンポーネント」ページで設定してください。</string> @@ -333,7 +332,6 @@ <string name="mode_startup">起動</string> <string name="mode_startup_session">起動時に開く</string> <string name="mode_startup_session_hint">DroidDeck の起動時にこのセッションを開始します。</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">リリースを確認中…</string> <string name="mode_decky_ready">%1$sをインストールする準備ができました。</string> <string name="mode_decky_none">互換性のあるバージョンが見つかりません。後でもう一度お試しください。</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">最新です · %1$s</string> <string name="mode_decky_loader">ローダー</string> <string name="mode_decky_install_latest">最新バージョンをインストール</string> - <string name="decky_channel">アップデートチャンネル</string> - <string name="decky_channel_hint">インストールするDecky Loaderのリリースです。Decky自身のアップデーターも同じチャンネルを使用します。</string> <string name="decky_channel_stable">安定版</string> <string name="decky_channel_prerelease">プレリリース版</string> <string name="decky_channel_testing">テスト版</string> <string name="decky_channel_failed">Deckyのアップデートチャンネルを保存できませんでした</string> - <string name="mode_decky_on">Steamと共に起動します。有効にすると、このデバイス上の他のアプリがSteamを制御できる場合があります。</string> - <string name="mode_decky_off">オフ。Steamのリモートデバッグポートは閉じたままになります。</string> <string name="mode_decky_remove_title">Decky Loaderをアンインストールしますか?</string> <string name="mode_decky_remove_text">ローダーを削除します。プラグインと設定は保持されます。</string> <string name="mode_client">クライアント</string> @@ -950,13 +944,15 @@ <string name="setup_launcher_orientation_auto">デバイスの回転に合わせる</string> <string name="setup_orientation_portrait">縦向き</string> <string name="setup_session_orientation">セッションの向き</string> - <string name="setup_session_orientation_hint">Steam、ゲーム、デスクトップ、コントローラーエディターに適用されます。解像度プリセットはセッションに合わせて回転し、カスタムの幅と高さは入力したとおりになります。</string> + <string name="setup_session_orientation_hint">Steam、ゲーム、デスクトップ、コントローラーエディターに適用されます。解像度プリセットはセッションに合わせて回転し、一方の向きがもう一方に従う場合、カスタムの幅と高さは向きに合わせて入れ替わります。</string> <string name="setup_orientation_auto">横向き(自動回転)</string> <string name="setup_orientation_landscape">横向き</string> <string name="setup_orientation_reverse">横向き(反転)</string> <string name="setup_fullscreen">全画面</string> <string name="setup_fullscreen_on">Androidのステータスバーとナビゲーションバーを非表示</string> <string name="setup_fullscreen_off">Androidのステータスバーとナビゲーションバーを表示</string> + <string name="setup_page_swipe">スワイプでページを切り替え</string> + <string name="setup_page_swipe_hint">ページを横切るようにスワイプすると、タブを切り替えます。</string> <string name="setup_dual_screen_launcher">デュアルスクリーンランチャー</string> <string name="setup_dual_screen_launcher_hint">自動では、内蔵セカンドスクリーンを搭載した携帯ゲーム機で、ランチャーの各セクション(Steam、ライブラリ、ストアなど)を2画面目に表示します。オンでは任意のセカンドディスプレイを使用します。オフではランチャーを1画面に留めます。</string> <string name="setup_dual_screen_sessions">デュアルスクリーンセッション</string> @@ -1274,8 +1270,6 @@ <string name="gate_open_dev">開発者向けオプションを開く</string> <string name="gate_no_toggle">このAndroidバージョンにはこのスイッチがないため、DroidDeckはワイヤレスデバッグを介して変更します。約1分かかり、PCは不要です。</string> <string name="gate_needs_wifi">ワイヤレスデバッグにはWi-Fiが必要です。ネットワークは何でもよく、インターネットは不要です。</string> - <string name="gate_needs_notifications">ペアリングコードは通知に表示されます。DroidDeckに通知を許可するか、「他の方法」を使用してください。</string> - <string name="gate_allow_notifications">通知を許可</string> <string name="gate_step1">設定 → 開発者向けオプション → ワイヤレスデバッグを開き、オンにする</string> <string name="gate_step2">「ペアリングコードでデバイスをペア設定」をタップ</string> <string name="gate_step3">DroidDeckの通知にペアリングコードを入力</string> @@ -1292,48 +1286,13 @@ <string name="gate_status">ステータス</string> <string name="gate_polling">2秒ごとに確認します。このスイッチをオフにすると、このページは自動的に閉じます。</string> <string name="gate_other_ways">他の方法</string> - <string name="gate_other_toggle">ワイヤレスデバッグ、手動でアドレス入力、PC ADB</string> - <string name="gate_other_no_toggle">手動でアドレス入力、PC ADB、開発者向けオプション</string> <string name="gate_use_wireless_instead">代わりにワイヤレスデバッグを使用</string> <string name="gate_some_roms">一部のROMではこのスイッチが提供されています。開発者向けオプションで「子プロセス」を検索してください。</string> - <string name="gate_manual_hint">通知方法が機能しない場合は、ポップアップのアドレスとペアリングコードを手動で入力してください。</string> - <string name="gate_enter_manually">手動でアドレスを入力</string> <string name="gate_from_computer">PCでADBを使用:</string> <string name="gate_copy_command">コマンドをコピー</string> <string name="gate_sidequest_steps">ヘッドセットをパソコンにつないで SideQuest を開きます。「Run ADB Command」→「Custom Command」を選び、下に表示されたコマンドを入力して「Run Command」を選びます。</string> <string name="gate_choose_display">Android設定をどの画面で開くか選択してください。</string> <string name="gate_main_screen">メイン画面</string> - <string name="wadb_finding_port">ペアリング済み。ワイヤレスデバッグのポートを検索中…</string> - <string name="wadb_enter_port">ペアリング済み。設定のポートを入力してください。</string> - <string name="wadb_applying">デバイスが見つかりました。設定を適用中…</string> - <string name="wadb_apply_failed">自動適用できませんでした。以下のアドレスを確認して再試行してください。 %1$s</string> - <string name="wadb_title_wireless">ワイヤレスデバッグ</string> - <string name="wadb_title_done">子プロセス制限を更新しました</string> - <string name="wadb_title">子プロセス制限の変更</string> - <string name="wadb_lede_compact0">オプションがない場合は、ワイヤレスデバッグでペアリングしてください。</string> - <string name="wadb_lede_compact1">ペアリング済み。ワイヤレスデバッグのIPアドレスとポートを確認してください。</string> - <string name="wadb_lede_done">子プロセス制限を更新しました。</string> - <string name="wadb_lede0">開発者向けオプションに子プロセス設定がない場合は、手順2を使用してください。開発者向けオプション → ワイヤレスデバッグ → ペアリングコードでデバイスをペア設定を開きます。</string> - <string name="wadb_lede1">ペアリング済み。以下のアドレスを使用するか、ワイヤレスデバッグ → IPアドレスとポートで更新してください。</string> - <string name="wadb_lede_done_long">ワイヤレスデバッグを介して子プロセス制限を更新しました。</string> - <string name="wadb_confirmed_on">Androidは制限がオンであることを確認しました。</string> - <string name="wadb_confirmed_off">Androidは制限がオフであることを確認しました。</string> - <string name="wadb_pair_group">2 · ワイヤレスデバッグのペアリング</string> - <string name="wadb_pair_address">ポップアップのIPアドレスとポート</string> - <string name="wadb_pin">ペアリングコード(PIN)</string> - <string name="wadb_pin_placeholder">6桁の数字</string> - <string name="wadb_pair">ペアリング</string> - <string name="wadb_apply_group">2 · ワイヤレスデバッグで適用</string> - <string name="wadb_connect_address">接続先のIPアドレスとポート</string> - <string name="wadb_pair_again">再ペアリング</string> - <string name="wadb_turn_off">制限をオフにする</string> - <string name="wadb_other_ways">その他の変更方法</string> - <string name="wadb_dev_try_first">1 · 開発者向けオプション(最初に試す)</string> - <string name="wadb_restrict_on">「子プロセスの制限を無効化」をオフにします。</string> - <string name="wadb_restrict_off">「子プロセスの制限を無効化」をオンにします。</string> - <string name="wadb_computer_last">3 · PC ADB(最終手段)</string> - <string name="wadb_only_if">ワイヤレスデバッグが利用できない場合にのみ使用してください。</string> - <string name="wadb_computer_group">3 · PC ADB(最終手段)</string> <string name="ctrl_color">色</string> <string name="ctrl_custom">カスタム</string> <string name="ctrl_opacity">不透明度</string> @@ -1615,8 +1574,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">%1$d個のセッションログフォルダを消去しました。</item> </plurals> - <string name="main_wadb_pair_failed">ワイヤレスデバッグのペアリングに失敗しました</string> - <string name="main_wadb_command_failed">ワイヤレスデバッグのコマンドに失敗しました</string> <string name="main_wadb_unavailable">ワイヤレスデバッグは利用できません</string> <string name="main_adb_copied">ADBコマンドをコピーしました</string> <string name="main_pick_roms">ROMフォルダを選択</string> @@ -2436,10 +2393,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s。%2$s\n\n%3$s</string> <string name="display_session">セッションの表示</string> - <string name="display_resolution">解像度</string> + <string name="display_zero_copy">ゼロコピー表示</string> + <string name="display_resolution_landscape">横向きの解像度</string> + <string name="display_resolution_portrait">縦向きの解像度</string> + <string name="display_follow_landscape">横向きに合わせる (%1$d×%2$d)</string> + <string name="display_follow_portrait">縦向きに合わせる (%1$d×%2$d)</string> <string name="display_game_fit">16:9ゲームの表示</string> <string name="display_game_fit_hint">16:9のゲームをこのディスプレイにどう合わせるか。次回のセッションから。</string> <string name="display_game_fit_unavailable">「画面に合わせる」か、16:9より縦長のカスタムサイズを選んでください。</string> + <string name="display_avoid_notch">ノッチを避ける</string> + <string name="display_avoid_notch_hint">映像をカメラの切り欠きから離します。セッションに戻ると反映されます。</string> <string name="display_preserve">縦横比を保持</string> <string name="display_stretch">画面いっぱいに引き伸ばす</string> <string name="display_image_scaling">画像のスケーリング</string> @@ -2726,6 +2689,7 @@ <string name="stores_login_error_ssl">ログインページへの接続は安全ではありません。</string> <string name="stores_login_error_verification">ログインを確認できませんでした。もう一度お試しください。</string> <string name="stores_login_error_generic">ログインに失敗しました。もう一度お試しください。</string> + <string name="stores_login_continue_in_browser">%1$s で追加の手順が必要です。開いたブラウザーで完了してから、もう一度お試しください。</string> <string name="common_close">閉じる</string> <string name="common_back">戻る</string> <string name="common_edit">編集</string> @@ -3106,7 +3070,7 @@ <string name="hand_camera_done">完了</string> <string name="glasses_xreal_network_missing">グラスの USB Ethernet 接続を待っています。このスマートフォンでは、アプリがこの接続を利用できない場合があります。</string> <string name="glasses_xreal_connection_failed">XREAL との接続が中断されたか、サポートされていない応答が返されました。再試行しています…</string> - <string name="glasses_xreal_experimental">1S のサポートは試験運用中です。グラスのメニューで Follow モードを使い、安定化をオフにしてください。トラッキングの方向と表示モードは、まだ実機でのテストが必要です。</string> + <string name="glasses_xreal_experimental">XREAL 1S、One、One Pro、One Pro+、Auraの試験的なサポートです。グラスのメニューでFollowモードを使用し、安定化をオフにしてください。AuraではSpatial Anchorもオフにしてください。ヘッドトラッキングと2D/3D切り替えは、AuraとOne Pro+でテスト済みです。</string> <string name="glasses_pro2_experimental">Pro 2 のヘッドトラッキングは試験運用中です。明るさと音量の調整、および表示モードの切り替えにはまだ対応していません。</string> <string name="stores_fact_developer">開発元</string> <string name="stores_fact_publisher">パブリッシャー</string> @@ -3980,6 +3944,7 @@ <string name="addons_sort_downloads">ダウンロード数順</string> <string name="addons_category_all">すべてのカテゴリ</string> <string name="addons_none_found">アドオンが見つかりません</string> + <string name="addons_curse_busy">先に CurseForge を閉じてください</string> <string name="addons_unreachable">%1$s に接続できませんでした</string> <string name="addons_no_file">このゲームバージョン用のファイルがありません</string> <string name="input_reset_positions">位置をリセット</string> @@ -4083,4 +4048,6 @@ <string name="theme_custom_signal">強調表示</string> <string name="theme_custom_good">成功</string> <string name="theme_custom_error">エラー</string> + <string name="hud_only_during_game">ゲーム中のみHUDを表示</string> + <string name="hud_only_during_game_hint">ゲームのフレームが検出されないときはHUDを非表示にする。</string> </resources> diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 557cabab25..8b3f92a2a9 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 출력</string> <string name="mode_hdr_unavailable">사용 불가: %1$s.</string> - <string name="mode_hdr_restart">앱을 다시 시작한 후 적용됩니다.</string> <string name="mode_drivers">드라이버</string> <string name="mode_gpu_drivers">GPU 드라이버</string> <string name="mode_gpu_drivers_hint">Steam과 데스크톱에서 공유됩니다. \"구성 요소\" 페이지에서 설정하세요.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">시작</string> <string name="mode_startup_session">실행 시 열기</string> <string name="mode_startup_session_hint">DroidDeck을 실행할 때 이 세션을 시작합니다.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">릴리스 확인 중…</string> <string name="mode_decky_ready">%1$s을(를) 설치할 준비가 되었습니다.</string> <string name="mode_decky_none">호환되는 버전을 찾을 수 없습니다. 나중에 다시 시도하세요.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">최신 버전 · %1$s</string> <string name="mode_decky_loader">로더</string> <string name="mode_decky_install_latest">최신 버전 설치</string> - <string name="decky_channel">업데이트 채널</string> - <string name="decky_channel_hint">설치할 Decky Loader 릴리스입니다. Decky 자체 업데이터도 같은 채널을 사용합니다.</string> <string name="decky_channel_stable">안정판</string> <string name="decky_channel_prerelease">사전 출시판</string> <string name="decky_channel_testing">테스트판</string> <string name="decky_channel_failed">Decky 업데이트 채널을 저장할 수 없습니다</string> - <string name="mode_decky_on">Steam과 함께 시작됩니다. 활성화하면 이 기기의 다른 앱이 Steam을 제어할 수 있습니다.</string> - <string name="mode_decky_off">끔. Steam의 원격 디버깅 포트가 닫힌 상태로 유지됩니다.</string> <string name="mode_decky_remove_title">Decky Loader를 제거하시겠습니까?</string> <string name="mode_decky_remove_text">로더를 제거합니다. 플러그인과 설정은 유지됩니다.</string> <string name="mode_client">클라이언트</string> @@ -950,13 +944,15 @@ <string name="setup_launcher_orientation_auto">기기 회전 따르기</string> <string name="setup_orientation_portrait">세로</string> <string name="setup_session_orientation">세션 방향</string> - <string name="setup_session_orientation_hint">Steam, 게임, 데스크톱 및 컨트롤러 편집기에 적용됩니다. 해상도 프리셋은 세션에 맞춰 회전하며, 사용자 정의 너비와 높이는 입력한 그대로 유지됩니다.</string> + <string name="setup_session_orientation_hint">Steam, 게임, 데스크톱 및 컨트롤러 편집기에 적용됩니다. 해상도 프리셋은 세션에 맞춰 회전하며, 한 방향이 다른 방향을 따를 때 사용자 정의 너비와 높이는 방향에 맞게 서로 바뀝니다.</string> <string name="setup_orientation_auto">자동 가로 모드</string> <string name="setup_orientation_landscape">가로 모드</string> <string name="setup_orientation_reverse">역방향 가로 모드</string> <string name="setup_fullscreen">전체 화면</string> <string name="setup_fullscreen_on">Android 상태 표시줄 및 탐색 표시줄 숨기기</string> <string name="setup_fullscreen_off">Android 상태 표시줄 및 탐색 표시줄 표시</string> + <string name="setup_page_swipe">스와이프로 페이지 전환</string> + <string name="setup_page_swipe_hint">페이지를 가로질러 스와이프하면 탭이 바뀝니다.</string> <string name="setup_dual_screen_launcher">듀얼 화면 런처</string> <string name="setup_dual_screen_launcher_hint">자동은 내장 두 번째 화면이 있는 휴대용 기기에서 런처 섹션(Steam, 라이브러리, 스토어 등)을 두 번째 화면에 표시합니다. 켜기는 어떤 두 번째 디스플레이든 사용합니다. 끄기는 런처를 한 화면에 유지합니다.</string> <string name="setup_dual_screen_sessions">듀얼 화면 세션</string> @@ -1274,8 +1270,6 @@ <string name="gate_open_dev">개발자 옵션 열기</string> <string name="gate_no_toggle">이 Android 버전에는 해당 스위치가 없으므로 DroidDeck이 무선 디버깅을 통해 수정합니다. 약 1분이 걸리며 PC가 필요하지 않습니다.</string> <string name="gate_needs_wifi">무선 디버깅에는 Wi-Fi가 필요합니다. 네트워크는 아무거나 괜찮으며 인터넷은 필요하지 않습니다.</string> - <string name="gate_needs_notifications">페어링 코드가 알림에 표시됩니다. DroidDeck에 알림을 허용하거나 \"다른 방법\"을 사용하세요.</string> - <string name="gate_allow_notifications">알림 허용</string> <string name="gate_step1">설정 → 개발자 옵션 → 무선 디버깅을 열고 켜기</string> <string name="gate_step2">\"페어링 코드로 기기 페어링\" 탭</string> <string name="gate_step3">DroidDeck 알림에 페어링 코드 입력</string> @@ -1292,48 +1286,13 @@ <string name="gate_status">상태</string> <string name="gate_polling">2초마다 확인합니다. 이 스위치를 끄면 이 페이지가 자동으로 닫힙니다.</string> <string name="gate_other_ways">다른 방법</string> - <string name="gate_other_toggle">무선 디버깅, 수동 주소 입력, PC ADB</string> - <string name="gate_other_no_toggle">수동 주소 입력, PC ADB, 개발자 옵션</string> <string name="gate_use_wireless_instead">대신 무선 디버깅 사용</string> <string name="gate_some_roms">일부 ROM에서는 이 스위치를 제공합니다. 개발자 옵션에서 \"하위 프로세스\"를 검색하세요.</string> - <string name="gate_manual_hint">알림 방법이 작동하지 않으면 팝업의 주소와 페어링 코드를 수동으로 입력하세요.</string> - <string name="gate_enter_manually">수동으로 주소 입력</string> <string name="gate_from_computer">PC에서 ADB 사용:</string> <string name="gate_copy_command">명령 복사</string> <string name="gate_sidequest_steps">헤드셋을 컴퓨터에 연결하고 SideQuest를 엽니다. “Run ADB Command”, “Custom Command”를 차례로 선택하고 아래에 표시된 명령을 입력한 뒤 “Run Command”를 선택하세요.</string> <string name="gate_choose_display">Android 설정을 어느 화면에서 열지 선택하세요.</string> <string name="gate_main_screen">메인 화면</string> - <string name="wadb_finding_port">페어링됨. 무선 디버깅 포트를 찾는 중…</string> - <string name="wadb_enter_port">페어링됨. 설정의 포트를 입력하세요.</string> - <string name="wadb_applying">기기를 찾았습니다. 설정을 적용하는 중…</string> - <string name="wadb_apply_failed">자동으로 적용할 수 없습니다. 아래 주소를 확인한 후 다시 시도하세요. %1$s</string> - <string name="wadb_title_wireless">무선 디버깅</string> - <string name="wadb_title_done">하위 프로세스 제한 업데이트됨</string> - <string name="wadb_title">하위 프로세스 제한 변경</string> - <string name="wadb_lede_compact0">옵션이 없으면 무선 디버깅으로 페어링하세요.</string> - <string name="wadb_lede_compact1">페어링됨. 무선 디버깅의 IP 주소와 포트를 확인하세요.</string> - <string name="wadb_lede_done">하위 프로세스 제한이 업데이트되었습니다.</string> - <string name="wadb_lede0">개발자 옵션에 하위 프로세스 설정이 없으면 2단계를 사용하세요. 개발자 옵션 → 무선 디버깅 → 페어링 코드로 기기 페어링을 엽니다.</string> - <string name="wadb_lede1">페어링됨. 아래 주소를 사용하거나 무선 디버깅 → IP 주소 및 포트에서 업데이트하세요.</string> - <string name="wadb_lede_done_long">무선 디버깅을 통해 하위 프로세스 제한을 업데이트했습니다.</string> - <string name="wadb_confirmed_on">Android에서 제한이 켜져 있음을 확인했습니다.</string> - <string name="wadb_confirmed_off">Android에서 제한이 꺼져 있음을 확인했습니다.</string> - <string name="wadb_pair_group">2 · 무선 디버깅 페어링</string> - <string name="wadb_pair_address">페어링 팝업의 IP 주소 및 포트</string> - <string name="wadb_pin">페어링 코드(PIN)</string> - <string name="wadb_pin_placeholder">6자리 숫자</string> - <string name="wadb_pair">페어링</string> - <string name="wadb_apply_group">2 · 무선 디버깅으로 적용</string> - <string name="wadb_connect_address">연결할 IP 주소 및 포트</string> - <string name="wadb_pair_again">다시 페어링</string> - <string name="wadb_turn_off">제한 끄기</string> - <string name="wadb_other_ways">기타 변경 방법</string> - <string name="wadb_dev_try_first">1 · 개발자 옵션(먼저 시도)</string> - <string name="wadb_restrict_on">\"하위 프로세스 제한 사용 중지\"를 끕니다.</string> - <string name="wadb_restrict_off">\"하위 프로세스 제한 사용 중지\"를 켭니다.</string> - <string name="wadb_computer_last">3 · PC ADB(최후의 수단)</string> - <string name="wadb_only_if">무선 디버깅을 사용할 수 없을 때만 사용하세요.</string> - <string name="wadb_computer_group">3 · PC ADB(최후의 수단)</string> <string name="ctrl_color">색상</string> <string name="ctrl_custom">사용자 정의</string> <string name="ctrl_opacity">불투명도</string> @@ -1615,8 +1574,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">세션 로그 폴더 %1$d개를 지웠습니다.</item> </plurals> - <string name="main_wadb_pair_failed">무선 디버깅 페어링 실패</string> - <string name="main_wadb_command_failed">무선 디버깅 명령 실패</string> <string name="main_wadb_unavailable">무선 디버깅을 사용할 수 없습니다</string> <string name="main_adb_copied">ADB 명령이 복사되었습니다</string> <string name="main_pick_roms">ROM 폴더 선택</string> @@ -2436,10 +2393,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">세션 디스플레이</string> - <string name="display_resolution">해상도</string> + <string name="display_zero_copy">제로카피 표시</string> + <string name="display_resolution_landscape">가로 해상도</string> + <string name="display_resolution_portrait">세로 해상도</string> + <string name="display_follow_landscape">가로와 동일 (%1$d×%2$d)</string> + <string name="display_follow_portrait">세로와 동일 (%1$d×%2$d)</string> <string name="display_game_fit">16:9 게임 맞춤</string> <string name="display_game_fit_hint">16:9 게임을 이 디스플레이에 맞추는 방식입니다. 다음 세션부터 적용됩니다.</string> <string name="display_game_fit_unavailable">화면에 맞춤 또는 16:9보다 좁은 사용자 정의 크기를 선택하세요.</string> + <string name="display_avoid_notch">노치 피하기</string> + <string name="display_avoid_notch_hint">화면을 카메라 컷아웃 밖에 표시합니다. 세션으로 돌아오면 적용됩니다.</string> <string name="display_preserve">비율 유지</string> <string name="display_stretch">화면에 맞게 늘이기</string> <string name="display_image_scaling">이미지 스케일링</string> @@ -2726,6 +2689,7 @@ <string name="stores_login_error_ssl">로그인 페이지 연결이 안전하지 않습니다.</string> <string name="stores_login_error_verification">로그인을 확인할 수 없습니다. 다시 시도하세요.</string> <string name="stores_login_error_generic">로그인에 실패했습니다. 다시 시도하세요.</string> + <string name="stores_login_continue_in_browser">%1$s에서 한 단계가 더 필요합니다. 열린 브라우저에서 완료한 다음 다시 시도하세요.</string> <string name="common_close">닫기</string> <string name="common_back">뒤로</string> <string name="common_edit">편집</string> @@ -3106,7 +3070,7 @@ <string name="hand_camera_done">완료</string> <string name="glasses_xreal_network_missing">안경의 USB Ethernet 연결을 기다리는 중입니다. 이 휴대폰은 앱에 이 연결을 제공하지 않을 수 있습니다.</string> <string name="glasses_xreal_connection_failed">XREAL 연결이 중단되었거나 지원되지 않는 응답을 받았습니다. 다시 시도하는 중…</string> - <string name="glasses_xreal_experimental">1S 지원은 실험 단계입니다. 안경 메뉴에서 Follow 모드를 사용하고 안정화를 끄세요. 트래킹 방향과 디스플레이 모드는 아직 기기에서 테스트가 필요합니다.</string> + <string name="glasses_xreal_experimental">XREAL 1S, One, One Pro, One Pro+ 및 Aura의 실험적 지원입니다. 안경 메뉴에서 Follow 모드를 사용하고 안정화를 끄세요. Aura에서는 Spatial Anchor도 끄세요. 헤드 트래킹과 2D/3D 전환은 Aura와 One Pro+에서 테스트되었습니다.</string> <string name="glasses_pro2_experimental">Pro 2 헤드 트래킹은 실험 단계입니다. 밝기와 음량 조절 및 디스플레이 모드 전환은 아직 지원되지 않습니다.</string> <string name="stores_fact_developer">개발사</string> <string name="stores_fact_publisher">배급사</string> @@ -3980,6 +3944,7 @@ <string name="addons_sort_downloads">다운로드 많은 순</string> <string name="addons_category_all">모든 카테고리</string> <string name="addons_none_found">애드온을 찾을 수 없음</string> + <string name="addons_curse_busy">먼저 CurseForge를 닫으세요</string> <string name="addons_unreachable">%1$s에 연결할 수 없습니다</string> <string name="addons_no_file">이 게임 버전용 파일이 없습니다</string> <string name="input_reset_positions">위치 초기화</string> @@ -4083,4 +4048,6 @@ <string name="theme_custom_signal">강조 표시</string> <string name="theme_custom_good">성공</string> <string name="theme_custom_error">오류</string> + <string name="hud_only_during_game">게임 중에만 HUD 표시</string> + <string name="hud_only_during_game_hint">게임 프레임이 감지되지 않으면 HUD 숨기기.</string> </resources> diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 168ceaa971..95364b21d1 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Output HDR10</string> <string name="mode_hdr_unavailable">Tidak tersedia: %1$s.</string> - <string name="mode_hdr_restart">Mulakan semula apl untuk menggunakannya.</string> <string name="mode_drivers">Pemacu</string> <string name="mode_gpu_drivers">Pemacu GPU</string> <string name="mode_gpu_drivers_hint">Dikongsi oleh Steam dan Desktop. Ditetapkan pada halaman Komponen.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Permulaan</string> <string name="mode_startup_session">Buka semasa pelancaran</string> <string name="mode_startup_session_hint">Memulakan sesi ini apabila DroidDeck dilancarkan.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Menyemak keluaran…</string> <string name="mode_decky_ready">Sedia untuk memasang %1$s.</string> <string name="mode_decky_none">Tiada binaan serasi ditemui. Cuba lagi kemudian.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Terkini · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Pasang yang terbaharu</string> - <string name="decky_channel">Saluran Kemas Kini</string> - <string name="decky_channel_hint">Keluaran Decky Loader yang hendak dipasang. Pengemas kini Decky sendiri menggunakan saluran yang sama.</string> <string name="decky_channel_stable">Stabil</string> <string name="decky_channel_prerelease">Prakeluaran</string> <string name="decky_channel_testing">Pengujian</string> <string name="decky_channel_failed">Tidak dapat menyimpan saluran kemas kini Decky</string> - <string name="mode_decky_on">Bermula bersama Steam. Semasa dihidupkan, apl lain pada peranti ini mungkin boleh mengawal Steam.</string> - <string name="mode_decky_off">Mati. Port debug jauh Steam kekal tertutup.</string> <string name="mode_decky_remove_title">Nyahpasang Decky Loader?</string> <string name="mode_decky_remove_text">Mengalih keluar loader. Plugin dan tetapan anda dikekalkan.</string> <string name="mode_client">Klien</string> @@ -950,13 +944,15 @@ <string name="setup_launcher_orientation_auto">Ikut putaran peranti</string> <string name="setup_orientation_portrait">Potret</string> <string name="setup_session_orientation">Orientasi sesi</string> - <string name="setup_session_orientation_hint">Berkuat kuasa pada Steam, permainan, desktop dan editor pengawal. Pratetap resolusi berputar bersama sesi; lebar dan tinggi tersuai kekal seperti yang dimasukkan.</string> + <string name="setup_session_orientation_hint">Berkuat kuasa pada Steam, permainan, desktop dan editor pengawal. Pratetap resolusi berputar bersama sesi; apabila satu orientasi mengikuti yang lain, lebar dan tinggi tersuai ditukar supaya sepadan.</string> <string name="setup_orientation_auto">Lanskap automatik</string> <string name="setup_orientation_landscape">Lanskap</string> <string name="setup_orientation_reverse">Lanskap songsang</string> <string name="setup_fullscreen">Skrin penuh</string> <string name="setup_fullscreen_on">Menyembunyikan bar status dan navigasi Android</string> <string name="setup_fullscreen_off">Memaparkan bar status dan navigasi Android</string> + <string name="setup_page_swipe">Leret antara halaman</string> + <string name="setup_page_swipe_hint">Leret merentasi halaman untuk menukar tab.</string> <string name="setup_dual_screen_launcher">Pelancar dwi skrin</string> <string name="setup_dual_screen_launcher_hint">Automatik meletakkan bahagian pelancar (Steam, Pustaka, Kedai dan selebihnya) pada skrin kedua terbina dalam peranti genggam. Hidup menggunakan sebarang paparan kedua. Mati mengekalkan pelancar pada satu skrin.</string> <string name="setup_dual_screen_sessions">Sesi dwi skrin</string> @@ -1274,8 +1270,6 @@ <string name="gate_open_dev">Buka Pilihan pembangun</string> <string name="gate_no_toggle">Versi Android ini tidak mempunyai suis untuknya, jadi DroidDeck menukarnya melalui Debugging Wayarles. Mengambil masa kira-kira seminit, tanpa komputer diperlukan.</string> <string name="gate_needs_wifi">Debugging Wayarles memerlukan Wi-Fi. Mana-mana rangkaian berfungsi; ia tidak memerlukan internet.</string> - <string name="gate_needs_notifications">Kod gandingan dihantar dalam pemberitahuan. Benarkan pemberitahuan untuk DroidDeck, atau gunakan Cara lain.</string> - <string name="gate_allow_notifications">Benarkan pemberitahuan</string> <string name="gate_step1">Buka Tetapan → Pilihan pembangun → Debugging Wayarles dan hidupkannya</string> <string name="gate_step2">Ketik “Gandingkan peranti dengan kod gandingan”</string> <string name="gate_step3">Taip kod itu ke dalam pemberitahuan DroidDeck</string> @@ -1292,48 +1286,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Menyemak setiap 2 saat. Halaman ini ditutup apabila ia mati.</string> <string name="gate_other_ways">Cara lain</string> - <string name="gate_other_toggle">Debugging Wayarles, alamat manual, ADB komputer</string> - <string name="gate_other_no_toggle">Alamat manual, ADB komputer, Pilihan pembangun</string> <string name="gate_use_wireless_instead">Gunakan Debugging Wayarles sebaliknya</string> <string name="gate_some_roms">Sesetengah ROM turut menambah suis itu. Cari “proses anak” dalam Pilihan pembangun.</string> - <string name="gate_manual_hint">Jika pemberitahuan tidak berfungsi, masukkan alamat dan kod tetingkap timbul itu sendiri.</string> - <string name="gate_enter_manually">Masukkan alamat secara manual</string> <string name="gate_from_computer">Daripada komputer dengan ADB:</string> <string name="gate_copy_command">Salin arahan</string> <string name="gate_sidequest_steps">Sambungkan set kepala ke komputer dan buka SideQuest. Pilih “Run ADB Command”, kemudian “Custom Command”, taip perintah yang dipaparkan di bawah dan pilih “Run Command”.</string> <string name="gate_choose_display">Pilih paparan mana untuk membuka Tetapan Android.</string> <string name="gate_main_screen">Skrin utama</string> - <string name="wadb_finding_port">Digandingkan. Mencari port Debugging Wayarles…</string> - <string name="wadb_enter_port">Digandingkan. Masukkan port daripada Tetapan.</string> - <string name="wadb_applying">Peranti dijumpai. Menggunakan tetapan…</string> - <string name="wadb_apply_failed">Tidak dapat digunakan secara automatik. Semak alamat di bawah dan cuba lagi. %1$s</string> - <string name="wadb_title_wireless">Debugging Wayarles</string> - <string name="wadb_title_done">Had proses anak dikemas kini</string> - <string name="wadb_title">Tukar had proses anak</string> - <string name="wadb_lede_compact0">Jika pilihan itu tiada, gandingkan melalui Debugging Wayarles.</string> - <string name="wadb_lede_compact1">Digandingkan. Semak alamat IP dan port dalam Debugging Wayarles.</string> - <string name="wadb_lede_done">Had proses anak telah dikemas kini.</string> - <string name="wadb_lede0">Gunakan langkah 2 jika Pilihan pembangun tidak mempunyai tetapan proses anak. Buka Pilihan pembangun → Debugging Wayarles → Gandingkan peranti dengan kod gandingan.</string> - <string name="wadb_lede1">Digandingkan. Gunakan alamat di bawah, atau kemas kini daripada Debugging Wayarles → Alamat IP & Port.</string> - <string name="wadb_lede_done_long">Had proses anak telah dikemas kini melalui Debugging Wayarles.</string> - <string name="wadb_confirmed_on">Android mengesahkan had itu hidup.</string> - <string name="wadb_confirmed_off">Android mengesahkan had itu mati.</string> - <string name="wadb_pair_group">2 · Gandingkan Debugging Wayarles</string> - <string name="wadb_pair_address">Alamat IP & port tetingkap timbul gandingan</string> - <string name="wadb_pin">Kod gandingan (PIN)</string> - <string name="wadb_pin_placeholder">6 digit</string> - <string name="wadb_pair">Gandingkan</string> - <string name="wadb_apply_group">2 · Gunakan melalui Debugging Wayarles</string> - <string name="wadb_connect_address">Alamat IP & port sambungan</string> - <string name="wadb_pair_again">Gandingkan semula</string> - <string name="wadb_turn_off">Matikan had</string> - <string name="wadb_other_ways">Cara lain untuk menukarnya</string> - <string name="wadb_dev_try_first">1 · Pilihan pembangun (cuba dahulu)</string> - <string name="wadb_restrict_on">Tetapkan “Lumpuhkan sekatan proses anak” mati.</string> - <string name="wadb_restrict_off">Tetapkan “Lumpuhkan sekatan proses anak” hidup.</string> - <string name="wadb_computer_last">3 · ADB komputer (pilihan akhir)</string> - <string name="wadb_only_if">Hanya jika Debugging Wayarles tidak tersedia.</string> - <string name="wadb_computer_group">3 · ADB komputer (pilihan akhir)</string> <string name="ctrl_color">Warna</string> <string name="ctrl_custom">Tersuai</string> <string name="ctrl_opacity">Kelegapan</string> @@ -1615,8 +1574,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">%1$d folder log sesi dikosongkan.</item> </plurals> - <string name="main_wadb_pair_failed">Gandingan Debugging Wayarles gagal</string> - <string name="main_wadb_command_failed">Arahan Debugging Wayarles gagal</string> <string name="main_wadb_unavailable">Debugging Wayarles tidak tersedia</string> <string name="main_adb_copied">Arahan ADB disalin</string> <string name="main_pick_roms">Pilih folder ROM</string> @@ -2436,10 +2393,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Paparan sesi</string> - <string name="display_resolution">Resolusi</string> + <string name="display_zero_copy">Paparan tanpa salinan</string> + <string name="display_resolution_landscape">Resolusi landskap</string> + <string name="display_resolution_portrait">Resolusi potret</string> + <string name="display_follow_landscape">Ikut landskap (%1$d×%2$d)</string> + <string name="display_follow_portrait">Ikut potret (%1$d×%2$d)</string> <string name="display_game_fit">Suaian permainan 16:9</string> <string name="display_game_fit_hint">Cara permainan 16:9 disuaikan ke paparan ini. Sesi seterusnya.</string> <string name="display_game_fit_unavailable">Pilih Sepadan skrin atau saiz tersuai lebih nipis daripada 16:9.</string> + <string name="display_avoid_notch">Elak takuk</string> + <string name="display_avoid_notch_hint">Memastikan gambar tidak berada di potongan kamera. Digunakan apabila anda kembali ke sesi.</string> <string name="display_preserve">Kekalkan nisbah</string> <string name="display_stretch">Regang ke paparan</string> <string name="display_image_scaling">Penskalaan imej</string> @@ -2726,6 +2689,7 @@ <string name="stores_login_error_ssl">Sambungan ke halaman log masuk tidak selamat.</string> <string name="stores_login_error_verification">Log masuk tidak dapat disahkan. Cuba lagi.</string> <string name="stores_login_error_generic">Log masuk gagal. Cuba lagi.</string> + <string name="stores_login_continue_in_browser">%1$s memerlukan satu langkah lagi. Selesaikannya dalam pelayar yang dibuka, kemudian cuba lagi.</string> <string name="common_close">Tutup</string> <string name="common_back">Kembali</string> <string name="common_edit">Sunting</string> @@ -3106,7 +3070,7 @@ <string name="hand_camera_done">Selesai</string> <string name="glasses_xreal_network_missing">Menunggu sambungan USB Ethernet cermin mata. Telefon ini mungkin tidak mendedahkannya kepada apl.</string> <string name="glasses_xreal_connection_failed">Sambungan XREAL terganggu atau memberikan respons yang tidak disokong. Mencuba semula…</string> - <string name="glasses_xreal_experimental">Sokongan eksperimen untuk 1S. Gunakan mod Follow dan matikan penstabilan dalam menu cermin mata. Arah penjejakan dan mod paparan masih perlu diuji pada peranti.</string> + <string name="glasses_xreal_experimental">Sokongan eksperimen untuk XREAL 1S, One, One Pro, One Pro+ dan Aura. Gunakan mod Follow dan matikan penstabilan dalam menu cermin mata; pada Aura, matikan juga Spatial Anchor. Penjejakan kepala dan pertukaran 2D/3D telah diuji pada Aura dan One Pro+.</string> <string name="glasses_pro2_experimental">Penjejakan kepala Pro 2 secara eksperimen. Pelarasan kecerahan, kelantangan dan pertukaran mod paparan belum disokong.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Mod Cardboard</string> @@ -3980,6 +3944,7 @@ <string name="addons_sort_downloads">Paling banyak dimuat turun</string> <string name="addons_category_all">Semua kategori</string> <string name="addons_none_found">Tiada addon ditemui</string> + <string name="addons_curse_busy">Tutup CurseForge dahulu</string> <string name="addons_unreachable">Tidak dapat mencapai %1$s</string> <string name="addons_no_file">Tiada fail untuk versi permainan ini</string> <string name="input_reset_positions">Tetapkan semula kedudukan</string> @@ -4083,4 +4048,6 @@ <string name="theme_custom_signal">Sorotan</string> <string name="theme_custom_good">Berjaya</string> <string name="theme_custom_error">Ralat</string> + <string name="hud_only_during_game">Paparkan HUD hanya semasa bermain</string> + <string name="hud_only_during_game_hint">Sembunyikan HUD apabila bingkai permainan tidak dikesan.</string> </resources> diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index e5115e83aa..2fd355eec3 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-utgang</string> <string name="mode_hdr_unavailable">Ikke tilgjengelig: %1$s.</string> - <string name="mode_hdr_restart">Start appen på nytt for å bruke dette.</string> <string name="mode_drivers">Drivere</string> <string name="mode_gpu_drivers">GPU-drivere</string> <string name="mode_gpu_drivers_hint">Delt av Steam og Skrivebord. Angis på Komponenter-siden.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Oppstart</string> <string name="mode_startup_session">Åpne ved oppstart</string> <string name="mode_startup_session_hint">Starter denne økten når DroidDeck starter.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Ser etter utgivelser…</string> <string name="mode_decky_ready">Klar til å installere %1$s.</string> <string name="mode_decky_none">Ingen kompatibel build funnet. Prøv igjen senere.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Oppdatert · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Installer nyeste</string> - <string name="decky_channel">Oppdateringskanal</string> - <string name="decky_channel_hint">Hvilke Decky Loader-utgivelser som installeres. Deckys egen oppdatering bruker samme kanal.</string> <string name="decky_channel_stable">Stabil</string> <string name="decky_channel_prerelease">Forhåndsutgivelse</string> <string name="decky_channel_testing">Testing</string> <string name="decky_channel_failed">Kunne ikke lagre oppdateringskanalen for Decky</string> - <string name="mode_decky_on">Starter med Steam. Mens på, kan andre apper på denne enheten kanskje styre Steam.</string> - <string name="mode_decky_off">Av. Steams fjernsøkeport for feilsøking forblir stengt.</string> <string name="mode_decky_remove_title">Avinstaller Decky Loader?</string> <string name="mode_decky_remove_text">Fjerner loaderen. Programtilleggene og innstillingene dine beholdes.</string> <string name="mode_client">Klient</string> @@ -953,13 +947,15 @@ <string name="setup_launcher_orientation_auto">Følg enhetens rotasjon</string> <string name="setup_orientation_portrait">Stående</string> <string name="setup_session_orientation">Retning for sesjonen</string> - <string name="setup_session_orientation_hint">Gjelder Steam, spill, skrivebordet og kontrollerredigeringen. Forhåndsinnstilte oppløsninger roterer med sesjonen; egendefinert bredde og høyde forblir som angitt.</string> + <string name="setup_session_orientation_hint">Gjelder Steam, spill, skrivebordet og kontrollerredigeringen. Forhåndsinnstilte oppløsninger roterer med sesjonen; når én retning følger den andre, byttes egendefinert bredde og høyde slik at de passer.</string> <string name="setup_orientation_auto">Automatisk liggende</string> <string name="setup_orientation_landscape">Liggende</string> <string name="setup_orientation_reverse">Omvendt liggende</string> <string name="setup_fullscreen">Fullskjerm</string> <string name="setup_fullscreen_on">Skjuler Androids status- og navigasjonslinjer</string> <string name="setup_fullscreen_off">Viser Androids status- og navigasjonslinjer</string> + <string name="setup_page_swipe">Sveip mellom sider</string> + <string name="setup_page_swipe_hint">Sveip over en side for å bytte fane.</string> <string name="setup_dual_screen_launcher">Startprogram på to skjermer</string> <string name="setup_dual_screen_launcher_hint">Automatisk plasserer startprogrammets deler (Steam, Bibliotek, Butikker og resten) på den andre skjermen på håndholdte enheter med innebygd sekundærskjerm. På bruker en hvilken som helst annen skjerm. Av holder startprogrammet på én skjerm.</string> <string name="setup_dual_screen_sessions">Økter på to skjermer</string> @@ -1280,8 +1276,6 @@ <string name="gate_open_dev">Åpne Utvikleralternativer</string> <string name="gate_no_toggle">Denne Android-versjonen har ingen bryter for det, så DroidDeck endrer det via trådløs feilsøking. Tar omtrent ett minutt, ingen datamaskin nødvendig.</string> <string name="gate_needs_wifi">Trådløs feilsøking krever Wi-Fi. Hvilket nettverk som helst fungerer; det krever ikke internett.</string> - <string name="gate_needs_notifications">Koblingskoden kommer i en varsling. Tillat varslinger for DroidDeck, eller bruk Andre måter.</string> - <string name="gate_allow_notifications">Tillat varslinger</string> <string name="gate_step1">Åpne Innstillinger → Utvikleralternativer → Trådløs feilsøking og slå det på</string> <string name="gate_step2">Trykk på «Par enhet med koblingskode»</string> <string name="gate_step3">Skriv koden inn i DroidDeck-varslingen</string> @@ -1298,48 +1292,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Kontrollerer hvert 2. sekund. Denne siden lukkes når det er av.</string> <string name="gate_other_ways">Andre måter</string> - <string name="gate_other_toggle">Trådløs feilsøking, manuell adresse, ADB fra datamaskin</string> - <string name="gate_other_no_toggle">Manuell adresse, ADB fra datamaskin, Utvikleralternativer</string> <string name="gate_use_wireless_instead">Bruk trådløs feilsøking i stedet</string> <string name="gate_some_roms">Noen ROM-er legger til bryteren likevel. Se etter «child process» i Utvikleralternativer.</string> - <string name="gate_manual_hint">Hvis varslingen ikke fungerer, skriv inn varselets adresse og kode selv.</string> - <string name="gate_enter_manually">Skriv inn adresse manuelt</string> <string name="gate_from_computer">Fra en datamaskin med ADB:</string> <string name="gate_copy_command">Kopier kommando</string> <string name="gate_sidequest_steps">Koble headsettet til en datamaskin og åpne SideQuest. Velg «Run ADB Command», deretter «Custom Command», skriv inn kommandoen vist nedenfor og velg «Run Command».</string> <string name="gate_choose_display">Velg hvilken skjerm Android-innstillinger skal åpnes på.</string> <string name="gate_main_screen">Hovedskjerm</string> - <string name="wadb_finding_port">Koblet sammen. Finner porten for trådløs feilsøking…</string> - <string name="wadb_enter_port">Koblet sammen. Skriv inn porten fra Innstillinger.</string> - <string name="wadb_applying">Enhet funnet. Bruker innstillingen…</string> - <string name="wadb_apply_failed">Kunne ikke bruke den automatisk. Kontroller adressen under og prøv igjen. %1$s</string> - <string name="wadb_title_wireless">Trådløs feilsøking</string> - <string name="wadb_title_done">Grensen for underprosesser er oppdatert</string> - <string name="wadb_title">Endre grensen for underprosesser</string> - <string name="wadb_lede_compact0">Hvis alternativet er borte, par over trådløs feilsøking.</string> - <string name="wadb_lede_compact1">Koblet sammen. Kontroller IP-adressen og porten i Trådløs feilsøking.</string> - <string name="wadb_lede_done">Grensen for underprosesser ble oppdatert.</string> - <string name="wadb_lede0">Bruk steg 2 hvis Utvikleralternativer ikke har en innstilling for underprosesser. Åpne Utvikleralternativer → Trådløs feilsøking → Par enhet med koblingskode.</string> - <string name="wadb_lede1">Koblet sammen. Bruk adressen under, eller oppdater den fra Trådløs feilsøking → IP-adresse og port.</string> - <string name="wadb_lede_done_long">Grensen for underprosesser ble oppdatert via trådløs feilsøking.</string> - <string name="wadb_confirmed_on">Android bekreftet at grensen er på.</string> - <string name="wadb_confirmed_off">Android bekreftet at grensen er av.</string> - <string name="wadb_pair_group">2 · Koble sammen trådløs feilsøking</string> - <string name="wadb_pair_address">IP-adresse og port for koblingsvarsel</string> - <string name="wadb_pin">Koblingskode (PIN)</string> - <string name="wadb_pin_placeholder">6 tall</string> - <string name="wadb_pair">Koble sammen</string> - <string name="wadb_apply_group">2 · Bruk via trådløs feilsøking</string> - <string name="wadb_connect_address">IP-adresse og port for tilkobling</string> - <string name="wadb_pair_again">Koble sammen igjen</string> - <string name="wadb_turn_off">Slå av grensen</string> - <string name="wadb_other_ways">Andre måter å endre det</string> - <string name="wadb_dev_try_first">1 · Utvikleralternativer (prøv først)</string> - <string name="wadb_restrict_on">Slå av «Slå av begrensninger for underordnede prosesser».</string> - <string name="wadb_restrict_off">Slå på «Slå av begrensninger for underordnede prosesser».</string> - <string name="wadb_computer_last">3 · ADB fra datamaskin (siste utvei)</string> - <string name="wadb_only_if">Bare hvis trådløs feilsøking ikke er tilgjengelig.</string> - <string name="wadb_computer_group">3 · ADB fra datamaskin (siste utvei)</string> <string name="ctrl_color">Farge</string> <string name="ctrl_custom">Egendefinert</string> <string name="ctrl_opacity">Opasitet</string> @@ -1627,8 +1586,6 @@ <item quantity="one">Tømte %1$d sesjonsloggmappe.</item> <item quantity="other">Tømte %1$d sesjonsloggmapper.</item> </plurals> - <string name="main_wadb_pair_failed">Kobling for trådløs feilsøking mislyktes</string> - <string name="main_wadb_command_failed">Kommando for trådløs feilsøking mislyktes</string> <string name="main_wadb_unavailable">Trådløs feilsøking er ikke tilgjengelig</string> <string name="main_adb_copied">ADB-kommando kopiert</string> <string name="main_pick_roms">Velg ROM-mappen</string> @@ -2461,10 +2418,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Sesjonsskjerm</string> - <string name="display_resolution">Oppløsning</string> + <string name="display_zero_copy">Presentasjon uten kopiering</string> + <string name="display_resolution_landscape">Oppløsning i liggende</string> + <string name="display_resolution_portrait">Oppløsning i stående</string> + <string name="display_follow_landscape">Følg liggende (%1$d×%2$d)</string> + <string name="display_follow_portrait">Følg stående (%1$d×%2$d)</string> <string name="display_game_fit">16:9-spilltilpasning</string> <string name="display_game_fit_hint">Hvordan 16:9-spill tilpasses denne skjermen. Fra neste sesjon.</string> <string name="display_game_fit_unavailable">Velg Tilpass skjerm eller en egendefinert størrelse smalere enn 16:9.</string> + <string name="display_avoid_notch">Unngå notch</string> + <string name="display_avoid_notch_hint">Holder bildet unna kamerautskjæringen. Gjelder når du går tilbake til økten.</string> <string name="display_preserve">Behold proporsjoner</string> <string name="display_stretch">Strekk til skjermen</string> <string name="display_image_scaling">Bildeskalering</string> @@ -2751,6 +2714,7 @@ <string name="stores_login_error_ssl">Tilkoblingen til innloggingssiden er ikke sikker.</string> <string name="stores_login_error_verification">Innloggingen kunne ikke verifiseres. Prøv igjen.</string> <string name="stores_login_error_generic">Innlogging mislyktes. Prøv igjen.</string> + <string name="stores_login_continue_in_browser">%1$s trenger ett trinn til. Fullfør det i nettleseren som ble åpnet, og prøv igjen.</string> <string name="common_close">Lukk</string> <string name="common_back">Tilbake</string> <string name="common_edit">Rediger</string> @@ -3135,7 +3099,7 @@ <string name="hand_camera_done">Ferdig</string> <string name="glasses_xreal_network_missing">Venter på USB Ethernet-tilkoblingen til brillene. Denne telefonen gjør den kanskje ikke tilgjengelig for apper.</string> <string name="glasses_xreal_connection_failed">XREAL-tilkoblingen ble avbrutt eller ga et svar som ikke støttes. Prøver igjen…</string> - <string name="glasses_xreal_experimental">Eksperimentell støtte for 1S. Bruk Follow-modus og slå av stabilisering i brillemenyen. Sporingsretninger og visningsmoduser må fortsatt testes på enheten.</string> + <string name="glasses_xreal_experimental">Eksperimentell støtte for XREAL 1S, One, One Pro, One Pro+ og Aura. Bruk Follow-modus og slå av stabilisering i brillemenyen; på Aura må du også slå av Spatial Anchor. Hodesporing og bytte mellom 2D/3D er testet på Aura og One Pro+.</string> <string name="glasses_pro2_experimental">Eksperimentell hodesporing for Pro 2. Justering av lysstyrke og volum samt bytte av visningsmodus støttes ikke ennå.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-modus</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">Mest nedlastet</string> <string name="addons_category_all">Alle kategorier</string> <string name="addons_none_found">Fant ingen tillegg</string> + <string name="addons_curse_busy">Lukk CurseForge først</string> <string name="addons_unreachable">Fikk ikke kontakt med %1$s</string> <string name="addons_no_file">Ingen fil for denne spillversjonen</string> <string name="input_reset_positions">Tilbakestill plasseringer</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">Uthevinger</string> <string name="theme_custom_good">Suksess</string> <string name="theme_custom_error">Feil</string> + <string name="hud_only_during_game">Vis HUD bare mens du spiller</string> + <string name="hud_only_during_game_hint">Skjul HUD når ingen spillbilder registreres.</string> </resources> diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 9151d3b212..b788d41499 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-uitvoer</string> <string name="mode_hdr_unavailable">Niet beschikbaar: %1$s.</string> - <string name="mode_hdr_restart">Start de app opnieuw om dit toe te passen.</string> <string name="mode_drivers">Drivers</string> <string name="mode_gpu_drivers">GPU-drivers</string> <string name="mode_gpu_drivers_hint">Gedeeld door Steam en Desktop. In te stellen op de pagina Componenten.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Opstarten</string> <string name="mode_startup_session">Openen bij start</string> <string name="mode_startup_session_hint">Start deze sessie wanneer DroidDeck start.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Zoeken naar releases…</string> <string name="mode_decky_ready">Klaar om %1$s te installeren.</string> <string name="mode_decky_none">Geen compatibele build gevonden. Probeer het later opnieuw.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Up-to-date · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Nieuwste installeren</string> - <string name="decky_channel">Updatekanaal</string> - <string name="decky_channel_hint">Welke Decky Loader-releases worden geïnstalleerd. De eigen updater van Decky gebruikt hetzelfde kanaal.</string> <string name="decky_channel_stable">Stabiel</string> <string name="decky_channel_prerelease">Voorlopige release</string> <string name="decky_channel_testing">Testversie</string> <string name="decky_channel_failed">Kan het Decky-updatekanaal niet opslaan</string> - <string name="mode_decky_on">Start met Steam. Zolang dit aan staat, kunnen andere apps op dit apparaat Steam mogelijk bedienen.</string> - <string name="mode_decky_off">Uit. De poort voor foutopsporing op afstand van Steam blijft dicht.</string> <string name="mode_decky_remove_title">Decky Loader verwijderen?</string> <string name="mode_decky_remove_text">Verwijdert de loader. Je plug-ins en instellingen blijven behouden.</string> <string name="mode_client">Client</string> @@ -953,13 +947,15 @@ <string name="setup_launcher_orientation_auto">Apparaatrotatie volgen</string> <string name="setup_orientation_portrait">Staand</string> <string name="setup_session_orientation">Oriëntatie van sessie</string> - <string name="setup_session_orientation_hint">Geldt voor Steam, games, desktop en de controllereditor. Resolutievoorinstellingen draaien mee met de sessie; aangepaste breedte en hoogte blijven zoals ingevoerd.</string> + <string name="setup_session_orientation_hint">Geldt voor Steam, games, desktop en de controllereditor. Resolutievoorinstellingen draaien mee met de sessie; als de ene oriëntatie de andere volgt, worden aangepaste breedte en hoogte omgewisseld.</string> <string name="setup_orientation_auto">Automatisch liggend</string> <string name="setup_orientation_landscape">Liggend</string> <string name="setup_orientation_reverse">Liggend omgekeerd</string> <string name="setup_fullscreen">Volledig scherm</string> <string name="setup_fullscreen_on">Verbergt de statusbalk en navigatiebalk van Android</string> <string name="setup_fullscreen_off">Toont de statusbalk en navigatiebalk van Android</string> + <string name="setup_page_swipe">Vegen tussen pagina\'s</string> + <string name="setup_page_swipe_hint">Veeg over een pagina om van tabblad te wisselen.</string> <string name="setup_dual_screen_launcher">Launcher op twee schermen</string> <string name="setup_dual_screen_launcher_hint">Automatisch zet de launchersecties (Steam, Bibliotheek, Winkels en de rest) op het tweede scherm van handhelds met een ingebouwd exemplaar. Aan gebruikt elk tweede scherm. Uit houdt de launcher op één scherm.</string> <string name="setup_dual_screen_sessions">Sessies op twee schermen</string> @@ -1280,8 +1276,6 @@ <string name="gate_open_dev">Opties voor ontwikkelaars openen</string> <string name="gate_no_toggle">Deze Android-versie heeft hiervoor geen schakelaar, dus wijzigt DroidDeck dit via Draadloos debuggen. Duurt ongeveer een minuut, geen computer nodig.</string> <string name="gate_needs_wifi">Draadloos debuggen heeft Wi-Fi nodig. Elk netwerk werkt; internet is niet vereist.</string> - <string name="gate_needs_notifications">De koppelingscode komt in een melding. Sta meldingen toe voor DroidDeck, of gebruik Andere manieren.</string> - <string name="gate_allow_notifications">Meldingen toestaan</string> <string name="gate_step1">Open Instellingen → Opties voor ontwikkelaars → Draadloos debuggen en zet het aan</string> <string name="gate_step2">Tik op “Apparaat koppelen met koppelingscode”</string> <string name="gate_step3">Voer de code in bij de melding van DroidDeck</string> @@ -1298,48 +1292,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Controleert elke 2 seconden. Deze pagina sluit zodra het uit staat.</string> <string name="gate_other_ways">Andere manieren</string> - <string name="gate_other_toggle">Draadloos debuggen, handmatig adres, computer-ADB</string> - <string name="gate_other_no_toggle">Handmatig adres, computer-ADB, Opties voor ontwikkelaars</string> <string name="gate_use_wireless_instead">Gebruik Draadloos debuggen in plaats daarvan</string> <string name="gate_some_roms">Sommige ROMs voegen de schakelaar toch toe. Zoek naar “subproces” in Opties voor ontwikkelaars.</string> - <string name="gate_manual_hint">Als de melding niet werkt, voer je het adres en de code van de pop-up zelf in.</string> - <string name="gate_enter_manually">Adres handmatig invoeren</string> <string name="gate_from_computer">Vanaf een computer met ADB:</string> <string name="gate_copy_command">Opdracht kopiëren</string> <string name="gate_sidequest_steps">Sluit de headset aan op een computer en open SideQuest. Kies ‘Run ADB Command’ en dan ‘Custom Command’, typ de hieronder getoonde opdracht en selecteer ‘Run Command’.</string> <string name="gate_choose_display">Kies op welk scherm Android-instellingen wordt geopend.</string> <string name="gate_main_screen">Hoofdscherm</string> - <string name="wadb_finding_port">Gekoppeld. Poort van Draadloos debuggen zoeken…</string> - <string name="wadb_enter_port">Gekoppeld. Voer de poort uit Instellingen in.</string> - <string name="wadb_applying">Apparaat gevonden. Instelling toepassen…</string> - <string name="wadb_apply_failed">Kan niet automatisch worden toegepast. Controleer het adres hieronder en probeer het opnieuw. %1$s</string> - <string name="wadb_title_wireless">Draadloos debuggen</string> - <string name="wadb_title_done">Limiet voor subprocessen bijgewerkt</string> - <string name="wadb_title">De limiet voor subprocessen wijzigen</string> - <string name="wadb_lede_compact0">Als de optie ontbreekt, koppel dan via Draadloos debuggen.</string> - <string name="wadb_lede_compact1">Gekoppeld. Controleer het IP-adres en de poort in Draadloos debuggen.</string> - <string name="wadb_lede_done">De limiet voor subprocessen is bijgewerkt.</string> - <string name="wadb_lede0">Gebruik stap 2 als Opties voor ontwikkelaars geen instelling voor subprocessen heeft. Open Opties voor ontwikkelaars → Draadloos debuggen → Apparaat koppelen met koppelingscode.</string> - <string name="wadb_lede1">Gekoppeld. Gebruik het adres hieronder, of werk het bij via Draadloos debuggen → IP-adres & Poort.</string> - <string name="wadb_lede_done_long">De limiet voor subprocessen is bijgewerkt via Draadloos debuggen.</string> - <string name="wadb_confirmed_on">Android heeft bevestigd dat de limiet aan staat.</string> - <string name="wadb_confirmed_off">Android heeft bevestigd dat de limiet uit staat.</string> - <string name="wadb_pair_group">2 · Draadloos debuggen koppelen</string> - <string name="wadb_pair_address">IP-adres & poort van de koppelingspop-up</string> - <string name="wadb_pin">Koppelingscode (pincode)</string> - <string name="wadb_pin_placeholder">6 cijfers</string> - <string name="wadb_pair">Koppelen</string> - <string name="wadb_apply_group">2 · Toepassen via Draadloos debuggen</string> - <string name="wadb_connect_address">IP-adres & poort van de verbinding</string> - <string name="wadb_pair_again">Opnieuw koppelen</string> - <string name="wadb_turn_off">Limiet uitschakelen</string> - <string name="wadb_other_ways">Andere manieren om dit te wijzigen</string> - <string name="wadb_dev_try_first">1 · Opties voor ontwikkelaars (probeer dit eerst)</string> - <string name="wadb_restrict_on">Zet “Beperkingen voor onderliggende processen uitzetten” uit.</string> - <string name="wadb_restrict_off">Zet “Beperkingen voor onderliggende processen uitzetten” aan.</string> - <string name="wadb_computer_last">3 · Computer-ADB (laatste redmiddel)</string> - <string name="wadb_only_if">Alleen als Draadloos debuggen niet beschikbaar is.</string> - <string name="wadb_computer_group">3 · Computer-ADB (laatste redmiddel)</string> <string name="ctrl_color">Kleur</string> <string name="ctrl_custom">Aangepast</string> <string name="ctrl_opacity">Transparantie</string> @@ -1627,8 +1586,6 @@ <item quantity="one">%1$d map met sessielogs gewist.</item> <item quantity="other">%1$d mappen met sessielogs gewist.</item> </plurals> - <string name="main_wadb_pair_failed">Koppelen voor draadloze foutopsporing mislukt</string> - <string name="main_wadb_command_failed">Opdracht voor draadloze foutopsporing mislukt</string> <string name="main_wadb_unavailable">Draadloze foutopsporing is niet beschikbaar</string> <string name="main_adb_copied">ADB-opdracht gekopieerd</string> <string name="main_pick_roms">Kies de ROM-map</string> @@ -2461,10 +2418,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Sessiescherm</string> - <string name="display_resolution">Resolutie</string> + <string name="display_zero_copy">Weergave zonder kopie</string> + <string name="display_resolution_landscape">Resolutie in liggend</string> + <string name="display_resolution_portrait">Resolutie in staand</string> + <string name="display_follow_landscape">Volg liggend (%1$d×%2$d)</string> + <string name="display_follow_portrait">Volg staand (%1$d×%2$d)</string> <string name="display_game_fit">16:9-beeldvulling</string> <string name="display_game_fit_hint">Hoe 16:9-games dit scherm vullen. Volgende sessie.</string> <string name="display_game_fit_unavailable">Kies Schermformaat of een aangepast formaat dat smaller is dan 16:9.</string> + <string name="display_avoid_notch">Notch vermijden</string> + <string name="display_avoid_notch_hint">Houdt het beeld buiten de camerauitsparing. Geldt zodra je terugkeert naar de sessie.</string> <string name="display_preserve">Beeldverhouding behouden</string> <string name="display_stretch">Uitrekken naar scherm</string> <string name="display_image_scaling">Beeldschaling</string> @@ -2751,6 +2714,7 @@ <string name="stores_login_error_ssl">De verbinding met de aanmeldpagina is niet beveiligd.</string> <string name="stores_login_error_verification">De aanmelding kon niet worden geverifieerd. Probeer het opnieuw.</string> <string name="stores_login_error_generic">Aanmelden mislukt. Probeer het opnieuw.</string> + <string name="stores_login_continue_in_browser">%1$s vraagt nog één stap. Rond die af in de browser die is geopend en probeer het opnieuw.</string> <string name="common_close">Sluiten</string> <string name="common_back">Terug</string> <string name="common_edit">Bewerken</string> @@ -3135,7 +3099,7 @@ <string name="hand_camera_done">Klaar</string> <string name="glasses_xreal_network_missing">Wachten op de USB Ethernet-verbinding van de bril. Deze telefoon maakt die mogelijk niet beschikbaar voor apps.</string> <string name="glasses_xreal_connection_failed">De XREAL-verbinding is onderbroken of gaf een niet-ondersteund antwoord. Opnieuw proberen…</string> - <string name="glasses_xreal_experimental">Experimentele ondersteuning voor 1S. Gebruik de Follow-modus en schakel stabilisatie uit in het menu van de bril. Trackingrichtingen en weergavemodi moeten nog op een apparaat worden getest.</string> + <string name="glasses_xreal_experimental">Experimentele ondersteuning voor XREAL 1S, One, One Pro, One Pro+ en Aura. Gebruik de Follow-modus en schakel stabilisatie uit in het menu van de bril; schakel op de Aura ook Spatial Anchor uit. Hoofdtracking en schakelen tussen 2D/3D zijn getest op de Aura en One Pro+.</string> <string name="glasses_pro2_experimental">Experimentele hoofdtracking voor Pro 2. Het aanpassen van helderheid en volume en het wisselen van weergavemodus worden nog niet ondersteund.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-modus</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">Meest gedownload</string> <string name="addons_category_all">Alle categorieën</string> <string name="addons_none_found">Geen add-ons gevonden</string> + <string name="addons_curse_busy">Sluit eerst CurseForge</string> <string name="addons_unreachable">Kan %1$s niet bereiken</string> <string name="addons_no_file">Geen bestand voor deze gameversie</string> <string name="input_reset_positions">Posities herstellen</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">Accenten</string> <string name="theme_custom_good">Geslaagd</string> <string name="theme_custom_error">Fout</string> + <string name="hud_only_during_game">HUD alleen tijdens een game weergeven</string> + <string name="hud_only_during_game_hint">Verberg de HUD wanneer er geen gameframes worden gedetecteerd.</string> </resources> diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 31742655ac..59fadab554 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Wyjście HDR10</string> <string name="mode_hdr_unavailable">Niedostępne: %1$s.</string> - <string name="mode_hdr_restart">Uruchom ponownie aplikację, aby zastosować.</string> <string name="mode_drivers">Sterowniki</string> <string name="mode_gpu_drivers">Sterowniki GPU</string> <string name="mode_gpu_drivers_hint">Wspólne dla Steam i pulpitu. Ustawiane na stronie Komponenty.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Uruchamianie</string> <string name="mode_startup_session">Otwórz przy uruchomieniu</string> <string name="mode_startup_session_hint">Uruchamia tę sesję po uruchomieniu DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Sprawdzanie wydań…</string> <string name="mode_decky_ready">Gotowe do instalacji: %1$s.</string> <string name="mode_decky_none">Nie znaleziono zgodnej wersji. Spróbuj ponownie później.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Aktualna · %1$s</string> <string name="mode_decky_loader">Program ładujący</string> <string name="mode_decky_install_latest">Zainstaluj najnowszą</string> - <string name="decky_channel">Kanał aktualizacji</string> - <string name="decky_channel_hint">Które wydania Decky Loader instalować. Wbudowany aktualizator Decky używa tego samego kanału.</string> <string name="decky_channel_stable">Stabilny</string> <string name="decky_channel_prerelease">Przedpremierowy</string> <string name="decky_channel_testing">Testowy</string> <string name="decky_channel_failed">Nie udało się zapisać kanału aktualizacji Decky</string> - <string name="mode_decky_on">Uruchamia się ze Steam. Gdy jest włączony, inne aplikacje na tym urządzeniu mogą sterować Steam.</string> - <string name="mode_decky_off">Wyłączony. Port zdalnego debugowania Steam pozostaje zamknięty.</string> <string name="mode_decky_remove_title">Odinstalować Decky Loader?</string> <string name="mode_decky_remove_text">Usuwa program ładujący. Twoje wtyczki i ustawienia zostaną zachowane.</string> <string name="mode_client">Klient</string> @@ -959,13 +953,15 @@ <string name="setup_launcher_orientation_auto">Zgodnie z obrotem urządzenia</string> <string name="setup_orientation_portrait">Pionowa</string> <string name="setup_session_orientation">Orientacja sesji</string> - <string name="setup_session_orientation_hint">Dotyczy Steam, gier, pulpitu i edytora kontrolera. Presety rozdzielczości obracają się z sesją; własna szerokość i wysokość pozostają jak wpisano.</string> + <string name="setup_session_orientation_hint">Dotyczy Steam, gier, pulpitu i edytora kontrolera. Presety rozdzielczości obracają się z sesją; gdy jedna orientacja podąża za drugą, własna szerokość i wysokość są zamieniane.</string> <string name="setup_orientation_auto">Automatyczna pozioma</string> <string name="setup_orientation_landscape">Pozioma</string> <string name="setup_orientation_reverse">Odwrócona pozioma</string> <string name="setup_fullscreen">Pełny ekran</string> <string name="setup_fullscreen_on">Ukrywa systemowe paski stanu i nawigacji</string> <string name="setup_fullscreen_off">Pokazuje systemowe paski stanu i nawigacji</string> + <string name="setup_page_swipe">Przesuwanie między stronami</string> + <string name="setup_page_swipe_hint">Przesuń palcem po stronie, aby zmienić kartę.</string> <string name="setup_dual_screen_launcher">Launcher na dwóch ekranach</string> <string name="setup_dual_screen_launcher_hint">Automatycznie umieszcza sekcje launchera (Steam, Biblioteka, Sklepy i pozostałe) na wbudowanym drugim ekranie konsol przenośnych. Włączone używa dowolnego drugiego wyświetlacza. Wyłączone pozostawia launcher na jednym ekranie.</string> <string name="setup_dual_screen_sessions">Sesje na dwóch ekranach</string> @@ -1294,8 +1290,6 @@ <string name="gate_open_dev">Otwórz Opcje programisty</string> <string name="gate_no_toggle">Ta wersja Androida nie ma dla tego przełącznika, więc DroidDeck zmienia go przez debugowanie bezprzewodowe. Zajmuje to około minuty, bez potrzeby komputera.</string> <string name="gate_needs_wifi">Debugowanie bezprzewodowe wymaga Wi-Fi. Działa każda sieć; nie musi mieć internetu.</string> - <string name="gate_needs_notifications">Kod parowania pojawia się w powiadomieniu. Zezwól DroidDeck na powiadomienia albo użyj sekcji „Inne sposoby”.</string> - <string name="gate_allow_notifications">Zezwól na powiadomienia</string> <string name="gate_step1">Otwórz Ustawienia → Opcje programisty → Debugowanie bezprzewodowe i włącz je</string> <string name="gate_step2">Dotknij „Sparuj urządzenie za pomocą kodu parowania”</string> <string name="gate_step3">Wpisz kod w powiadomieniu DroidDeck</string> @@ -1312,48 +1306,13 @@ <string name="gate_status">Stan</string> <string name="gate_polling">Sprawdzanie co 2 sekundy. Ta strona zamknie się, gdy przełącznik będzie wyłączony.</string> <string name="gate_other_ways">Inne sposoby</string> - <string name="gate_other_toggle">Debugowanie bezprzewodowe, adres ręczny, komputer z ADB</string> - <string name="gate_other_no_toggle">Adres ręczny, komputer z ADB, Opcje programisty</string> <string name="gate_use_wireless_instead">Użyj za to debugowania bezprzewodowego</string> <string name="gate_some_roms">Niektóre ROM-y dodają ten przełącznik mimo to. Poszukaj „child process” w Opcjach programisty.</string> - <string name="gate_manual_hint">Jeśli powiadomienie nie działa, wpisz adres i kod z okienka samodzielnie.</string> - <string name="gate_enter_manually">Wpisz adres ręcznie</string> <string name="gate_from_computer">Z komputera z ADB:</string> <string name="gate_copy_command">Kopiuj polecenie</string> <string name="gate_sidequest_steps">Podłącz gogle do komputera i otwórz SideQuest. Wybierz „Run ADB Command”, potem „Custom Command”, wpisz polecenie widoczne poniżej i wybierz „Run Command”.</string> <string name="gate_choose_display">Wybierz, na którym ekranie otworzyć Ustawienia Androida.</string> <string name="gate_main_screen">Ekran główny</string> - <string name="wadb_finding_port">Sparowano. Wyszukiwanie portu debugowania bezprzewodowego…</string> - <string name="wadb_enter_port">Sparowano. Wpisz port z Ustawień.</string> - <string name="wadb_applying">Znaleziono urządzenie. Stosowanie ustawienia…</string> - <string name="wadb_apply_failed">Nie udało się zastosować automatycznie. Sprawdź adres poniżej i spróbuj ponownie. %1$s</string> - <string name="wadb_title_wireless">Debugowanie bezprzewodowe</string> - <string name="wadb_title_done">Limit procesów podrzędnych zmieniony</string> - <string name="wadb_title">Zmień limit procesów podrzędnych</string> - <string name="wadb_lede_compact0">Jeśli opcja jest niedostępna, sparuj przez debugowanie bezprzewodowe.</string> - <string name="wadb_lede_compact1">Sparowano. Sprawdź adres IP i port w Debugowaniu bezprzewodowym.</string> - <string name="wadb_lede_done">Limit procesów podrzędnych został zmieniony.</string> - <string name="wadb_lede0">Użyj kroku 2, jeśli Opcje programisty nie mają ustawienia procesów podrzędnych. Otwórz Opcje programisty → Debugowanie bezprzewodowe → Sparuj urządzenie za pomocą kodu parowania.</string> - <string name="wadb_lede1">Sparowano. Użyj adresu poniżej lub zaktualizuj go z Debugowanie bezprzewodowe → Adres IP i port.</string> - <string name="wadb_lede_done_long">Limit procesów podrzędnych został zmieniony przez debugowanie bezprzewodowe.</string> - <string name="wadb_confirmed_on">Android potwierdził, że limit jest włączony.</string> - <string name="wadb_confirmed_off">Android potwierdził, że limit jest wyłączony.</string> - <string name="wadb_pair_group">2 · Sparuj debugowanie bezprzewodowe</string> - <string name="wadb_pair_address">Adres IP i port okienka parowania</string> - <string name="wadb_pin">Kod parowania (PIN)</string> - <string name="wadb_pin_placeholder">6 cyfr</string> - <string name="wadb_pair">Sparuj</string> - <string name="wadb_apply_group">2 · Zastosuj przez debugowanie bezprzewodowe</string> - <string name="wadb_connect_address">Adres IP i port połączenia</string> - <string name="wadb_pair_again">Sparuj ponownie</string> - <string name="wadb_turn_off">Wyłącz limit</string> - <string name="wadb_other_ways">Inne sposoby na zmianę tego</string> - <string name="wadb_dev_try_first">1 · Opcje programisty (spróbuj najpierw)</string> - <string name="wadb_restrict_on">Ustaw „Wyłącz ograniczenia procesów podrzędnych aplikacji” na wyłączone.</string> - <string name="wadb_restrict_off">Ustaw „Wyłącz ograniczenia procesów podrzędnych aplikacji” na włączone.</string> - <string name="wadb_computer_last">3 · Komputer z ADB (ostatnia opcja)</string> - <string name="wadb_only_if">Tylko jeśli debugowanie bezprzewodowe jest niedostępne.</string> - <string name="wadb_computer_group">3 · Komputer z ADB (ostatnia opcja)</string> <string name="ctrl_color">Kolor</string> <string name="ctrl_custom">Własny</string> <string name="ctrl_opacity">Przezroczystość</string> @@ -1653,8 +1612,6 @@ <item quantity="many">Wyczyszczono %1$d folderów logów sesji.</item> <item quantity="other">Wyczyszczono %1$d folderu logów sesji.</item> </plurals> - <string name="main_wadb_pair_failed">Parowanie przez debugowanie bezprzewodowe nie powiodło się</string> - <string name="main_wadb_command_failed">Polecenie debugowania bezprzewodowego nie powiodło się</string> <string name="main_wadb_unavailable">Debugowanie bezprzewodowe jest niedostępne</string> <string name="main_adb_copied">Skopiowano polecenie ADB</string> <string name="main_pick_roms">Wybierz folder ROM-ów</string> @@ -2513,10 +2470,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Ekran sesji</string> - <string name="display_resolution">Rozdzielczość</string> + <string name="display_zero_copy">Prezentacja bez kopiowania</string> + <string name="display_resolution_landscape">Rozdzielczość w poziomie</string> + <string name="display_resolution_portrait">Rozdzielczość w pionie</string> + <string name="display_follow_landscape">Jak w poziomie (%1$d×%2$d)</string> + <string name="display_follow_portrait">Jak w pionie (%1$d×%2$d)</string> <string name="display_game_fit">Dopasowanie gier 16:9</string> <string name="display_game_fit_hint">Jak gry 16:9 mieszczą się na tym ekranie. Od następnej sesji.</string> <string name="display_game_fit_unavailable">Wybierz „Dopasuj do ekranu” lub własny rozmiar węższy niż 16:9.</string> + <string name="display_avoid_notch">Omijaj notch</string> + <string name="display_avoid_notch_hint">Utrzymuje obraz poza wycięciem na aparat. Działa po powrocie do sesji.</string> <string name="display_preserve">Zachowaj proporcje</string> <string name="display_stretch">Rozciągnij do ekranu</string> <string name="display_image_scaling">Skalowanie obrazu</string> @@ -2803,6 +2766,7 @@ <string name="stores_login_error_ssl">Połączenie ze stroną logowania nie jest bezpieczne.</string> <string name="stores_login_error_verification">Nie udało się zweryfikować logowania. Spróbuj ponownie.</string> <string name="stores_login_error_generic">Logowanie nie powiodło się. Spróbuj ponownie.</string> + <string name="stores_login_continue_in_browser">%1$s wymaga jeszcze jednego kroku. Dokończ go w otwartej przeglądarce, a potem spróbuj ponownie.</string> <string name="common_close">Zamknij</string> <string name="common_back">Wstecz</string> <string name="common_edit">Edytuj</string> @@ -3195,7 +3159,7 @@ <string name="hand_camera_done">Gotowe</string> <string name="glasses_xreal_network_missing">Oczekiwanie na połączenie USB Ethernet okularów. Ten telefon może nie udostępniać go aplikacjom.</string> <string name="glasses_xreal_connection_failed">Połączenie z XREAL zostało przerwane lub zwróciło nieobsługiwaną odpowiedź. Ponawianie…</string> - <string name="glasses_xreal_experimental">Eksperymentalna obsługa 1S. Użyj trybu Follow i wyłącz stabilizację w menu okularów. Kierunki śledzenia i tryby wyświetlania wymagają jeszcze testów na urządzeniu.</string> + <string name="glasses_xreal_experimental">Eksperymentalna obsługa XREAL 1S, One, One Pro, One Pro+ i Aura. Użyj trybu Follow i wyłącz stabilizację w menu okularów; na Aura wyłącz też Spatial Anchor. Śledzenie głowy i przełączanie między 2D/3D przetestowano na Aura i One Pro+.</string> <string name="glasses_pro2_experimental">Eksperymentalne śledzenie ruchów głowy dla Pro 2. Regulacja jasności i głośności oraz przełączanie trybu wyświetlania nie są jeszcze obsługiwane.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Tryb Cardboard</string> @@ -4090,6 +4054,7 @@ <string name="addons_sort_downloads">Najczęściej pobierane</string> <string name="addons_category_all">Wszystkie kategorie</string> <string name="addons_none_found">Nie znaleziono dodatków</string> + <string name="addons_curse_busy">Najpierw zamknij CurseForge</string> <string name="addons_unreachable">Nie można połączyć się z %1$s</string> <string name="addons_no_file">Brak pliku dla tej wersji gry</string> <string name="input_reset_positions">Resetuj położenie</string> @@ -4193,4 +4158,6 @@ <string name="theme_custom_signal">Wyróżnienia</string> <string name="theme_custom_good">Sukces</string> <string name="theme_custom_error">Błąd</string> + <string name="hud_only_during_game">Pokazuj HUD tylko podczas gry</string> + <string name="hud_only_during_game_hint">Ukryj HUD, gdy nie wykryto klatek gry.</string> </resources> diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index a5745195b4..5e1f62f5d1 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Saída HDR10</string> <string name="mode_hdr_unavailable">Indisponível: %1$s.</string> - <string name="mode_hdr_restart">Reinicie a app para aplicar.</string> <string name="mode_drivers">Controladores</string> <string name="mode_gpu_drivers">Controladores da GPU</string> <string name="mode_gpu_drivers_hint">Partilhados pelo Steam e pelo Ambiente de trabalho. Defina-os na página Componentes.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Arranque</string> <string name="mode_startup_session">Abrir ao iniciar</string> <string name="mode_startup_session_hint">Inicia esta sessão quando o DroidDeck é aberto.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">A procurar versões…</string> <string name="mode_decky_ready">Pronto para instalar %1$s.</string> <string name="mode_decky_none">Nenhuma versão compatível encontrada. Tente novamente mais tarde.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Atualizado · %1$s</string> <string name="mode_decky_loader">Carregador</string> <string name="mode_decky_install_latest">Instalar a versão mais recente</string> - <string name="decky_channel">Canal de atualização</string> - <string name="decky_channel_hint">Que versões do Decky Loader instalar. O atualizador do próprio Decky utiliza o mesmo canal.</string> <string name="decky_channel_stable">Estável</string> <string name="decky_channel_prerelease">Pré-lançamento</string> <string name="decky_channel_testing">Testes</string> <string name="decky_channel_failed">Não foi possível guardar o canal de atualização do Decky</string> - <string name="mode_decky_on">Inicia com o Steam. Enquanto estiver ligado, outras apps neste dispositivo poderão controlar o Steam.</string> - <string name="mode_decky_off">Desligado. A porta de depuração remota do Steam mantém-se fechada.</string> <string name="mode_decky_remove_title">Desinstalar o Decky Loader?</string> <string name="mode_decky_remove_text">Remove o carregador. Os seus plugins e definições são mantidos.</string> <string name="mode_client">Cliente</string> @@ -948,13 +942,15 @@ <string name="setup_launcher_orientation_auto">Seguir a rotação do dispositivo</string> <string name="setup_orientation_portrait">Vertical</string> <string name="setup_session_orientation">Orientação da sessão</string> - <string name="setup_session_orientation_hint">Aplica-se ao Steam, aos jogos, ao ambiente de trabalho e ao editor de comandos. As predefinições de resolução rodam com a sessão; a largura e a altura personalizadas ficam como foram introduzidas.</string> + <string name="setup_session_orientation_hint">Aplica-se ao Steam, aos jogos, ao ambiente de trabalho e ao editor de comandos. As predefinições de resolução rodam com a sessão; quando uma orientação segue a outra, a largura e a altura personalizadas são trocadas para corresponder.</string> <string name="setup_orientation_auto">Horizontal automática</string> <string name="setup_orientation_landscape">Horizontal</string> <string name="setup_orientation_reverse">Horizontal invertida</string> <string name="setup_fullscreen">Ecrã inteiro</string> <string name="setup_fullscreen_on">Oculta as barras de estado e de navegação do Android</string> <string name="setup_fullscreen_off">Mostra as barras de estado e de navegação do Android</string> + <string name="setup_page_swipe">Deslizar entre páginas</string> + <string name="setup_page_swipe_hint">Deslize sobre uma página para mudar de separador.</string> <string name="setup_dual_screen_launcher">Iniciador de ecrã duplo</string> <string name="setup_dual_screen_launcher_hint">Automático coloca as secções do iniciador (Steam, Biblioteca, Lojas e as restantes) no segundo ecrã das consolas portáteis com um segundo ecrã integrado. Ativado utiliza qualquer segundo ecrã. Desativado mantém o iniciador num único ecrã.</string> <string name="setup_dual_screen_sessions">Sessões de ecrã duplo</string> @@ -1278,8 +1274,6 @@ <string name="gate_open_dev">Abrir Opções de programador</string> <string name="gate_no_toggle">Esta versão do Android não tem um interruptor para isto, por isso o DroidDeck altera-o através da Depuração sem fios. Demora cerca de um minuto e não é preciso computador.</string> <string name="gate_needs_wifi">A Depuração sem fios requer Wi-Fi. Qualquer rede serve; não precisa de Internet.</string> - <string name="gate_needs_notifications">O código de sincronização é introduzido numa notificação. Permita as notificações do DroidDeck ou utilize Outras formas.</string> - <string name="gate_allow_notifications">Permitir notificações</string> <string name="gate_step1">Abra Definições → Opções de programador → Depuração sem fios e ative-a</string> <string name="gate_step2">Toque em “Sincronizar dispositivo com código de sincronização”</string> <string name="gate_step3">Escreva o código na notificação do DroidDeck</string> @@ -1296,48 +1290,13 @@ <string name="gate_status">Estado</string> <string name="gate_polling">A verificar a cada 2 segundos. Esta página fecha-se quando estiver desativado.</string> <string name="gate_other_ways">Outras formas</string> - <string name="gate_other_toggle">Depuração sem fios, endereço manual, ADB num computador</string> - <string name="gate_other_no_toggle">Endereço manual, ADB num computador, Opções de programador</string> <string name="gate_use_wireless_instead">Utilizar antes a Depuração sem fios</string> <string name="gate_some_roms">Algumas ROMs adicionam o interruptor mesmo assim. Procure “processos secundários” nas Opções de programador.</string> - <string name="gate_manual_hint">Se a notificação não funcionar, introduza manualmente o endereço e o código da janela.</string> - <string name="gate_enter_manually">Introduzir endereço manualmente</string> <string name="gate_from_computer">A partir de um computador com ADB:</string> <string name="gate_copy_command">Copiar comando</string> <string name="gate_sidequest_steps">Ligue os óculos a um computador e abra o SideQuest. Escolha “Run ADB Command”, depois “Custom Command”, escreva o comando apresentado abaixo e selecione “Run Command”.</string> <string name="gate_choose_display">Escolha em que ecrã abrir as Definições do Android.</string> <string name="gate_main_screen">Ecrã principal</string> - <string name="wadb_finding_port">Sincronizado. A procurar a porta da Depuração sem fios…</string> - <string name="wadb_enter_port">Sincronizado. Introduza a porta indicada nas Definições.</string> - <string name="wadb_applying">Dispositivo encontrado. A aplicar a definição…</string> - <string name="wadb_apply_failed">Não foi possível aplicar automaticamente. Verifique o endereço abaixo e tente novamente. %1$s</string> - <string name="wadb_title_wireless">Depuração sem fios</string> - <string name="wadb_title_done">Limite de processos secundários atualizado</string> - <string name="wadb_title">Alterar o limite de processos secundários</string> - <string name="wadb_lede_compact0">Se a opção não existir, sincronize através da Depuração sem fios.</string> - <string name="wadb_lede_compact1">Sincronizado. Verifique o endereço IP e a porta na Depuração sem fios.</string> - <string name="wadb_lede_done">O limite de processos secundários foi atualizado.</string> - <string name="wadb_lede0">Utilize o passo 2 se as Opções de programador não tiverem a definição de processos secundários. Abra Opções de programador → Depuração sem fios → Sincronizar dispositivo com código de sincronização.</string> - <string name="wadb_lede1">Sincronizado. Utilize o endereço abaixo ou atualize-o em Depuração sem fios → Endereço IP e porta.</string> - <string name="wadb_lede_done_long">O limite de processos secundários foi atualizado através da Depuração sem fios.</string> - <string name="wadb_confirmed_on">O Android confirmou que o limite está ativado.</string> - <string name="wadb_confirmed_off">O Android confirmou que o limite está desativado.</string> - <string name="wadb_pair_group">2 · Sincronizar a Depuração sem fios</string> - <string name="wadb_pair_address">Endereço IP e porta da janela de sincronização</string> - <string name="wadb_pin">Código de sincronização (PIN)</string> - <string name="wadb_pin_placeholder">6 dígitos</string> - <string name="wadb_pair">Sincronizar</string> - <string name="wadb_apply_group">2 · Aplicar através da Depuração sem fios</string> - <string name="wadb_connect_address">Endereço IP e porta de ligação</string> - <string name="wadb_pair_again">Sincronizar novamente</string> - <string name="wadb_turn_off">Desativar limite</string> - <string name="wadb_other_ways">Outras formas de o alterar</string> - <string name="wadb_dev_try_first">1 · Opções de programador (tente primeiro)</string> - <string name="wadb_restrict_on">Desative “Desativar restrições de processos secundários”.</string> - <string name="wadb_restrict_off">Ative “Desativar restrições de processos secundários”.</string> - <string name="wadb_computer_last">3 · ADB num computador (último recurso)</string> - <string name="wadb_only_if">Apenas se a Depuração sem fios não estiver disponível.</string> - <string name="wadb_computer_group">3 · ADB num computador (último recurso)</string> <string name="ctrl_color">Cor</string> <string name="ctrl_custom">Personalizada</string> <string name="ctrl_opacity">Opacidade</string> @@ -1631,8 +1590,6 @@ <item quantity="many">Foram limpas %1$d pastas de registos de sessão.</item> <item quantity="other">Foram limpas %1$d pastas de registos de sessão.</item> </plurals> - <string name="main_wadb_pair_failed">Falha na sincronização da depuração sem fios</string> - <string name="main_wadb_command_failed">Falha no comando de depuração sem fios</string> <string name="main_wadb_unavailable">A depuração sem fios não está disponível</string> <string name="main_adb_copied">Comando ADB copiado</string> <string name="main_pick_roms">Escolha a pasta de ROMs</string> @@ -2492,10 +2449,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Ecrã da sessão</string> - <string name="display_resolution">Resolução</string> + <string name="display_zero_copy">Apresentação sem cópia</string> + <string name="display_resolution_landscape">Resolução na horizontal</string> + <string name="display_resolution_portrait">Resolução na vertical</string> + <string name="display_follow_landscape">Igual à horizontal (%1$d×%2$d)</string> + <string name="display_follow_portrait">Igual à vertical (%1$d×%2$d)</string> <string name="display_game_fit">Ajuste de jogos 16:9</string> <string name="display_game_fit_hint">Como os jogos 16:9 se ajustam a este ecrã. Próxima sessão.</string> <string name="display_game_fit_unavailable">Escolha «Igual ao ecrã» ou um tamanho personalizado mais estreito do que 16:9.</string> + <string name="display_avoid_notch">Evitar o entalhe</string> + <string name="display_avoid_notch_hint">Mantém a imagem fora do recorte da câmara. Aplica-se ao voltar à sessão.</string> <string name="display_preserve">Manter proporções</string> <string name="display_stretch">Esticar até ao ecrã</string> <string name="display_image_scaling">Escala da imagem</string> @@ -2779,6 +2742,7 @@ <string name="stores_login_error_ssl">A ligação à página de início de sessão não é segura.</string> <string name="stores_login_error_verification">Não foi possível verificar o início de sessão. Tente novamente.</string> <string name="stores_login_error_generic">Falha no início de sessão. Tente novamente.</string> + <string name="stores_login_continue_in_browser">%1$s precisa de mais um passo. Conclua-o no navegador que foi aberto e tente novamente.</string> <string name="common_close">Fechar</string> <string name="common_back">Voltar</string> <string name="common_edit">Editar</string> @@ -3167,7 +3131,7 @@ <string name="hand_camera_done">Concluído</string> <string name="glasses_xreal_network_missing">A aguardar a ligação Ethernet por USB dos óculos. Este telemóvel pode não a disponibilizar às apps.</string> <string name="glasses_xreal_connection_failed">A ligação aos óculos XREAL foi interrompida ou devolveu uma resposta não suportada. A tentar novamente…</string> - <string name="glasses_xreal_experimental">Suporte experimental para os 1S. Utilize o modo Follow e desative a estabilização no menu dos óculos. As direções de seguimento e os modos de ecrã ainda têm de ser testados no dispositivo.</string> + <string name="glasses_xreal_experimental">Suporte experimental para XREAL 1S, One, One Pro, One Pro+ e Aura. Utilize o modo Follow e desative a estabilização no menu dos óculos; no Aura, desative também Spatial Anchor. O seguimento da cabeça e a alternância entre 2D/3D foram testados nos modelos Aura e One Pro+.</string> <string name="glasses_pro2_experimental">Seguimento experimental dos movimentos da cabeça para Pro 2. O ajuste do brilho e do volume e a mudança do modo de ecrã ainda não são suportados.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Modo Cardboard</string> @@ -4063,6 +4027,7 @@ <string name="addons_sort_downloads">Mais transferidos</string> <string name="addons_category_all">Todas as categorias</string> <string name="addons_none_found">Nenhum addon encontrado</string> + <string name="addons_curse_busy">Feche primeiro o CurseForge</string> <string name="addons_unreachable">Não foi possível contactar %1$s</string> <string name="addons_no_file">Não há ficheiro para esta versão do jogo</string> <string name="input_reset_positions">Repor posições</string> @@ -4152,4 +4117,6 @@ <string name="display_scaling_integer">Inteiro</string> <string name="display_scaling_fit">Ajustar</string> <string name="drawer_antialiasing">Suavização de serrilhado</string> + <string name="hud_only_during_game">Mostrar o HUD apenas durante um jogo</string> + <string name="hud_only_during_game_hint">Ocultar o HUD quando não forem detetados fotogramas do jogo.</string> </resources> diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index f5eca4b046..6372234699 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Saída HDR10</string> <string name="mode_hdr_unavailable">Indisponível: %1$s.</string> - <string name="mode_hdr_restart">Reinicie o app para aplicar.</string> <string name="mode_drivers">Drivers</string> <string name="mode_gpu_drivers">Drivers de GPU</string> <string name="mode_gpu_drivers_hint">Compartilhados pela Steam e pela Área de trabalho. Defina na página Componentes.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Inicialização</string> <string name="mode_startup_session">Abrir ao iniciar</string> <string name="mode_startup_session_hint">Inicia esta sessão quando o DroidDeck é aberto.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Procurando versões…</string> <string name="mode_decky_ready">Pronto para instalar %1$s.</string> <string name="mode_decky_none">Nenhuma versão compatível encontrada. Tente novamente mais tarde.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Atualizado · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Instalar a mais recente</string> - <string name="decky_channel">Canal de atualização</string> - <string name="decky_channel_hint">Quais versões do Decky Loader instalar. O atualizador do próprio Decky usa o mesmo canal.</string> <string name="decky_channel_stable">Estável</string> <string name="decky_channel_prerelease">Pré-lançamento</string> <string name="decky_channel_testing">Testes</string> <string name="decky_channel_failed">Não foi possível salvar o canal de atualização do Decky</string> - <string name="mode_decky_on">Inicia com a Steam. Enquanto estiver ativado, outros apps neste dispositivo podem conseguir controlar a Steam.</string> - <string name="mode_decky_off">Desativado. A porta de depuração remota da Steam fica fechada.</string> <string name="mode_decky_remove_title">Desinstalar o Decky Loader?</string> <string name="mode_decky_remove_text">Remove o loader. Seus plugins e configurações são mantidos.</string> <string name="mode_client">Cliente</string> @@ -955,13 +949,15 @@ <string name="setup_launcher_orientation_auto">Seguir a rotação do dispositivo</string> <string name="setup_orientation_portrait">Retrato</string> <string name="setup_session_orientation">Orientação da sessão</string> - <string name="setup_session_orientation_hint">Vale para a Steam, os jogos, a área de trabalho e o editor de controle. As predefinições de resolução giram com a sessão; largura e altura personalizadas ficam como foram digitadas.</string> + <string name="setup_session_orientation_hint">Vale para a Steam, os jogos, a área de trabalho e o editor de controle. As predefinições de resolução giram com a sessão; quando uma orientação segue a outra, largura e altura personalizadas são trocadas para corresponder.</string> <string name="setup_orientation_auto">Paisagem automática</string> <string name="setup_orientation_landscape">Paisagem</string> <string name="setup_orientation_reverse">Paisagem invertida</string> <string name="setup_fullscreen">Tela cheia</string> <string name="setup_fullscreen_on">Oculta as barras de status e de navegação do Android</string> <string name="setup_fullscreen_off">Mostra as barras de status e de navegação do Android</string> + <string name="setup_page_swipe">Deslizar entre páginas</string> + <string name="setup_page_swipe_hint">Deslize sobre uma página para mudar de aba.</string> <string name="setup_dual_screen_launcher">Iniciador em duas telas</string> <string name="setup_dual_screen_launcher_hint">O modo automático coloca as seções do iniciador (Steam, Biblioteca, Lojas e as demais) na segunda tela de consoles portáteis com uma tela secundária integrada. Ativado usa qualquer tela secundária. Desativado mantém o iniciador em uma única tela.</string> <string name="setup_dual_screen_sessions">Sessões em duas telas</string> @@ -1286,8 +1282,6 @@ <string name="gate_open_dev">Abrir as Opções do desenvolvedor</string> <string name="gate_no_toggle">Esta versão do Android não tem uma chave para isso, então o DroidDeck faz a mudança pela Depuração por Wi-Fi. Leva cerca de um minuto, sem precisar de computador.</string> <string name="gate_needs_wifi">A Depuração por Wi-Fi requer Wi-Fi. Qualquer rede serve; não precisa de internet.</string> - <string name="gate_needs_notifications">O código de pareamento é digitado em uma notificação. Permita notificações do DroidDeck ou use Outras formas.</string> - <string name="gate_allow_notifications">Permitir notificações</string> <string name="gate_step1">Abra Configurações → Opções do desenvolvedor → Depuração por Wi-Fi e ative</string> <string name="gate_step2">Toque em “Parear o dispositivo com um código de pareamento”</string> <string name="gate_step3">Digite o código na notificação do DroidDeck</string> @@ -1304,48 +1298,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Verificando a cada 2 segundos. Esta página fecha quando o limite for desativado.</string> <string name="gate_other_ways">Outras formas</string> - <string name="gate_other_toggle">Depuração por Wi-Fi, endereço manual, ADB pelo computador</string> - <string name="gate_other_no_toggle">Endereço manual, ADB pelo computador, Opções do desenvolvedor</string> <string name="gate_use_wireless_instead">Usar a Depuração por Wi-Fi</string> <string name="gate_some_roms">Algumas ROMs adicionam a chave mesmo assim. Procure “processos filhos” nas Opções do desenvolvedor.</string> - <string name="gate_manual_hint">Se a notificação não funcionar, digite você mesmo o endereço e o código do pop-up.</string> - <string name="gate_enter_manually">Digitar endereço manualmente</string> <string name="gate_from_computer">De um computador com ADB:</string> <string name="gate_copy_command">Copiar comando</string> <string name="gate_sidequest_steps">Conecte o headset a um computador e abra o SideQuest. Escolha “Run ADB Command”, depois “Custom Command”, digite o comando mostrado abaixo e selecione “Run Command”.</string> <string name="gate_choose_display">Escolha em qual tela abrir as Configurações do Android.</string> <string name="gate_main_screen">Tela principal</string> - <string name="wadb_finding_port">Pareado. Procurando a porta da Depuração por Wi-Fi…</string> - <string name="wadb_enter_port">Pareado. Digite a porta mostrada nas Configurações.</string> - <string name="wadb_applying">Dispositivo encontrado. Aplicando a configuração…</string> - <string name="wadb_apply_failed">Não foi possível aplicar automaticamente. Verifique o endereço abaixo e tente de novo. %1$s</string> - <string name="wadb_title_wireless">Depuração por Wi-Fi</string> - <string name="wadb_title_done">Limite de processos filhos atualizado</string> - <string name="wadb_title">Alterar o limite de processos filhos</string> - <string name="wadb_lede_compact0">Se a opção não existir, pareie pela Depuração por Wi-Fi.</string> - <string name="wadb_lede_compact1">Pareado. Verifique o endereço IP e a porta na Depuração por Wi-Fi.</string> - <string name="wadb_lede_done">O limite de processos filhos foi atualizado.</string> - <string name="wadb_lede0">Use a etapa 2 se as Opções do desenvolvedor não tiverem a configuração de processos filhos. Abra Opções do desenvolvedor → Depuração por Wi-Fi → Parear o dispositivo com um código de pareamento.</string> - <string name="wadb_lede1">Pareado. Use o endereço abaixo ou atualize-o em Depuração por Wi-Fi → Endereço IP e porta.</string> - <string name="wadb_lede_done_long">O limite de processos filhos foi atualizado pela Depuração por Wi-Fi.</string> - <string name="wadb_confirmed_on">O Android confirmou que o limite está ativado.</string> - <string name="wadb_confirmed_off">O Android confirmou que o limite está desativado.</string> - <string name="wadb_pair_group">2 · Parear pela Depuração por Wi-Fi</string> - <string name="wadb_pair_address">Endereço IP e porta do pop-up de pareamento</string> - <string name="wadb_pin">Código de pareamento (PIN)</string> - <string name="wadb_pin_placeholder">6 dígitos</string> - <string name="wadb_pair">Parear</string> - <string name="wadb_apply_group">2 · Aplicar pela Depuração por Wi-Fi</string> - <string name="wadb_connect_address">Endereço IP e porta de conexão</string> - <string name="wadb_pair_again">Parear de novo</string> - <string name="wadb_turn_off">Desativar o limite</string> - <string name="wadb_other_ways">Outras formas de alterar</string> - <string name="wadb_dev_try_first">1 · Opções do desenvolvedor (tente primeiro)</string> - <string name="wadb_restrict_on">Desative “Desativar restrições de processos filhos”.</string> - <string name="wadb_restrict_off">Ative “Desativar restrições de processos filhos”.</string> - <string name="wadb_computer_last">3 · ADB pelo computador (último recurso)</string> - <string name="wadb_only_if">Só se a Depuração por Wi-Fi não estiver disponível.</string> - <string name="wadb_computer_group">3 · ADB pelo computador (último recurso)</string> <string name="ctrl_color">Cor</string> <string name="ctrl_custom">Personalizada</string> <string name="ctrl_opacity">Opacidade</string> @@ -1639,8 +1598,6 @@ <item quantity="many">%1$d pastas de logs de sessão limpas.</item> <item quantity="other">%1$d pastas de logs de sessão limpas.</item> </plurals> - <string name="main_wadb_pair_failed">Falha no pareamento da depuração por Wi-Fi</string> - <string name="main_wadb_command_failed">Falha no comando de depuração por Wi-Fi</string> <string name="main_wadb_unavailable">A depuração por Wi-Fi não está disponível</string> <string name="main_adb_copied">Comando ADB copiado</string> <string name="main_pick_roms">Escolha a pasta de ROMs</string> @@ -2500,10 +2457,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Tela da sessão</string> - <string name="display_resolution">Resolução</string> + <string name="display_zero_copy">Apresentação sem cópia</string> + <string name="display_resolution_landscape">Resolução na horizontal</string> + <string name="display_resolution_portrait">Resolução na vertical</string> + <string name="display_follow_landscape">Igual à horizontal (%1$d×%2$d)</string> + <string name="display_follow_portrait">Igual à vertical (%1$d×%2$d)</string> <string name="display_game_fit">Ajuste de jogos 16:9</string> <string name="display_game_fit_hint">Como os jogos 16:9 se ajustam a esta tela. Na próxima sessão.</string> <string name="display_game_fit_unavailable">Escolha Igual à tela ou um tamanho personalizado mais estreito que 16:9.</string> + <string name="display_avoid_notch">Evitar o notch</string> + <string name="display_avoid_notch_hint">Mantém a imagem fora do recorte da câmera. Aplica-se ao voltar à sessão.</string> <string name="display_preserve">Manter proporções</string> <string name="display_stretch">Esticar para a tela</string> <string name="display_image_scaling">Escala de imagem</string> @@ -2787,6 +2750,7 @@ <string name="stores_login_error_ssl">A conexão com a página de login não é segura.</string> <string name="stores_login_error_verification">Não foi possível verificar o login. Tente de novo.</string> <string name="stores_login_error_generic">Falha no login. Tente de novo.</string> + <string name="stores_login_continue_in_browser">%1$s precisa de mais uma etapa. Conclua no navegador que foi aberto e tente novamente.</string> <string name="common_close">Fechar</string> <string name="common_back">Voltar</string> <string name="common_edit">Editar</string> @@ -3175,7 +3139,7 @@ <string name="hand_camera_done">Concluído</string> <string name="glasses_xreal_network_missing">Aguardando a conexão Ethernet por USB dos óculos. Este celular pode não disponibilizá-la para os apps.</string> <string name="glasses_xreal_connection_failed">A conexão com os óculos XREAL foi interrompida ou retornou uma resposta incompatível. Tentando novamente…</string> - <string name="glasses_xreal_experimental">Suporte experimental ao 1S. Use o modo Follow e desative a estabilização no menu dos óculos. As direções do rastreamento e os modos de exibição ainda precisam de testes no dispositivo.</string> + <string name="glasses_xreal_experimental">Suporte experimental a XREAL 1S, One, One Pro, One Pro+ e Aura. Use o modo Follow e desative a estabilização no menu dos óculos; no Aura, desative também Spatial Anchor. O rastreamento de cabeça e a alternância entre 2D/3D foram testados nos modelos Aura e One Pro+.</string> <string name="glasses_pro2_experimental">Rastreamento experimental da cabeça para Pro 2. Os ajustes de brilho e volume e a troca do modo de exibição ainda não são compatíveis.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Modo Cardboard</string> @@ -4071,6 +4035,7 @@ <string name="addons_sort_downloads">Mais baixados</string> <string name="addons_category_all">Todas as categorias</string> <string name="addons_none_found">Nenhum addon encontrado</string> + <string name="addons_curse_busy">Feche o CurseForge primeiro</string> <string name="addons_unreachable">Não foi possível acessar %1$s</string> <string name="addons_no_file">Não há arquivo para esta versão do jogo</string> <string name="input_reset_positions">Redefinir posições</string> @@ -4160,4 +4125,6 @@ <string name="display_scaling_integer">Inteiro</string> <string name="display_scaling_fit">Ajustar</string> <string name="drawer_antialiasing">Suavização de serrilhado</string> + <string name="hud_only_during_game">Mostrar o HUD somente durante o jogo</string> + <string name="hud_only_during_game_hint">Ocultar o HUD quando nenhum quadro do jogo for detectado.</string> </resources> diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index cc7a55a184..f25f8abbb2 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Ieșire HDR10</string> <string name="mode_hdr_unavailable">Indisponibil: %1$s.</string> - <string name="mode_hdr_restart">Repornește aplicația pentru a aplica.</string> <string name="mode_drivers">Drivere</string> <string name="mode_gpu_drivers">Drivere GPU</string> <string name="mode_gpu_drivers_hint">Partajate de Steam și Desktop. Se stabilesc pe pagina Componente.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Pornire</string> <string name="mode_startup_session">Deschide la pornire</string> <string name="mode_startup_session_hint">Pornește această sesiune când se lansează DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Se verifică versiunile…</string> <string name="mode_decky_ready">Pregătit pentru instalarea %1$s.</string> <string name="mode_decky_none">Nu s-a găsit o versiune compatibilă. Încearcă din nou mai târziu.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Actualizat · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Instalează cea mai recentă versiune</string> - <string name="decky_channel">Canal de actualizare</string> - <string name="decky_channel_hint">Ce versiuni Decky Loader se instalează. Actualizatorul propriu al Decky folosește același canal.</string> <string name="decky_channel_stable">Stabil</string> <string name="decky_channel_prerelease">Pre-lansare</string> <string name="decky_channel_testing">Testare</string> <string name="decky_channel_failed">Canalul de actualizare Decky nu a putut fi salvat</string> - <string name="mode_decky_on">Pornește odată cu Steam. Cât timp este activ, alte aplicații de pe acest dispozitiv pot fi capabile să controleze Steam.</string> - <string name="mode_decky_off">Dezactivat. Portul de depanare la distanță al Steam rămâne închis.</string> <string name="mode_decky_remove_title">Dezinstalezi Decky Loader?</string> <string name="mode_decky_remove_text">Elimină loader-ul. Pluginurile și setările tale sunt păstrate.</string> <string name="mode_client">Client</string> @@ -956,13 +950,15 @@ <string name="setup_launcher_orientation_auto">Urmează rotirea dispozitivului</string> <string name="setup_orientation_portrait">Portret</string> <string name="setup_session_orientation">Orientarea sesiunii</string> - <string name="setup_session_orientation_hint">Se aplică pentru Steam, jocuri, desktop și editorul de controller. Presetările de rezoluție se rotesc odată cu sesiunea; lățimea și înălțimea personalizate rămân cum au fost introduse.</string> + <string name="setup_session_orientation_hint">Se aplică pentru Steam, jocuri, desktop și editorul de controller. Presetările de rezoluție se rotesc odată cu sesiunea; când o orientare o urmează pe cealaltă, lățimea și înălțimea personalizate se inversează pentru a se potrivi.</string> <string name="setup_orientation_auto">Peisaj automat</string> <string name="setup_orientation_landscape">Peisaj</string> <string name="setup_orientation_reverse">Peisaj inversat</string> <string name="setup_fullscreen">Ecran complet</string> <string name="setup_fullscreen_on">Ascunde barele de stare și de navigare Android</string> <string name="setup_fullscreen_off">Arată barele de stare și de navigare Android</string> + <string name="setup_page_swipe">Glisare între pagini</string> + <string name="setup_page_swipe_hint">Glisați peste o pagină pentru a schimba fila.</string> <string name="setup_dual_screen_launcher">Lansator pe două ecrane</string> <string name="setup_dual_screen_launcher_hint">Automat plasează secțiunile lansatorului (Steam, Bibliotecă, Magazine și celelalte) pe ecranul secundar al consolelor portabile cu unul integrat. Activat folosește orice ecran secundar. Dezactivat păstrează lansatorul pe un singur ecran.</string> <string name="setup_dual_screen_sessions">Sesiuni pe două ecrane</string> @@ -1287,8 +1283,6 @@ <string name="gate_open_dev">Deschide Opțiunile pentru dezvoltatori</string> <string name="gate_no_toggle">Această versiune de Android nu are un comutator pentru asta, așa că DroidDeck o schimbă prin Depanarea wireless. Durează circa un minut, fără a avea nevoie de un computer.</string> <string name="gate_needs_wifi">Depanarea wireless are nevoie de Wi-Fi. Orice rețea funcționează; nu are nevoie de internet.</string> - <string name="gate_needs_notifications">Codul de asociere apare într-o notificare. Permite notificările pentru DroidDeck, sau folosește Alte moduri.</string> - <string name="gate_allow_notifications">Permite notificările</string> <string name="gate_step1">Deschide Setări → Opțiuni pentru dezvoltatori → Depanare wireless și activează-o</string> <string name="gate_step2">Apasă „Asociază dispozitivul cu un cod de asociere”</string> <string name="gate_step3">Introdu codul în notificarea DroidDeck</string> @@ -1305,48 +1299,13 @@ <string name="gate_status">Stare</string> <string name="gate_polling">Se verifică la fiecare 2 secunde. Această pagină se închide când este dezactivată.</string> <string name="gate_other_ways">Alte moduri</string> - <string name="gate_other_toggle">Depanare wireless, adresă manuală, ADB pe computer</string> - <string name="gate_other_no_toggle">Adresă manuală, ADB pe computer, Opțiuni pentru dezvoltatori</string> <string name="gate_use_wireless_instead">Folosește Depanarea wireless în schimb</string> <string name="gate_some_roms">Unele ROM-uri adaugă comutatorul oricum. Caută „procese-copil” în Opțiuni pentru dezvoltatori.</string> - <string name="gate_manual_hint">Dacă notificarea nu funcționează, introdu tu adresa și codul din fereastră.</string> - <string name="gate_enter_manually">Introdu adresa manual</string> <string name="gate_from_computer">De pe un computer cu ADB:</string> <string name="gate_copy_command">Copiază comanda</string> <string name="gate_sidequest_steps">Conectează căștile la un computer și deschide SideQuest. Alege „Run ADB Command”, apoi „Custom Command”, scrie comanda afișată mai jos și selectează „Run Command”.</string> <string name="gate_choose_display">Alege pe care afișaj se deschid Setările Android.</string> <string name="gate_main_screen">Ecranul principal</string> - <string name="wadb_finding_port">Asociat. Se caută portul de Depanare wireless…</string> - <string name="wadb_enter_port">Asociat. Introdu portul din Setări.</string> - <string name="wadb_applying">Dispozitiv găsit. Se aplică setarea…</string> - <string name="wadb_apply_failed">Nu s-a putut aplica automat. Verifică adresa de mai jos și încearcă din nou. %1$s</string> - <string name="wadb_title_wireless">Depanare wireless</string> - <string name="wadb_title_done">Limita proceselor-copil a fost actualizată</string> - <string name="wadb_title">Schimbă limita proceselor-copil</string> - <string name="wadb_lede_compact0">Dacă opțiunea lipsește, asociază-te prin Depanare wireless.</string> - <string name="wadb_lede_compact1">Asociat. Verifică adresa IP și portul în Depanare wireless.</string> - <string name="wadb_lede_done">Limita proceselor-copil a fost actualizată.</string> - <string name="wadb_lede0">Folosește pasul 2 dacă Opțiunile pentru dezvoltatori nu au o setare pentru procese-copil. Deschide Opțiuni pentru dezvoltatori → Depanare wireless → Asociază dispozitivul cu un cod de asociere.</string> - <string name="wadb_lede1">Asociat. Folosește adresa de mai jos, sau actualizeaz-o din Depanare wireless → Adresă IP și port.</string> - <string name="wadb_lede_done_long">Limita proceselor-copil a fost actualizată prin Depanarea wireless.</string> - <string name="wadb_confirmed_on">Android a confirmat că limita este activă.</string> - <string name="wadb_confirmed_off">Android a confirmat că limita este dezactivată.</string> - <string name="wadb_pair_group">2 · Asociază Depanarea wireless</string> - <string name="wadb_pair_address">Adresa IP și portul ferestrei de asociere</string> - <string name="wadb_pin">Cod de asociere (PIN)</string> - <string name="wadb_pin_placeholder">6 cifre</string> - <string name="wadb_pair">Asociază</string> - <string name="wadb_apply_group">2 · Aplică prin Depanarea wireless</string> - <string name="wadb_connect_address">Adresa IP și portul de conexiune</string> - <string name="wadb_pair_again">Asociază din nou</string> - <string name="wadb_turn_off">Dezactivează limita</string> - <string name="wadb_other_ways">Alte moduri de a o schimba</string> - <string name="wadb_dev_try_first">1 · Opțiuni pentru dezvoltatori (încearcă mai întâi)</string> - <string name="wadb_restrict_on">Dezactivează „Dezactivează restricțiile pentru procese secundare”.</string> - <string name="wadb_restrict_off">Activează „Dezactivează restricțiile pentru procese secundare”.</string> - <string name="wadb_computer_last">3 · ADB pe computer (ultima soluție)</string> - <string name="wadb_only_if">Doar dacă Depanarea wireless nu este disponibilă.</string> - <string name="wadb_computer_group">3 · ADB pe computer (ultima soluție)</string> <string name="ctrl_color">Culoare</string> <string name="ctrl_custom">Personalizat</string> <string name="ctrl_opacity">Opacitate</string> @@ -1640,8 +1599,6 @@ <item quantity="few">S-au șters %1$d foldere de jurnal de sesiune.</item> <item quantity="other">S-au șters %1$d de foldere de jurnal de sesiune.</item> </plurals> - <string name="main_wadb_pair_failed">Asocierea Depanării wireless a eșuat</string> - <string name="main_wadb_command_failed">Comanda Depanării wireless a eșuat</string> <string name="main_wadb_unavailable">Depanarea wireless nu este disponibilă</string> <string name="main_adb_copied">Comanda ADB copiată</string> <string name="main_pick_roms">Alege folderul ROMs</string> @@ -2487,10 +2444,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Afișajul sesiunii</string> - <string name="display_resolution">Rezoluție</string> + <string name="display_zero_copy">Prezentare fără copiere</string> + <string name="display_resolution_landscape">Rezoluție în peisaj</string> + <string name="display_resolution_portrait">Rezoluție în portret</string> + <string name="display_follow_landscape">Ca peisajul (%1$d×%2$d)</string> + <string name="display_follow_portrait">Ca portretul (%1$d×%2$d)</string> <string name="display_game_fit">Potrivire joc 16:9</string> <string name="display_game_fit_hint">Cum se potrivesc jocurile 16:9 cu acest afișaj. Sesiunea următoare.</string> <string name="display_game_fit_unavailable">Alege Potrivire ecran sau o dimensiune personalizată mai îngustă decât 16:9.</string> + <string name="display_avoid_notch">Evită decupajul</string> + <string name="display_avoid_notch_hint">Ține imaginea departe de decupajul camerei. Se aplică la revenirea în sesiune.</string> <string name="display_preserve">Păstrează proporțiile</string> <string name="display_stretch">Întinde pe afișaj</string> <string name="display_image_scaling">Scalarea imaginii</string> @@ -2777,6 +2740,7 @@ <string name="stores_login_error_ssl">Conexiunea la pagina de autentificare nu este sigură.</string> <string name="stores_login_error_verification">Autentificarea nu a putut fi verificată. Încearcă din nou.</string> <string name="stores_login_error_generic">Autentificarea a eșuat. Încearcă din nou.</string> + <string name="stores_login_continue_in_browser">%1$s mai cere un pas. Finalizează-l în browserul care s-a deschis, apoi încearcă din nou.</string> <string name="common_close">Închide</string> <string name="common_back">Înapoi</string> <string name="common_edit">Editează</string> @@ -3165,7 +3129,7 @@ <string name="hand_camera_done">Gata</string> <string name="glasses_xreal_network_missing">Se așteaptă conexiunea USB Ethernet a ochelarilor. Este posibil ca acest telefon să nu o expună aplicațiilor.</string> <string name="glasses_xreal_connection_failed">Conexiunea XREAL a fost întreruptă sau a returnat un răspuns neacceptat. Se reîncearcă…</string> - <string name="glasses_xreal_experimental">Suport experimental pentru 1S. Folosește modul Follow și dezactivează stabilizarea din meniul ochelarilor. Direcțiile de urmărire și modurile de afișare trebuie încă testate pe dispozitiv.</string> + <string name="glasses_xreal_experimental">Suport experimental pentru XREAL 1S, One, One Pro, One Pro+ și Aura. Folosește modul Follow și dezactivează stabilizarea din meniul ochelarilor; pe Aura, dezactivează și Spatial Anchor. Urmărirea capului și comutarea între 2D/3D au fost testate pe Aura și One Pro+.</string> <string name="glasses_pro2_experimental">Urmărire experimentală a mișcărilor capului pentru Pro 2. Reglarea luminozității și a volumului și schimbarea modului de afișare nu sunt încă acceptate.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Mod Cardboard</string> @@ -4050,6 +4014,7 @@ <string name="addons_sort_downloads">Cele mai descărcate</string> <string name="addons_category_all">Toate categoriile</string> <string name="addons_none_found">Nu s-au găsit suplimente</string> + <string name="addons_curse_busy">Închide mai întâi CurseForge</string> <string name="addons_unreachable">Nu s-a putut accesa %1$s</string> <string name="addons_no_file">Nu există fișier pentru această versiune a jocului</string> <string name="input_reset_positions">Resetează pozițiile</string> @@ -4153,4 +4118,6 @@ <string name="theme_custom_signal">Evidențieri</string> <string name="theme_custom_good">Succes</string> <string name="theme_custom_error">Eroare</string> + <string name="hud_only_during_game">Afișează HUD-ul doar în timpul jocului</string> + <string name="hud_only_during_game_hint">Ascunde HUD-ul când nu sunt detectate cadre ale jocului.</string> </resources> diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index a5f31948ad..956c3d5136 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Вывод HDR10</string> <string name="mode_hdr_unavailable">Недоступно: %1$s.</string> - <string name="mode_hdr_restart">Вступит в силу после перезапуска приложения.</string> <string name="mode_drivers">Драйверы</string> <string name="mode_gpu_drivers">Драйверы GPU</string> <string name="mode_gpu_drivers_hint">Общие для Steam и рабочего стола. Настройте на странице «Компоненты».</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Запуск</string> <string name="mode_startup_session">Открывать при запуске</string> <string name="mode_startup_session_hint">Запускает этот сеанс при запуске DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Проверка выпусков…</string> <string name="mode_decky_ready">Готово к установке %1$s.</string> <string name="mode_decky_none">Совместимая версия не найдена. Повторите попытку позже.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Актуально · %1$s</string> <string name="mode_decky_loader">Загрузчик</string> <string name="mode_decky_install_latest">Установить последнюю</string> - <string name="decky_channel">Канал обновлений</string> - <string name="decky_channel_hint">Какие выпуски Decky Loader устанавливать. Встроенное средство обновления Decky использует тот же канал.</string> <string name="decky_channel_stable">Стабильный</string> <string name="decky_channel_prerelease">Предварительный</string> <string name="decky_channel_testing">Тестовый</string> <string name="decky_channel_failed">Не удалось сохранить канал обновлений Decky</string> - <string name="mode_decky_on">Запускается вместе со Steam. Пока включено, другие приложения на этом устройстве могут управлять Steam.</string> - <string name="mode_decky_off">Выкл. Порт удаленной отладки Steam остается закрытым.</string> <string name="mode_decky_remove_title">Удалить Decky Loader?</string> <string name="mode_decky_remove_text">Удаляет загрузчик. Ваши плагины и настройки сохранятся.</string> <string name="mode_client">Клиент</string> @@ -959,13 +953,15 @@ <string name="setup_launcher_orientation_auto">Следовать повороту устройства</string> <string name="setup_orientation_portrait">Портретная</string> <string name="setup_session_orientation">Ориентация сессии</string> - <string name="setup_session_orientation_hint">Применяется к Steam, играм, рабочему столу и редактору контроллера. Предустановки разрешения поворачиваются вместе с сессией; свои ширина и высота остаются как введены.</string> + <string name="setup_session_orientation_hint">Применяется к Steam, играм, рабочему столу и редактору контроллера. Предустановки разрешения поворачиваются вместе с сессией; когда одна ориентация следует за другой, свои ширина и высота меняются местами.</string> <string name="setup_orientation_auto">Альбомная (авто)</string> <string name="setup_orientation_landscape">Альбомная</string> <string name="setup_orientation_reverse">Перевернутая альбомная</string> <string name="setup_fullscreen">Полноэкранный режим</string> <string name="setup_fullscreen_on">Скрывает строку состояния и панель навигации Android</string> <string name="setup_fullscreen_off">Показывает строку состояния и панель навигации Android</string> + <string name="setup_page_swipe">Перелистывание страниц свайпом</string> + <string name="setup_page_swipe_hint">Проведите по странице, чтобы сменить вкладку.</string> <string name="setup_dual_screen_launcher">Лаунчер на двух экранах</string> <string name="setup_dual_screen_launcher_hint">«Автоматически» переносит разделы лаунчера (Steam, Библиотека, Магазины и остальные) на второй экран портативных устройств со встроенным вторым экраном. «Вкл.» использует любой второй дисплей. «Выкл.» оставляет лаунчер на одном экране.</string> <string name="setup_dual_screen_sessions">Сессии на двух экранах</string> @@ -1294,8 +1290,6 @@ <string name="gate_open_dev">Открыть «Для разработчиков»</string> <string name="gate_no_toggle">В этой версии Android нет такого переключателя, поэтому DroidDeck внесет изменения через отладку по Wi-Fi. Это займет около минуты, компьютер не нужен.</string> <string name="gate_needs_wifi">Для отладки по Wi-Fi требуется Wi-Fi. Подойдет любая сеть, интернет не нужен.</string> - <string name="gate_needs_notifications">Код сопряжения придет в уведомлении. Разрешите DroidDeck отправлять уведомления или используйте «Другие способы».</string> - <string name="gate_allow_notifications">Разрешить уведомления</string> <string name="gate_step1">Откройте Настройки → Для разработчиков → Отладка по Wi-Fi и включите ее</string> <string name="gate_step2">Нажмите «Подключить устройство с помощью кода подключения»</string> <string name="gate_step3">Введите код сопряжения в уведомлении DroidDeck</string> @@ -1312,48 +1306,13 @@ <string name="gate_status">Статус</string> <string name="gate_polling">Проверка каждые 2 секунды. После отключения этого переключателя страница закроется автоматически.</string> <string name="gate_other_ways">Другие способы</string> - <string name="gate_other_toggle">Отладка по Wi-Fi, ручной ввод адреса, ADB на ПК</string> - <string name="gate_other_no_toggle">Ручной ввод адреса, ADB на ПК, «Для разработчиков»</string> <string name="gate_use_wireless_instead">Использовать отладку по Wi-Fi</string> <string name="gate_some_roms">В некоторых прошивках переключатель все же есть. Поищите «дочерние процессы» в разделе «Для разработчиков».</string> - <string name="gate_manual_hint">Если способ с уведомлением не работает, введите адрес и код сопряжения из окна вручную.</string> - <string name="gate_enter_manually">Ввести адрес вручную</string> <string name="gate_from_computer">С компьютера через ADB:</string> <string name="gate_copy_command">Копировать команду</string> <string name="gate_sidequest_steps">Подключите шлем к компьютеру и откройте SideQuest. Выберите «Run ADB Command», затем «Custom Command», введите команду, показанную ниже, и нажмите «Run Command».</string> <string name="gate_choose_display">Выберите экран для открытия настроек Android.</string> <string name="gate_main_screen">Главный экран</string> - <string name="wadb_finding_port">Сопряжено. Поиск порта отладки по Wi-Fi…</string> - <string name="wadb_enter_port">Сопряжено. Введите порт из настроек.</string> - <string name="wadb_applying">Устройство найдено. Применение настроек…</string> - <string name="wadb_apply_failed">Не удалось применить автоматически. Проверьте адрес ниже и повторите попытку. %1$s</string> - <string name="wadb_title_wireless">Отладка по Wi-Fi</string> - <string name="wadb_title_done">Ограничение дочерних процессов обновлено</string> - <string name="wadb_title">Изменить ограничение дочерних процессов</string> - <string name="wadb_lede_compact0">Если опции нет, выполните сопряжение через отладку по Wi-Fi.</string> - <string name="wadb_lede_compact1">Сопряжено. Проверьте IP-адрес и порт в отладке по Wi-Fi.</string> - <string name="wadb_lede_done">Ограничение дочерних процессов обновлено.</string> - <string name="wadb_lede0">Если в параметрах разработчика нет настройки дочерних процессов, используйте шаг 2. Откройте Для разработчиков → Отладка по Wi-Fi → Сопряжение устройства с помощью кода.</string> - <string name="wadb_lede1">Сопряжено. Используйте адрес ниже или обновите его в разделе Отладка по Wi-Fi → IP-адрес и порт.</string> - <string name="wadb_lede_done_long">Ограничение дочерних процессов обновлено через отладку по Wi-Fi.</string> - <string name="wadb_confirmed_on">Android подтвердил, что ограничение включено.</string> - <string name="wadb_confirmed_off">Android подтвердил, что ограничение отключено.</string> - <string name="wadb_pair_group">2 · Сопряжение отладки по Wi-Fi</string> - <string name="wadb_pair_address">IP-адрес и порт из окна сопряжения</string> - <string name="wadb_pin">Код сопряжения (PIN)</string> - <string name="wadb_pin_placeholder">6 цифр</string> - <string name="wadb_pair">Сопряжение</string> - <string name="wadb_apply_group">2 · Применение через отладку по Wi-Fi</string> - <string name="wadb_connect_address">IP-адрес и порт подключения</string> - <string name="wadb_pair_again">Сопряжение заново</string> - <string name="wadb_turn_off">Отключить ограничение</string> - <string name="wadb_other_ways">Другие способы изменения</string> - <string name="wadb_dev_try_first">1 · Для разработчиков (сначала попробуйте это)</string> - <string name="wadb_restrict_on">Отключите «Отключить ограничения для дочерних процессов».</string> - <string name="wadb_restrict_off">Включите «Отключить ограничения для дочерних процессов».</string> - <string name="wadb_computer_last">3 · ADB на ПК (крайняя мера)</string> - <string name="wadb_only_if">Используйте только если отладка по Wi-Fi недоступна.</string> - <string name="wadb_computer_group">3 · ADB на ПК (крайняя мера)</string> <string name="ctrl_color">Цвет</string> <string name="ctrl_custom">Пользовательский</string> <string name="ctrl_opacity">Непрозрачность</string> @@ -1653,8 +1612,6 @@ <item quantity="many">Очищено %1$d папок журналов сессии.</item> <item quantity="other">Очищено %1$d папки журналов сессии.</item> </plurals> - <string name="main_wadb_pair_failed">Ошибка сопряжения для отладки по Wi-Fi</string> - <string name="main_wadb_command_failed">Ошибка команды отладки по Wi-Fi</string> <string name="main_wadb_unavailable">Отладка по Wi-Fi недоступна</string> <string name="main_adb_copied">Команда ADB скопирована</string> <string name="main_pick_roms">Выберите папку ROM</string> @@ -1691,6 +1648,7 @@ <string name="main_pick_game_storage">Выберите папку хранилища игр</string> <string name="main_pick_decky_zip">Выберите ZIP-файл плагина Decky</string> <string name="main_storage_not_usable">Нельзя использовать: %1$s</string> + <string name="main_storage_fat32">FAT32 не поддерживает файлы больше 4 ГБ, поэтому часть игр не установится. Отформатируйте в exFAT.</string> <string name="main_running_program">Программа</string> <string name="main_removing_runtime">Удаление среды выполнения Linux</string> <string name="main_settings_main_screen">Не удалось открыть настройки на нижнем экране; они открыты на главном экране.</string> @@ -2513,10 +2471,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Экран сессии</string> - <string name="display_resolution">Разрешение</string> + <string name="display_zero_copy">Вывод без копирования</string> + <string name="display_resolution_landscape">Разрешение в альбомной ориентации</string> + <string name="display_resolution_portrait">Разрешение в портретной ориентации</string> + <string name="display_follow_landscape">Как в альбомной (%1$d×%2$d)</string> + <string name="display_follow_portrait">Как в портретной (%1$d×%2$d)</string> <string name="display_game_fit">Игры 16:9</string> <string name="display_game_fit_hint">Как игры 16:9 вписываются в этот экран. Вступит в силу в следующей сессии.</string> <string name="display_game_fit_unavailable">Выберите «По размеру экрана» или свой размер уже 16:9.</string> + <string name="display_avoid_notch">Обходить вырез</string> + <string name="display_avoid_notch_hint">Не выводит картинку под вырез камеры. Применяется при возврате в сессию.</string> <string name="display_preserve">Сохранять пропорции</string> <string name="display_stretch">Растянуть на экран</string> <string name="display_image_scaling">Масштабирование изображения</string> @@ -2800,6 +2764,7 @@ <string name="stores_login_error_ssl">Подключение к странице входа не защищено.</string> <string name="stores_login_error_verification">Не удалось подтвердить вход. Повторите попытку.</string> <string name="stores_login_error_generic">Ошибка входа. Повторите попытку.</string> + <string name="stores_login_continue_in_browser">%1$s требует ещё один шаг. Завершите его в открывшемся браузере и попробуйте снова.</string> <string name="common_close">Закрыть</string> <string name="common_back">Назад</string> <string name="common_edit">Изменить</string> @@ -3192,7 +3157,7 @@ <string name="hand_camera_done">Готово</string> <string name="glasses_xreal_network_missing">Ожидание подключения очков по USB Ethernet. Этот телефон может не предоставлять его приложениям.</string> <string name="glasses_xreal_connection_failed">Подключение к XREAL прервано или получен неподдерживаемый ответ. Повторная попытка…</string> - <string name="glasses_xreal_experimental">Экспериментальная поддержка 1S. Включите режим Follow и отключите стабилизацию в меню очков. Направления отслеживания и режимы отображения ещё нужно проверить на устройстве.</string> + <string name="glasses_xreal_experimental">Экспериментальная поддержка XREAL 1S, One, One Pro, One Pro+ и Aura. Используйте режим Follow и отключите стабилизацию в меню очков; на Aura также отключите Spatial Anchor. Отслеживание головы и переключение между 2D/3D проверены на Aura и One Pro+.</string> <string name="glasses_pro2_experimental">Экспериментальное отслеживание движений головы для Pro 2. Настройка яркости и громкости и переключение режимов отображения пока не поддерживаются.</string> <string name="stores_fact_developer">Разработчик</string> <string name="stores_fact_publisher">Издатель</string> @@ -4090,6 +4055,7 @@ <string name="addons_sort_downloads">Самые скачиваемые</string> <string name="addons_category_all">Все категории</string> <string name="addons_none_found">Аддоны не найдены</string> + <string name="addons_curse_busy">Сначала закройте CurseForge</string> <string name="addons_unreachable">Не удалось подключиться к %1$s</string> <string name="addons_no_file">Нет файла для этой версии игры</string> <string name="input_reset_positions">Сбросить положение</string> @@ -4193,4 +4159,6 @@ <string name="theme_custom_signal">Выделения</string> <string name="theme_custom_good">Успех</string> <string name="theme_custom_error">Ошибка</string> + <string name="hud_only_during_game">Показывать HUD только во время игры</string> + <string name="hud_only_during_game_hint">Скрывать HUD, когда кадры игры не обнаруживаются.</string> </resources> diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 9bc129df9a..9361bca121 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10-utgång</string> <string name="mode_hdr_unavailable">Inte tillgängligt: %1$s.</string> - <string name="mode_hdr_restart">Starta om appen för att tillämpa.</string> <string name="mode_drivers">Drivrutiner</string> <string name="mode_gpu_drivers">GPU-drivrutiner</string> <string name="mode_gpu_drivers_hint">Delas av Steam och skrivbordet. Ställs in på sidan Komponenter.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Uppstart</string> <string name="mode_startup_session">Öppna vid start</string> <string name="mode_startup_session_hint">Startar den här sessionen när DroidDeck startar.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Söker efter utgåvor…</string> <string name="mode_decky_ready">Redo att installera %1$s.</string> <string name="mode_decky_none">Inget kompatibelt bygge hittades. Försök igen senare.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Senaste versionen · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Installera senaste</string> - <string name="decky_channel">Uppdateringskanal</string> - <string name="decky_channel_hint">Vilka Decky Loader-utgåvor som installeras. Deckys egen uppdaterare använder samma kanal.</string> <string name="decky_channel_stable">Stabil</string> <string name="decky_channel_prerelease">Förhandsversion</string> <string name="decky_channel_testing">Test</string> <string name="decky_channel_failed">Det gick inte att spara Deckys uppdateringskanal</string> - <string name="mode_decky_on">Startar med Steam. Medan det är på kan andra appar på enheten eventuellt styra Steam.</string> - <string name="mode_decky_off">Av. Steams fjärrfelsökningsport förblir stängd.</string> <string name="mode_decky_remove_title">Avinstallera Decky Loader?</string> <string name="mode_decky_remove_text">Tar bort inläsaren. Dina tillägg och inställningar behålls.</string> <string name="mode_client">Klient</string> @@ -953,13 +947,15 @@ <string name="setup_launcher_orientation_auto">Följ enhetens rotation</string> <string name="setup_orientation_portrait">Stående</string> <string name="setup_session_orientation">Sessionens orientering</string> - <string name="setup_session_orientation_hint">Gäller Steam, spel, skrivbordet och kontrollredigeraren. Upplösningsförinställningar roterar med sessionen; anpassad bredd och höjd förblir som angivet.</string> + <string name="setup_session_orientation_hint">Gäller Steam, spel, skrivbordet och kontrollredigeraren. Upplösningsförinställningar roterar med sessionen; när en orientering följer den andra byts anpassad bredd och höjd så att de passar.</string> <string name="setup_orientation_auto">Automatiskt liggande</string> <string name="setup_orientation_landscape">Liggande</string> <string name="setup_orientation_reverse">Liggande, upp och ned</string> <string name="setup_fullscreen">Helskärm</string> <string name="setup_fullscreen_on">Döljer Androids statusfält och navigeringsfält</string> <string name="setup_fullscreen_off">Visar Androids statusfält och navigeringsfält</string> + <string name="setup_page_swipe">Svep mellan sidor</string> + <string name="setup_page_swipe_hint">Svep över en sida för att byta flik.</string> <string name="setup_dual_screen_launcher">Startprogram för två skärmar</string> <string name="setup_dual_screen_launcher_hint">Automatiskt: placerar startprogrammets avsnitt (Steam, Bibliotek, Butiker med flera) på den inbyggda andra skärmen på handhållna enheter som har en. På: använder vilken andra bildskärm som helst. Av: behåller startprogrammet på en skärm.</string> <string name="setup_dual_screen_sessions">Sessioner med två skärmar</string> @@ -1280,8 +1276,6 @@ <string name="gate_open_dev">Öppna Utvecklaralternativ</string> <string name="gate_no_toggle">Den här Android-versionen har ingen omkopplare för det, så DroidDeck ändrar det via Trådlös felsökning. Tar ungefär en minut, ingen dator behövs.</string> <string name="gate_needs_wifi">Trådlös felsökning kräver Wi-Fi. Alla nätverk fungerar; det behöver inte internet.</string> - <string name="gate_needs_notifications">Ihopkopplingskoden skickas i en avisering. Tillåt aviseringar för DroidDeck, eller använd Andra sätt.</string> - <string name="gate_allow_notifications">Tillåt aviseringar</string> <string name="gate_step1">Öppna Inställningar → Utvecklaralternativ → Trådlös felsökning och slå på det</string> <string name="gate_step2">Tryck på ”Para ihop enhet med ihopkopplingskod”</string> <string name="gate_step3">Skriv in koden i DroidDeck-aviseringen</string> @@ -1298,48 +1292,13 @@ <string name="gate_status">Status</string> <string name="gate_polling">Kontrollerar var 2 sekunder. Den här sidan stängs när det är av.</string> <string name="gate_other_ways">Andra sätt</string> - <string name="gate_other_toggle">Trådlös felsökning, manuell adress, dator-ADB</string> - <string name="gate_other_no_toggle">Manuell adress, dator-ADB, Utvecklaralternativ</string> <string name="gate_use_wireless_instead">Använd Trådlös felsökning i stället</string> <string name="gate_some_roms">Vissa ROM:ar lägger till omkopplaren trots allt. Leta efter ”underprocess” i Utvecklaralternativ.</string> - <string name="gate_manual_hint">Om aviseringen inte fungerar, ange popup-fönstrets adress och kod själv.</string> - <string name="gate_enter_manually">Ange adress manuellt</string> <string name="gate_from_computer">Från en dator med ADB:</string> <string name="gate_copy_command">Kopiera kommando</string> <string name="gate_sidequest_steps">Anslut headsetet till en dator och öppna SideQuest. Välj ”Run ADB Command” och sedan ”Custom Command”, skriv in kommandot som visas nedan och välj ”Run Command”.</string> <string name="gate_choose_display">Välj vilken skärm Android-inställningar ska öppnas på.</string> <string name="gate_main_screen">Huvudskärm</string> - <string name="wadb_finding_port">Ihopkopplad. Letar efter porten för Trådlös felsökning…</string> - <string name="wadb_enter_port">Ihopkopplad. Ange porten från Inställningar.</string> - <string name="wadb_applying">Enhet hittad. Tillämpar inställningen…</string> - <string name="wadb_apply_failed">Kunde inte tillämpas automatiskt. Kontrollera adressen nedan och försök igen. %1$s</string> - <string name="wadb_title_wireless">Trådlös felsökning</string> - <string name="wadb_title_done">Gränsen för underprocesser har uppdaterats</string> - <string name="wadb_title">Ändra gränsen för underprocesser</string> - <string name="wadb_lede_compact0">Om alternativet saknas, para ihop via Trådlös felsökning.</string> - <string name="wadb_lede_compact1">Ihopkopplad. Kontrollera IP-adressen och porten i Trådlös felsökning.</string> - <string name="wadb_lede_done">Gränsen för underprocesser har uppdaterats.</string> - <string name="wadb_lede0">Använd steg 2 om Utvecklaralternativ inte har någon inställning för underprocesser. Öppna Utvecklaralternativ → Trådlös felsökning → Para ihop enhet med ihopkopplingskod.</string> - <string name="wadb_lede1">Ihopkopplad. Använd adressen nedan, eller uppdatera den från Trådlös felsökning → IP-adress & port.</string> - <string name="wadb_lede_done_long">Gränsen för underprocesser uppdaterades via Trådlös felsökning.</string> - <string name="wadb_confirmed_on">Android bekräftade att gränsen är på.</string> - <string name="wadb_confirmed_off">Android bekräftade att gränsen är av.</string> - <string name="wadb_pair_group">2 · Para ihop Trådlös felsökning</string> - <string name="wadb_pair_address">Ihopkopplingsrutans IP-adress & port</string> - <string name="wadb_pin">Ihopkopplingskod (PIN)</string> - <string name="wadb_pin_placeholder">6 siffror</string> - <string name="wadb_pair">Para ihop</string> - <string name="wadb_apply_group">2 · Tillämpa via Trådlös felsökning</string> - <string name="wadb_connect_address">Anslutningens IP-adress & port</string> - <string name="wadb_pair_again">Para ihop igen</string> - <string name="wadb_turn_off">Stäng av gränsen</string> - <string name="wadb_other_ways">Andra sätt att ändra det</string> - <string name="wadb_dev_try_first">1 · Utvecklaralternativ (prova först)</string> - <string name="wadb_restrict_on">Slå av ”Inaktivera begränsningar på underordnade processer”.</string> - <string name="wadb_restrict_off">Slå på ”Inaktivera begränsningar på underordnade processer”.</string> - <string name="wadb_computer_last">3 · Dator-ADB (sista utväg)</string> - <string name="wadb_only_if">Bara om Trådlös felsökning inte är tillgänglig.</string> - <string name="wadb_computer_group">3 · Dator-ADB (sista utväg)</string> <string name="ctrl_color">Färg</string> <string name="ctrl_custom">Anpassad</string> <string name="ctrl_opacity">Opacitet</string> @@ -1627,8 +1586,6 @@ <item quantity="one">Rensade %1$d sessionsloggmapp.</item> <item quantity="other">Rensade %1$d sessionsloggmappar.</item> </plurals> - <string name="main_wadb_pair_failed">Parkopplingen för trådlös felsökning misslyckades</string> - <string name="main_wadb_command_failed">Kommandot för trådlös felsökning misslyckades</string> <string name="main_wadb_unavailable">Trådlös felsökning är inte tillgänglig</string> <string name="main_adb_copied">ADB-kommandot har kopierats</string> <string name="main_pick_roms">Välj ROM-mappen</string> @@ -2461,10 +2418,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Sessionsskärm</string> - <string name="display_resolution">Upplösning</string> + <string name="display_zero_copy">Presentation utan kopiering</string> + <string name="display_resolution_landscape">Upplösning i liggande</string> + <string name="display_resolution_portrait">Upplösning i stående</string> + <string name="display_follow_landscape">Följ liggande (%1$d×%2$d)</string> + <string name="display_follow_portrait">Följ stående (%1$d×%2$d)</string> <string name="display_game_fit">16:9-spelanpassning</string> <string name="display_game_fit_hint">Hur 16:9-spel anpassas till den här skärmen. Nästa session.</string> <string name="display_game_fit_unavailable">Välj Matcha skärmen eller en anpassad storlek som är smalare än 16:9.</string> + <string name="display_avoid_notch">Undvik notch</string> + <string name="display_avoid_notch_hint">Håller bilden utanför kameraurtaget. Gäller när du återvänder till sessionen.</string> <string name="display_preserve">Behåll proportionerna</string> <string name="display_stretch">Sträck ut till skärmen</string> <string name="display_image_scaling">Bildskalning</string> @@ -2751,6 +2714,7 @@ <string name="stores_login_error_ssl">Anslutningen till inloggningssidan är inte säker.</string> <string name="stores_login_error_verification">Inloggningen kunde inte verifieras. Försök igen.</string> <string name="stores_login_error_generic">Inloggningen misslyckades. Försök igen.</string> + <string name="stores_login_continue_in_browser">%1$s behöver ett steg till. Slutför det i webbläsaren som öppnades och försök sedan igen.</string> <string name="common_close">Stäng</string> <string name="common_back">Tillbaka</string> <string name="common_edit">Redigera</string> @@ -3135,7 +3099,7 @@ <string name="hand_camera_done">Klar</string> <string name="glasses_xreal_network_missing">Väntar på glasögonens USB Ethernet-anslutning. Telefonen kanske inte gör den tillgänglig för appar.</string> <string name="glasses_xreal_connection_failed">XREAL-anslutningen avbröts eller gav ett svar som inte stöds. Försöker igen…</string> - <string name="glasses_xreal_experimental">Experimentellt stöd för 1S. Använd Follow-läget och stäng av stabiliseringen i glasögonens meny. Spårningsriktningar och visningslägen behöver fortfarande testas på enheten.</string> + <string name="glasses_xreal_experimental">Experimentellt stöd för XREAL 1S, One, One Pro, One Pro+ och Aura. Använd Follow-läget och stäng av stabiliseringen i glasögonens meny; på Aura ska du även stänga av Spatial Anchor. Huvudspårning och växling mellan 2D/3D har testats på Aura och One Pro+.</string> <string name="glasses_pro2_experimental">Experimentell huvudspårning för Pro 2. Justering av ljusstyrka och volym samt byte av visningsläge stöds inte ännu.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard-läge</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">Mest nedladdade</string> <string name="addons_category_all">Alla kategorier</string> <string name="addons_none_found">Inga tillägg hittades</string> + <string name="addons_curse_busy">Stäng CurseForge först</string> <string name="addons_unreachable">Kunde inte nå %1$s</string> <string name="addons_no_file">Ingen fil för den här spelversionen</string> <string name="input_reset_positions">Återställ positioner</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">Markeringar</string> <string name="theme_custom_good">Lyckades</string> <string name="theme_custom_error">Fel</string> + <string name="hud_only_during_game">Visa HUD endast under spel</string> + <string name="hud_only_during_game_hint">Dölj HUD när inga spelbildrutor upptäcks.</string> </resources> diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 2402c15f86..a7f07bbe93 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">เอาต์พุต HDR10</string> <string name="mode_hdr_unavailable">ไม่พร้อมใช้งาน: %1$s</string> - <string name="mode_hdr_restart">รีสตาร์ทแอปเพื่อให้มีผล</string> <string name="mode_drivers">ไดรเวอร์</string> <string name="mode_gpu_drivers">ไดรเวอร์ GPU</string> <string name="mode_gpu_drivers_hint">ใช้ร่วมกันระหว่าง Steam และเดสก์ท็อป ตั้งค่าได้ที่หน้า Components</string> @@ -333,7 +332,6 @@ <string name="mode_startup">การเริ่มทำงาน</string> <string name="mode_startup_session">เปิดเมื่อเริ่มต้น</string> <string name="mode_startup_session_hint">เริ่มเซสชันนี้เมื่อเปิด DroidDeck</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">กำลังค้นหารุ่นที่เผยแพร่…</string> <string name="mode_decky_ready">พร้อมติดตั้ง %1$s</string> <string name="mode_decky_none">ไม่พบบิลด์ที่เข้ากันได้ ลองใหม่อีกครั้งในหลัง</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">เป็นรุ่นล่าสุดแล้ว · %1$s</string> <string name="mode_decky_loader">ตัวโหลด</string> <string name="mode_decky_install_latest">ติดตั้งรุ่นล่าสุด</string> - <string name="decky_channel">ช่องทางอัปเดต</string> - <string name="decky_channel_hint">รุ่นของ Decky Loader ที่จะติดตั้ง ตัวอัปเดตของ Decky เองก็ใช้ช่องทางเดียวกัน</string> <string name="decky_channel_stable">เสถียร</string> <string name="decky_channel_prerelease">ก่อนเปิดตัว</string> <string name="decky_channel_testing">ทดสอบ</string> <string name="decky_channel_failed">บันทึกช่องทางอัปเดตของ Decky ไม่ได้</string> - <string name="mode_decky_on">เริ่มพร้อมกับ Steam เมื่อเปิดใช้งาน แอปอื่นบนอุปกรณ์นี้อาจสามารถควบคุม Steam ได้</string> - <string name="mode_decky_off">ปิดอยู่ พอร์ตดีบักระยะไกลของ Steam ยังคงปิดอยู่</string> <string name="mode_decky_remove_title">ถอนการติดตั้ง Decky Loader?</string> <string name="mode_decky_remove_text">ลบตัวโหลดออก พลักอินและการตั้งค่าของคุณจะยังคงอยู่</string> <string name="mode_client">ไคลเอนต์</string> @@ -950,13 +944,15 @@ <string name="setup_launcher_orientation_auto">หมุนตามอุปกรณ์</string> <string name="setup_orientation_portrait">แนวตั้ง</string> <string name="setup_session_orientation">การวางแนวของเซสชัน</string> - <string name="setup_session_orientation_hint">มีผลกับ Steam เกม เดสก์ท็อป และตัวแก้ไขคอนโทรลเลอร์ ค่าความละเอียดที่ตั้งไว้ล่วงหน้าจะหมุนตามเซสชัน ส่วนความกว้างและความสูงที่กำหนดเองจะคงตามที่ป้อนไว้</string> + <string name="setup_session_orientation_hint">มีผลกับ Steam เกม เดสก์ท็อป และตัวแก้ไขคอนโทรลเลอร์ ค่าความละเอียดที่ตั้งไว้ล่วงหน้าจะหมุนตามเซสชัน เมื่อแนวหนึ่งตามอีกแนวหนึ่ง ความกว้างและความสูงที่กำหนดเองจะสลับกันให้ตรงกัน</string> <string name="setup_orientation_auto">แนวนอนอัตโนมัติ</string> <string name="setup_orientation_landscape">แนวนอน</string> <string name="setup_orientation_reverse">แนวนอนกลับด้าน</string> <string name="setup_fullscreen">เต็มจอ</string> <string name="setup_fullscreen_on">ซ่อนแถบสถานะและแถบนำทางของ Android</string> <string name="setup_fullscreen_off">แสดงแถบสถานะและแถบนำทางของ Android</string> + <string name="setup_page_swipe">ปัดเพื่อเปลี่ยนหน้า</string> + <string name="setup_page_swipe_hint">ปัดผ่านหน้าเพื่อเปลี่ยนแท็บ</string> <string name="setup_dual_screen_launcher">ลอนเชอร์แบบสองจอ</string> <string name="setup_dual_screen_launcher_hint">โหมดอัตโนมัติจะแสดงส่วนต่างๆ ของลอนเชอร์ (Steam, คลังเกม, ร้านค้า และส่วนอื่นๆ) บนจอที่สองของเครื่องเล่นพกพาที่มีจอที่สองในตัว โหมดเปิดใช้จอที่สองใดก็ได้ โหมดปิดจะแสดงลอนเชอร์บนจอเดียว</string> <string name="setup_dual_screen_sessions">เซสชันแบบสองจอ</string> @@ -1274,8 +1270,6 @@ <string name="gate_open_dev">เปิดตัวเลือกสำหรับนักพัฒนา</string> <string name="gate_no_toggle">Android รุ่นนี้ไม่มีสวิตช์สำหรับสิ่งนี้ ดังนั้น DroidDeck จะเปลี่ยนค่าผ่าน Wireless debugging ใช้เวลาประมาณหนึ่งนาที ไม่ต้องใช้คอมพิวเตอร์</string> <string name="gate_needs_wifi">Wireless debugging ต้องใช้ Wi-Fi เครือข่ายใดก็ได้ ไม่จำเป็นต้องมีอินเทอร์เน็ต</string> - <string name="gate_needs_notifications">รหัสจับคู่จะแสดงในการแจ้งเตือน อนุญาตการแจ้งเตือนสำหรับ DroidDeck หรือใช้วิธีอื่น</string> - <string name="gate_allow_notifications">อนุญาตการแจ้งเตือน</string> <string name="gate_step1">เปิดการตั้งค่า → ตัวเลือกสำหรับนักพัฒนา → Wireless debugging แล้วเปิดใช้งาน</string> <string name="gate_step2">แตะ “Pair device with pairing code”</string> <string name="gate_step3">พิมพ์รหัสลงในการแจ้งเตือนของ DroidDeck</string> @@ -1292,48 +1286,13 @@ <string name="gate_status">สถานะ</string> <string name="gate_polling">กำลังตรวจสอบทุก 2 วินาที หน้านี้จะปิดเมื่อปิดใช้งานแล้ว</string> <string name="gate_other_ways">วิธีอื่น</string> - <string name="gate_other_toggle">Wireless debugging, ที่อยู่แบบกำหนดเอง, ADB จากคอมพิวเตอร์</string> - <string name="gate_other_no_toggle">ที่อยู่แบบกำหนดเอง, ADB จากคอมพิวเตอร์, ตัวเลือกสำหรับนักพัฒนา</string> <string name="gate_use_wireless_instead">ใช้ Wireless debugging แทน</string> <string name="gate_some_roms">บาง ROM เพิ่มสวิตช์นี้มาเองเลย ลองหา “child process” ในตัวเลือกสำหรับนักพัฒนา</string> - <string name="gate_manual_hint">หากการแจ้งเตือนไม่ทำงาน ให้กรอกที่อยู่และรหัสจากป๊อปอัปด้วยตัวเอง</string> - <string name="gate_enter_manually">กรอกที่อยู่ด้วยตัวเอง</string> <string name="gate_from_computer">จากคอมพิวเตอร์ที่มี ADB:</string> <string name="gate_copy_command">คัดลอกคำสั่ง</string> <string name="gate_sidequest_steps">เชื่อมต่อแว่นกับคอมพิวเตอร์แล้วเปิด SideQuest เลือก “Run ADB Command” จากนั้น “Custom Command” พิมพ์คำสั่งที่แสดงด้านล่างแล้วเลือก “Run Command”</string> <string name="gate_choose_display">เลือกหน้าจอที่จะเปิดการตั้งค่า Android</string> <string name="gate_main_screen">หน้าจอหลัก</string> - <string name="wadb_finding_port">จับคู่แล้ว กำลังค้นหาพอร์ตของ Wireless debugging…</string> - <string name="wadb_enter_port">จับคู่แล้ว กรอกพอร์ตจากการตั้งค่า</string> - <string name="wadb_applying">พบอุปกรณ์แล้ว กำลังปรับใช้การตั้งค่า…</string> - <string name="wadb_apply_failed">ไม่สามารถปรับใช้โดยอัตโนมัติได้ ตรวจสอบที่อยู่ด้านล่างแล้วลองใหม่ %1$s</string> - <string name="wadb_title_wireless">การแก้ไขข้อบกพร่องแบบไร้สาย</string> - <string name="wadb_title_done">อัปเดตขีดจำกัดโพรเซสลูกแล้ว</string> - <string name="wadb_title">เปลี่ยนขีดจำกัดโพรเซสลูก</string> - <string name="wadb_lede_compact0">หากไม่พบตัวเลือกนี้ ให้จับคู่ผ่าน Wireless debugging</string> - <string name="wadb_lede_compact1">จับคู่แล้ว ตรวจสอบที่อยู่ IP และพอร์ตใน Wireless debugging</string> - <string name="wadb_lede_done">อัปเดตขีดจำกัดโพรเซสลูกแล้ว</string> - <string name="wadb_lede0">ใช้ขั้นตอนที่ 2 หากตัวเลือกสำหรับนักพัฒนาไม่มีการตั้งค่าโพรเซสลูก เปิดตัวเลือกสำหรับนักพัฒนา → Wireless debugging → Pair device with pairing code</string> - <string name="wadb_lede1">จับคู่แล้ว ใช้ที่อยู่ด้านล่าง หรืออัปเดตจาก Wireless debugging → IP address & Port</string> - <string name="wadb_lede_done_long">อัปเดตขีดจำกัดโพรเซสลูกผ่าน Wireless debugging แล้ว</string> - <string name="wadb_confirmed_on">Android ยืนยันแล้วว่าขีดจำกัดเปิดอยู่</string> - <string name="wadb_confirmed_off">Android ยืนยันแล้วว่าขีดจำกัดปิดอยู่</string> - <string name="wadb_pair_group">2 · จับคู่ Wireless debugging</string> - <string name="wadb_pair_address">ที่อยู่ IP และพอร์ตของป๊อปอัปการจับคู่</string> - <string name="wadb_pin">รหัสจับคู่ (PIN)</string> - <string name="wadb_pin_placeholder">6 หลัก</string> - <string name="wadb_pair">จับคู่</string> - <string name="wadb_apply_group">2 · ปรับใช้ผ่าน Wireless debugging</string> - <string name="wadb_connect_address">ที่อยู่ IP และพอร์ตสำหรับเชื่อมต่อ</string> - <string name="wadb_pair_again">จับคู่อีกครั้ง</string> - <string name="wadb_turn_off">ปิดขีดจำกัด</string> - <string name="wadb_other_ways">วิธีอื่นในการเปลี่ยนค่านี้</string> - <string name="wadb_dev_try_first">1 · ตัวเลือกสำหรับนักพัฒนา (ลองก่อน)</string> - <string name="wadb_restrict_on">ปิด “ปิดการจำกัดการประมวลผลข้อมูลย่อย”</string> - <string name="wadb_restrict_off">เปิด “ปิดการจำกัดการประมวลผลข้อมูลย่อย”</string> - <string name="wadb_computer_last">3 · ADB จากคอมพิวเตอร์ (ทางเลือกสุดท้าย)</string> - <string name="wadb_only_if">ใช้เฉพาะเมื่อ Wireless debugging ใช้งานไม่ได้</string> - <string name="wadb_computer_group">3 · ADB จากคอมพิวเตอร์ (ทางเลือกสุดท้าย)</string> <string name="ctrl_color">สี</string> <string name="ctrl_custom">กำหนดเอง</string> <string name="ctrl_opacity">ความโปร่งใส</string> @@ -1615,8 +1574,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">ล้างโฟลเดอร์ล็อกเซสชัน %1$d โฟลเดอร์แล้ว</item> </plurals> - <string name="main_wadb_pair_failed">การจับคู่ Wireless debugging ล้มเหลว</string> - <string name="main_wadb_command_failed">คำสั่ง Wireless debugging ล้มเหลว</string> <string name="main_wadb_unavailable">Wireless debugging ไม่พร้อมใช้งาน</string> <string name="main_adb_copied">คัดลอกคำสั่ง ADB แล้ว</string> <string name="main_pick_roms">เลือกโฟลเดอร์ ROM</string> @@ -2436,10 +2393,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s %2$s\n\n%3$s</string> <string name="display_session">การแสดงผลของเซสชัน</string> - <string name="display_resolution">ความละเอียด</string> + <string name="display_zero_copy">การแสดงผลแบบไม่คัดลอก</string> + <string name="display_resolution_landscape">ความละเอียดแนวนอน</string> + <string name="display_resolution_portrait">ความละเอียดแนวตั้ง</string> + <string name="display_follow_landscape">ตามแนวนอน (%1$d×%2$d)</string> + <string name="display_follow_portrait">ตามแนวตั้ง (%1$d×%2$d)</string> <string name="display_game_fit">การแสดงเกม 16:9 ให้พอดี</string> <string name="display_game_fit_hint">วิธีที่เกม 16:9 แสดงพอดีกับหน้าจอนี้ มีผลในเซสชันถัดไป</string> <string name="display_game_fit_unavailable">เลือกพอดีหน้าจอ หรือขนาดกำหนดเองที่แคบกว่า 16:9</string> + <string name="display_avoid_notch">เลี่ยงรอยบาก</string> + <string name="display_avoid_notch_hint">ไม่แสดงภาพทับช่องกล้อง มีผลเมื่อคุณกลับเข้าสู่เซสชัน</string> <string name="display_preserve">คงสัดส่วนไว้</string> <string name="display_stretch">ยืดให้พอดีหน้าจอ</string> <string name="display_image_scaling">การปรับขนาดภาพ</string> @@ -2726,6 +2689,7 @@ <string name="stores_login_error_ssl">การเชื่อมต่อไปยังหน้าลงชื่อเข้าใช้ไม่ปลอดภัย</string> <string name="stores_login_error_verification">ไม่สามารถยืนยันการลงชื่อเข้าใช้ได้ ลองใหม่</string> <string name="stores_login_error_generic">ลงชื่อเข้าใช้ล้มเหลว ลองใหม่</string> + <string name="stores_login_continue_in_browser">%1$s ต้องการอีกหนึ่งขั้นตอน ทำให้เสร็จในเบราว์เซอร์ที่เปิดขึ้น แล้วลองอีกครั้ง</string> <string name="common_close">ปิด</string> <string name="common_back">กลับ</string> <string name="common_edit">แก้ไข</string> @@ -3106,7 +3070,7 @@ <string name="hand_camera_done">เสร็จสิ้น</string> <string name="glasses_xreal_network_missing">กำลังรอการเชื่อมต่อ USB Ethernet ของแว่นตา โทรศัพท์นี้อาจไม่เปิดให้แอปเข้าถึงการเชื่อมต่อนี้</string> <string name="glasses_xreal_connection_failed">การเชื่อมต่อ XREAL ขาดหายหรือได้รับการตอบกลับที่ไม่รองรับ กำลังลองใหม่…</string> - <string name="glasses_xreal_experimental">รองรับ 1S แบบทดลอง ใช้โหมด Follow และปิดการกันสั่นในเมนูของแว่นตา ทิศทางการติดตามและโหมดการแสดงผลยังต้องทดสอบกับอุปกรณ์จริง</string> + <string name="glasses_xreal_experimental">รองรับ XREAL 1S, One, One Pro, One Pro+ และ Aura แบบทดลอง ใช้โหมด Follow และปิดการกันสั่นในเมนูของแว่นตา สำหรับ Aura ให้ปิด Spatial Anchor ด้วย การติดตามศีรษะและการสลับ 2D/3D ผ่านการทดสอบบน Aura และ One Pro+ แล้ว</string> <string name="glasses_pro2_experimental">การติดตามศีรษะแบบทดลองสำหรับ Pro 2 ยังไม่รองรับการปรับความสว่าง ระดับเสียง และการสลับโหมดการแสดงผล</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">โหมด Cardboard</string> @@ -3980,6 +3944,7 @@ <string name="addons_sort_downloads">ดาวน์โหลดมากที่สุด</string> <string name="addons_category_all">ทุกหมวดหมู่</string> <string name="addons_none_found">ไม่พบแอดออน</string> + <string name="addons_curse_busy">ปิด CurseForge ก่อน</string> <string name="addons_unreachable">ไม่สามารถเชื่อมต่อ %1$s ได้</string> <string name="addons_no_file">ไม่มีไฟล์สำหรับเกมเวอร์ชันนี้</string> <string name="input_reset_positions">รีเซ็ตตำแหน่ง</string> @@ -4083,4 +4048,6 @@ <string name="theme_custom_signal">จุดเน้น</string> <string name="theme_custom_good">สำเร็จ</string> <string name="theme_custom_error">ข้อผิดพลาด</string> + <string name="hud_only_during_game">แสดง HUD เฉพาะขณะเล่นเกม</string> + <string name="hud_only_during_game_hint">ซ่อน HUD เมื่อไม่พบเฟรมของเกม</string> </resources> diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index bdcb3b8b0f..581d4aecbb 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 çıkışı</string> <string name="mode_hdr_unavailable">Kullanılamıyor: %1$s.</string> - <string name="mode_hdr_restart">Uygulamak için uygulamayı yeniden başlatın.</string> <string name="mode_drivers">Sürücüler</string> <string name="mode_gpu_drivers">GPU sürücüleri</string> <string name="mode_gpu_drivers_hint">Steam ve Masaüstü tarafından paylaşılır. Bileşenler sayfasından ayarlanır.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Başlangıç</string> <string name="mode_startup_session">Açılışta başlat</string> <string name="mode_startup_session_hint">DroidDeck açıldığında bu oturumu başlatır.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Sürümler kontrol ediliyor…</string> <string name="mode_decky_ready">%1$s yüklenmeye hazır.</string> <string name="mode_decky_none">Uyumlu derleme bulunamadı. Daha sonra tekrar deneyin.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Güncel · %1$s</string> <string name="mode_decky_loader">Yükleyici</string> <string name="mode_decky_install_latest">En yenisini yükle</string> - <string name="decky_channel">Güncelleme kanalı</string> - <string name="decky_channel_hint">Hangi Decky Loader sürümlerinin yükleneceği. Decky\'nin kendi güncelleyicisi de aynı kanalı kullanır.</string> <string name="decky_channel_stable">Kararlı</string> <string name="decky_channel_prerelease">Ön sürüm</string> <string name="decky_channel_testing">Test</string> <string name="decky_channel_failed">Decky güncelleme kanalı kaydedilemedi</string> - <string name="mode_decky_on">Steam ile başlar. Açıkken bu cihazdaki diğer uygulamalar Steam\'i kontrol edebilir.</string> - <string name="mode_decky_off">Kapalı. Steam\'in uzaktan hata ayıklama bağlantı noktası kapalı kalır.</string> <string name="mode_decky_remove_title">Decky Loader kaldırılsın mı?</string> <string name="mode_decky_remove_text">Yükleyiciyi kaldırır. Eklentileriniz ve ayarlarınız korunur.</string> <string name="mode_client">İstemci</string> @@ -945,13 +939,15 @@ <string name="setup_launcher_orientation_auto">Cihaz dönüşünü izle</string> <string name="setup_orientation_portrait">Dikey</string> <string name="setup_session_orientation">Oturum yönü</string> - <string name="setup_session_orientation_hint">Steam, oyunlar, masaüstü ve kumanda düzenleyicisi için geçerlidir. Çözünürlük ön ayarları oturumla birlikte döner; özel genişlik ve yükseklik girildiği gibi kalır.</string> + <string name="setup_session_orientation_hint">Steam, oyunlar, masaüstü ve kumanda düzenleyicisi için geçerlidir. Çözünürlük ön ayarları oturumla birlikte döner; bir yön diğerini izlediğinde özel genişlik ve yükseklik eşleşmek üzere yer değiştirir.</string> <string name="setup_orientation_auto">Otomatik yatay</string> <string name="setup_orientation_landscape">Yatay</string> <string name="setup_orientation_reverse">Ters yatay</string> <string name="setup_fullscreen">Tam ekran</string> <string name="setup_fullscreen_on">Android durum ve gezinme çubuklarını gizler</string> <string name="setup_fullscreen_off">Android durum ve gezinme çubuklarını gösterir</string> + <string name="setup_page_swipe">Sayfalar arasında kaydır</string> + <string name="setup_page_swipe_hint">Sekme değiştirmek için sayfa boyunca kaydırın.</string> <string name="setup_dual_screen_launcher">Çift ekranlı başlatıcı</string> <string name="setup_dual_screen_launcher_hint">Otomatik, yerleşik ikinci ekranı olan el konsollarında başlatıcı bölümlerini (Steam, Kitaplık, Mağazalar ve diğerleri) ikinci ekrana yerleştirir. Açık, herhangi bir ikinci ekranı kullanır. Kapalı, başlatıcıyı tek ekranda tutar.</string> <string name="setup_dual_screen_sessions">Çift ekranlı oturumlar</string> @@ -1272,8 +1268,6 @@ <string name="gate_open_dev">Geliştirici seçeneklerini aç</string> <string name="gate_no_toggle">Bu Android sürümünde bunun için bir anahtar yok, bu yüzden DroidDeck bunu Kablosuz hata ayıklama üzerinden değiştirir. Yaklaşık bir dakika sürer, bilgisayar gerekmez.</string> <string name="gate_needs_wifi">Kablosuz hata ayıklama Wi-Fi gerektirir. Herhangi bir ağ işe yarar; internet gerekmez.</string> - <string name="gate_needs_notifications">Eşleştirme kodu bir bildirime gelir. DroidDeck için bildirimlere izin verin veya Diğer yollar\'ı kullanın.</string> - <string name="gate_allow_notifications">Bildirimlere izin ver</string> <string name="gate_step1">Ayarlar → Geliştirici seçenekleri → Kablosuz hata ayıklama\'yı açın</string> <string name="gate_step2">“Eşleştirme koduyla cihaz eşle” seçeneğine dokunun</string> <string name="gate_step3">Kodu DroidDeck bildirimine yazın</string> @@ -1290,48 +1284,13 @@ <string name="gate_status">Durum</string> <string name="gate_polling">Her 2 saniyede bir kontrol ediliyor. Kapandığında bu sayfa kapanır.</string> <string name="gate_other_ways">Diğer yollar</string> - <string name="gate_other_toggle">Kablosuz hata ayıklama, elle adres girme, bilgisayardan ADB</string> - <string name="gate_other_no_toggle">Elle adres girme, bilgisayardan ADB, Geliştirici seçenekleri</string> <string name="gate_use_wireless_instead">Bunun yerine Kablosuz hata ayıklamayı kullan</string> <string name="gate_some_roms">Bazı ROM\'lar bu anahtarı yine de ekler. Geliştirici seçenekleri\'nde “alt süreç” ifadesini arayın.</string> - <string name="gate_manual_hint">Bildirim işe yaramazsa açılır penceredeki adresi ve kodu kendiniz girin.</string> - <string name="gate_enter_manually">Adresi elle girin</string> <string name="gate_from_computer">ADB\'li bir bilgisayardan:</string> <string name="gate_copy_command">Komutu kopyala</string> <string name="gate_sidequest_steps">Başlığı bir bilgisayara bağlayın ve SideQuest’i açın. “Run ADB Command”, ardından “Custom Command” seçin, aşağıda gösterilen komutu yazın ve “Run Command” seçin.</string> <string name="gate_choose_display">Android Ayarları\'nın hangi ekranda açılacağını seçin.</string> <string name="gate_main_screen">Ana ekran</string> - <string name="wadb_finding_port">Eşleşti. Kablosuz hata ayıklama bağlantı noktası bulunuyor…</string> - <string name="wadb_enter_port">Eşleşti. Bağlantı noktasını Ayarlar\'dan girin.</string> - <string name="wadb_applying">Cihaz bulundu. Ayar uygulanıyor…</string> - <string name="wadb_apply_failed">Otomatik olarak uygulanamadı. Aşağıdaki adresi kontrol edip yeniden deneyin. %1$s</string> - <string name="wadb_title_wireless">Kablosuz hata ayıklama</string> - <string name="wadb_title_done">Alt süreç sınırı güncellendi</string> - <string name="wadb_title">Alt süreç sınırını değiştir</string> - <string name="wadb_lede_compact0">Seçenek yoksa Kablosuz hata ayıklama üzerinden eşleyin.</string> - <string name="wadb_lede_compact1">Eşleşti. IP adresini ve bağlantı noktasını Kablosuz hata ayıklama\'da kontrol edin.</string> - <string name="wadb_lede_done">Alt süreç sınırı güncellendi.</string> - <string name="wadb_lede0">Geliştirici seçenekleri\'nde alt süreç ayarı yoksa 2. adımı kullanın. Geliştirici seçenekleri → Kablosuz hata ayıklama → Eşleştirme koduyla cihaz eşle\'yi açın.</string> - <string name="wadb_lede1">Eşleşti. Aşağıdaki adresi kullanın veya Kablosuz hata ayıklama → IP adresi ve bağlantı noktası\'ndan güncelleyin.</string> - <string name="wadb_lede_done_long">Alt süreç sınırı Kablosuz hata ayıklama üzerinden güncellendi.</string> - <string name="wadb_confirmed_on">Android sınırın açık olduğunu onayladı.</string> - <string name="wadb_confirmed_off">Android sınırın kapalı olduğunu onayladı.</string> - <string name="wadb_pair_group">2 · Kablosuz hata ayıklamayı eşle</string> - <string name="wadb_pair_address">Eşleştirme açılır penceresinin IP adresi ve bağlantı noktası</string> - <string name="wadb_pin">Eşleştirme kodu (PIN)</string> - <string name="wadb_pin_placeholder">6 hane</string> - <string name="wadb_pair">Eşle</string> - <string name="wadb_apply_group">2 · Kablosuz hata ayıklama üzerinden uygula</string> - <string name="wadb_connect_address">Bağlantı IP adresi ve bağlantı noktası</string> - <string name="wadb_pair_again">Yeniden eşle</string> - <string name="wadb_turn_off">Sınırı kapat</string> - <string name="wadb_other_ways">Değiştirmenin diğer yolları</string> - <string name="wadb_dev_try_first">1 · Geliştirici seçenekleri (önce bunu deneyin)</string> - <string name="wadb_restrict_on">“Alt işlem kısıtlamalarını devre dışı bırak” seçeneğini kapalı olarak ayarlayın.</string> - <string name="wadb_restrict_off">“Alt işlem kısıtlamalarını devre dışı bırak” seçeneğini açık olarak ayarlayın.</string> - <string name="wadb_computer_last">3 · Bilgisayardan ADB (son yöntem)</string> - <string name="wadb_only_if">Yalnızca Kablosuz hata ayıklama kullanılamıyorsa.</string> - <string name="wadb_computer_group">3 · Bilgisayardan ADB (son yöntem)</string> <string name="ctrl_color">Renk</string> <string name="ctrl_custom">Özel</string> <string name="ctrl_opacity">Opaklık</string> @@ -1619,8 +1578,6 @@ <item quantity="one">%1$d oturum günlüğü klasörü temizlendi.</item> <item quantity="other">%1$d oturum günlüğü klasörü temizlendi.</item> </plurals> - <string name="main_wadb_pair_failed">Kablosuz hata ayıklama eşlemesi başarısız oldu</string> - <string name="main_wadb_command_failed">Kablosuz hata ayıklama komutu başarısız oldu</string> <string name="main_wadb_unavailable">Kablosuz hata ayıklama kullanılamıyor</string> <string name="main_adb_copied">ADB komutu kopyalandı</string> <string name="main_pick_roms">ROM klasörünü seçin</string> @@ -2453,10 +2410,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Oturum ekranı</string> - <string name="display_resolution">Çözünürlük</string> + <string name="display_zero_copy">Kopyasız sunum</string> + <string name="display_resolution_landscape">Yatay çözünürlük</string> + <string name="display_resolution_portrait">Dikey çözünürlük</string> + <string name="display_follow_landscape">Yatayı izle (%1$d×%2$d)</string> + <string name="display_follow_portrait">Dikeyi izle (%1$d×%2$d)</string> <string name="display_game_fit">16:9 oyun sığdırma</string> <string name="display_game_fit_hint">16:9 oyunların bu ekrana nasıl sığacağı. Sonraki oturumda.</string> <string name="display_game_fit_unavailable">Ekrana Uydur\'u veya 16:9\'dan daha dar özel bir boyutu seçin.</string> + <string name="display_avoid_notch">Çentikten kaçın</string> + <string name="display_avoid_notch_hint">Görüntüyü kamera çentiğinin dışında tutar. Oturuma döndüğünüzde uygulanır.</string> <string name="display_preserve">Oranları koru</string> <string name="display_stretch">Ekrana uzat</string> <string name="display_image_scaling">Görüntü ölçekleme</string> @@ -2740,6 +2703,7 @@ <string name="stores_login_error_ssl">Oturum açma sayfasına bağlantı güvenli değil.</string> <string name="stores_login_error_verification">Oturum açma doğrulanamadı. Yeniden deneyin.</string> <string name="stores_login_error_generic">Oturum açma başarısız oldu. Yeniden deneyin.</string> + <string name="stores_login_continue_in_browser">%1$s bir adım daha istiyor. Açılan tarayıcıda tamamlayın, ardından yeniden deneyin.</string> <string name="common_close">Kapat</string> <string name="common_back">Geri</string> <string name="common_edit">Düzenle</string> @@ -3124,7 +3088,7 @@ <string name="hand_camera_done">Bitti</string> <string name="glasses_xreal_network_missing">Gözlüğün USB Ethernet bağlantısı bekleniyor. Bu telefon bu bağlantıyı uygulamalara açmıyor olabilir.</string> <string name="glasses_xreal_connection_failed">XREAL bağlantısı kesildi veya desteklenmeyen bir yanıt döndü. Yeniden deneniyor…</string> - <string name="glasses_xreal_experimental">Deneysel 1S desteği. Gözlük menüsünde Follow modunu kullanın ve görüntü sabitlemeyi kapatın. Takip yönlerinin ve ekran modlarının hâlâ cihazda test edilmesi gerekiyor.</string> + <string name="glasses_xreal_experimental">Deneysel XREAL 1S, One, One Pro, One Pro+ ve Aura desteği. Gözlük menüsünde Follow modunu kullanın ve görüntü sabitlemeyi kapatın; Aura üzerinde Spatial Anchor özelliğini de kapatın. Kafa takibi ve 2D/3D geçişi Aura ve One Pro+ üzerinde test edilmiştir.</string> <string name="glasses_pro2_experimental">Pro 2 için deneysel baş takibi. Parlaklık ve ses düzeyi ayarı ile ekran modu değiştirme henüz desteklenmiyor.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Cardboard modu</string> @@ -4010,6 +3974,7 @@ <string name="addons_sort_downloads">En çok indirilen</string> <string name="addons_category_all">Tüm kategoriler</string> <string name="addons_none_found">Eklenti bulunamadı</string> + <string name="addons_curse_busy">Önce CurseForge\'u kapatın</string> <string name="addons_unreachable">%1$s adresine ulaşılamadı</string> <string name="addons_no_file">Bu oyun sürümü için dosya yok</string> <string name="input_reset_positions">Konumları sıfırla</string> @@ -4113,4 +4078,6 @@ <string name="theme_custom_signal">Vurgular</string> <string name="theme_custom_good">Başarılı</string> <string name="theme_custom_error">Hata</string> + <string name="hud_only_during_game">HUD\'yi yalnızca oyun sırasında göster</string> + <string name="hud_only_during_game_hint">Oyun kareleri algılanmadığında HUD\'yi gizle.</string> </resources> diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 6259160400..8db1b46441 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Вивід HDR10</string> <string name="mode_hdr_unavailable">Недоступно: %1$s.</string> - <string name="mode_hdr_restart">Перезапустіть додаток, щоб застосувати.</string> <string name="mode_drivers">Драйвери</string> <string name="mode_gpu_drivers">Драйвери GPU</string> <string name="mode_gpu_drivers_hint">Спільні для Steam і робочого столу. Налаштовуються на сторінці «Компоненти».</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Запуск</string> <string name="mode_startup_session">Відкривати під час запуску</string> <string name="mode_startup_session_hint">Запускає цей сеанс під час запуску DroidDeck.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Пошук випусків…</string> <string name="mode_decky_ready">Можна встановити %1$s.</string> <string name="mode_decky_none">Сумісну збірку не знайдено. Спробуйте пізніше.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Актуальна версія · %1$s</string> <string name="mode_decky_loader">Завантажувач</string> <string name="mode_decky_install_latest">Установити останню версію</string> - <string name="decky_channel">Канал оновлень</string> - <string name="decky_channel_hint">Які випуски Decky Loader встановлювати. Власний засіб оновлення Decky використовує той самий канал.</string> <string name="decky_channel_stable">Стабільний</string> <string name="decky_channel_prerelease">Попередній</string> <string name="decky_channel_testing">Тестовий</string> <string name="decky_channel_failed">Не вдалося зберегти канал оновлень Decky</string> - <string name="mode_decky_on">Запускається разом зі Steam. Поки його ввімкнено, інші додатки на цьому пристрої можуть керувати Steam.</string> - <string name="mode_decky_off">Вимкнено. Порт віддаленого налагодження Steam залишається закритим.</string> <string name="mode_decky_remove_title">Видалити Decky Loader?</string> <string name="mode_decky_remove_text">Видаляє завантажувач. Ваші плагіни й налаштування зберігаються.</string> <string name="mode_client">Клієнт</string> @@ -959,13 +953,15 @@ <string name="setup_launcher_orientation_auto">Слідувати повороту пристрою</string> <string name="setup_orientation_portrait">Книжкова</string> <string name="setup_session_orientation">Орієнтація сеансу</string> - <string name="setup_session_orientation_hint">Застосовується до Steam, ігор, робочого столу й редактора контролера. Готові роздільні здатності повертаються разом із сеансом; власні ширина й висота залишаються як введено.</string> + <string name="setup_session_orientation_hint">Застосовується до Steam, ігор, робочого столу й редактора контролера. Готові роздільні здатності повертаються разом із сеансом; коли одна орієнтація слідує за іншою, власні ширина й висота міняються місцями.</string> <string name="setup_orientation_auto">Автоматично альбомна</string> <string name="setup_orientation_landscape">Альбомна</string> <string name="setup_orientation_reverse">Перевернута альбомна</string> <string name="setup_fullscreen">Повний екран</string> <string name="setup_fullscreen_on">Приховує рядок стану та панель навігації Android</string> <string name="setup_fullscreen_off">Показує рядок стану та панель навігації Android</string> + <string name="setup_page_swipe">Гортання сторінок свайпом</string> + <string name="setup_page_swipe_hint">Проведіть по сторінці, щоб змінити вкладку.</string> <string name="setup_dual_screen_launcher">Лаунчер для двох екранів</string> <string name="setup_dual_screen_launcher_hint">Автоматичний режим розміщує розділи лаунчера (Steam, Бібліотека, Магазини тощо) на вбудованому другому екрані портативних пристроїв. У режимі «Увімкнено» використовується будь-який другий дисплей. У режимі «Вимкнено» лаунчер залишається на одному екрані.</string> <string name="setup_dual_screen_sessions">Сеанси для двох екранів</string> @@ -1294,8 +1290,6 @@ <string name="gate_open_dev">Відкрити «Параметри розробника»</string> <string name="gate_no_toggle">У цій версії Android немає перемикача для цього, тож DroidDeck змінює налаштування через бездротове налагодження. Займає приблизно хвилину, комп’ютер не потрібен.</string> <string name="gate_needs_wifi">Бездротове налагодження потребує Wi-Fi. Підійде будь-яка мережа; інтернет не потрібен.</string> - <string name="gate_needs_notifications">Код поєднання приходить у сповіщенні. Дозвольте сповіщення для DroidDeck або скористайтеся розділом «Інші способи».</string> - <string name="gate_allow_notifications">Дозволити сповіщення</string> <string name="gate_step1">Відкрийте «Налаштування» → «Параметри розробника» → «Бездротове налагодження» і увімкніть його</string> <string name="gate_step2">Натисніть «Поєднати пристрій за кодом»</string> <string name="gate_step3">Введіть код у сповіщення DroidDeck</string> @@ -1312,48 +1306,13 @@ <string name="gate_status">Статус</string> <string name="gate_polling">Перевірка кожні 2 секунди. Ця сторінка закриється, коли це вимкнено.</string> <string name="gate_other_ways">Інші способи</string> - <string name="gate_other_toggle">Бездротове налагодження, адреса вручну, ADB з комп’ютера</string> - <string name="gate_other_no_toggle">Адреса вручну, ADB з комп’ютера, параметри розробника</string> <string name="gate_use_wireless_instead">Використати бездротове налагодження замість цього</string> <string name="gate_some_roms">Деякі прошивки все одно додають цей перемикач. Пошукайте «дочірній процес» у параметрах розробника.</string> - <string name="gate_manual_hint">Якщо сповіщення не працює, введіть адресу та код із вікна вручну.</string> - <string name="gate_enter_manually">Ввести адресу вручну</string> <string name="gate_from_computer">З комп’ютера з ADB:</string> <string name="gate_copy_command">Копіювати команду</string> <string name="gate_sidequest_steps">Підключіть шолом до комп’ютера й відкрийте SideQuest. Виберіть «Run ADB Command», потім «Custom Command», введіть команду, показану нижче, і виберіть «Run Command».</string> <string name="gate_choose_display">Виберіть, на якому екрані відкрити налаштування Android.</string> <string name="gate_main_screen">Головний екран</string> - <string name="wadb_finding_port">Поєднано. Пошук порту бездротового налагодження…</string> - <string name="wadb_enter_port">Поєднано. Введіть порт із налаштувань.</string> - <string name="wadb_applying">Пристрій знайдено. Застосування налаштування…</string> - <string name="wadb_apply_failed">Не вдалося застосувати автоматично. Перевірте адресу нижче і повторіть спробу. %1$s</string> - <string name="wadb_title_wireless">Бездротове налагодження</string> - <string name="wadb_title_done">Обмеження дочірніх процесів оновлено</string> - <string name="wadb_title">Змінити обмеження дочірніх процесів</string> - <string name="wadb_lede_compact0">Якщо цього параметра немає, поєднайтеся через бездротове налагодження.</string> - <string name="wadb_lede_compact1">Поєднано. Перевірте IP-адресу і порт у бездротовому налагодженні.</string> - <string name="wadb_lede_done">Обмеження дочірніх процесів оновлено.</string> - <string name="wadb_lede0">Використайте крок 2, якщо в параметрах розробника немає налаштування дочірніх процесів. Відкрийте «Параметри розробника» → «Бездротове налагодження» → «Поєднати пристрій за кодом».</string> - <string name="wadb_lede1">Поєднано. Використайте адресу нижче або оновіть її в розділі «Бездротове налагодження» → «IP-адреса та порт».</string> - <string name="wadb_lede_done_long">Обмеження дочірніх процесів оновлено через бездротове налагодження.</string> - <string name="wadb_confirmed_on">Android підтвердив, що обмеження увімкнено.</string> - <string name="wadb_confirmed_off">Android підтвердив, що обмеження вимкнено.</string> - <string name="wadb_pair_group">2 · Поєднати бездротове налагодження</string> - <string name="wadb_pair_address">IP-адреса і порт із вікна поєднання</string> - <string name="wadb_pin">Код поєднання (PIN)</string> - <string name="wadb_pin_placeholder">6 цифр</string> - <string name="wadb_pair">Поєднати</string> - <string name="wadb_apply_group">2 · Застосувати через бездротове налагодження</string> - <string name="wadb_connect_address">IP-адреса і порт з’єднання</string> - <string name="wadb_pair_again">Поєднати ще раз</string> - <string name="wadb_turn_off">Вимкнути обмеження</string> - <string name="wadb_other_ways">Інші способи змінити це</string> - <string name="wadb_dev_try_first">1 · Параметри розробника (спробуйте спершу)</string> - <string name="wadb_restrict_on">Вимкніть «Вимкнути обмеження для дочірніх процесів».</string> - <string name="wadb_restrict_off">Увімкніть «Вимкнути обмеження для дочірніх процесів».</string> - <string name="wadb_computer_last">3 · ADB з комп’ютера (останній варіант)</string> - <string name="wadb_only_if">Лише якщо бездротове налагодження недоступне.</string> - <string name="wadb_computer_group">3 · ADB з комп’ютера (останній варіант)</string> <string name="ctrl_color">Колір</string> <string name="ctrl_custom">Власний</string> <string name="ctrl_opacity">Непрозорість</string> @@ -1653,8 +1612,6 @@ <item quantity="many">Очищено %1$d папок журналів сеансів.</item> <item quantity="other">Очищено %1$d папки журналів сеансів.</item> </plurals> - <string name="main_wadb_pair_failed">Не вдалося створити пару через бездротове налагодження</string> - <string name="main_wadb_command_failed">Помилка команди бездротового налагодження</string> <string name="main_wadb_unavailable">Бездротове налагодження недоступне</string> <string name="main_adb_copied">Команду ADB скопійовано</string> <string name="main_pick_roms">Виберіть папку ROMs</string> @@ -2513,10 +2470,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Дисплей сеансу</string> - <string name="display_resolution">Роздільна здатність</string> + <string name="display_zero_copy">Показ без копіювання</string> + <string name="display_resolution_landscape">Роздільна здатність в альбомній орієнтації</string> + <string name="display_resolution_portrait">Роздільна здатність у портретній орієнтації</string> + <string name="display_follow_landscape">Як в альбомній (%1$d×%2$d)</string> + <string name="display_follow_portrait">Як у портретній (%1$d×%2$d)</string> <string name="display_game_fit">Вписування гри 16:9</string> <string name="display_game_fit_hint">Як ігри 16:9 вписуються в цей дисплей. З наступного сеансу.</string> <string name="display_game_fit_unavailable">Виберіть «Під екран» або власний розмір, вужчий за 16:9.</string> + <string name="display_avoid_notch">Обходити виріз</string> + <string name="display_avoid_notch_hint">Не виводить зображення під виріз камери. Застосовується після повернення до сесії.</string> <string name="display_preserve">Зберігати пропорції</string> <string name="display_stretch">Розтягнути на весь дисплей</string> <string name="display_image_scaling">Масштабування зображення</string> @@ -2803,6 +2766,7 @@ <string name="stores_login_error_ssl">З’єднання зі сторінкою входу не захищене.</string> <string name="stores_login_error_verification">Не вдалося підтвердити вхід. Спробуйте ще раз.</string> <string name="stores_login_error_generic">Вхід не вдався. Спробуйте ще раз.</string> + <string name="stores_login_continue_in_browser">%1$s потребує ще одного кроку. Завершіть його у відкритому браузері та спробуйте ще раз.</string> <string name="common_close">Закрити</string> <string name="common_back">Назад</string> <string name="common_edit">Редагувати</string> @@ -3195,7 +3159,7 @@ <string name="hand_camera_done">Готово</string> <string name="glasses_xreal_network_missing">Очікування з’єднання USB Ethernet від окулярів. Цей телефон може не надавати його додаткам.</string> <string name="glasses_xreal_connection_failed">З’єднання з XREAL перервалося або повернуло непідтримувану відповідь. Повторна спроба…</string> - <string name="glasses_xreal_experimental">Експериментальна підтримка 1S. Увімкніть режим Follow і вимкніть стабілізацію в меню окулярів. Напрямки відстеження й режими відображення ще потрібно перевірити на пристрої.</string> + <string name="glasses_xreal_experimental">Експериментальна підтримка XREAL 1S, One, One Pro, One Pro+ та Aura. Використовуйте режим Follow і вимкніть стабілізацію в меню окулярів; на Aura також вимкніть Spatial Anchor. Відстеження голови та перемикання між 2D/3D перевірено на Aura й One Pro+.</string> <string name="glasses_pro2_experimental">Експериментальне відстеження рухів голови для Pro 2. Налаштування яскравості й гучності та перемикання режимів відображення ще не підтримуються.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Режим Cardboard</string> @@ -4090,6 +4054,7 @@ <string name="addons_sort_downloads">Найбільше завантажень</string> <string name="addons_category_all">Усі категорії</string> <string name="addons_none_found">Аддонів не знайдено</string> + <string name="addons_curse_busy">Спочатку закрийте CurseForge</string> <string name="addons_unreachable">Не вдалося під’єднатися до %1$s</string> <string name="addons_no_file">Немає файлу для цієї версії гри</string> <string name="input_reset_positions">Скинути розташування</string> @@ -4193,4 +4158,6 @@ <string name="theme_custom_signal">Виділення</string> <string name="theme_custom_good">Успіх</string> <string name="theme_custom_error">Помилка</string> + <string name="hud_only_during_game">Показувати HUD лише під час гри</string> + <string name="hud_only_during_game_hint">Приховувати HUD, коли кадри гри не виявляються.</string> </resources> diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 424ff42df2..707c107c89 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">Xuất HDR10</string> <string name="mode_hdr_unavailable">Không khả dụng: %1$s.</string> - <string name="mode_hdr_restart">Khởi động lại ứng dụng để áp dụng.</string> <string name="mode_drivers">Driver</string> <string name="mode_gpu_drivers">Driver GPU</string> <string name="mode_gpu_drivers_hint">Dùng chung cho Steam và Desktop. Đặt ở trang Components.</string> @@ -333,7 +332,6 @@ <string name="mode_startup">Khởi động</string> <string name="mode_startup_session">Mở khi khởi chạy</string> <string name="mode_startup_session_hint">Bắt đầu phiên này khi DroidDeck khởi chạy.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Đang kiểm tra bản phát hành…</string> <string name="mode_decky_ready">Sẵn sàng cài %1$s.</string> <string name="mode_decky_none">Không tìm thấy bản build tương thích. Hãy thử lại sau.</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">Đã mới nhất · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Cài bản mới nhất</string> - <string name="decky_channel">Kênh cập nhật</string> - <string name="decky_channel_hint">Các bản phát hành Decky Loader sẽ cài. Trình cập nhật riêng của Decky dùng cùng kênh này.</string> <string name="decky_channel_stable">Ổn định</string> <string name="decky_channel_prerelease">Tiền phát hành</string> <string name="decky_channel_testing">Thử nghiệm</string> <string name="decky_channel_failed">Không thể lưu kênh cập nhật Decky</string> - <string name="mode_decky_on">Khởi động cùng Steam. Khi đang bật, các ứng dụng khác trên thiết bị này có thể điều khiển được Steam.</string> - <string name="mode_decky_off">Tắt. Cổng gỡ lỗi từ xa của Steam luôn đóng.</string> <string name="mode_decky_remove_title">Gỡ cài đặt Decky Loader?</string> <string name="mode_decky_remove_text">Gỡ bỏ loader. Plugin và thiết lập của bạn được giữ lại.</string> <string name="mode_client">Client</string> @@ -950,13 +944,15 @@ <string name="setup_launcher_orientation_auto">Theo hướng xoay thiết bị</string> <string name="setup_orientation_portrait">Dọc</string> <string name="setup_session_orientation">Hướng màn hình phiên</string> - <string name="setup_session_orientation_hint">Áp dụng cho Steam, game, desktop và trình chỉnh sửa tay cầm. Độ phân giải đặt sẵn xoay theo phiên; chiều rộng và chiều cao tùy chỉnh giữ nguyên như đã nhập.</string> + <string name="setup_session_orientation_hint">Áp dụng cho Steam, game, desktop và trình chỉnh sửa tay cầm. Độ phân giải đặt sẵn xoay theo phiên; khi một hướng theo hướng còn lại, chiều rộng và chiều cao tùy chỉnh được hoán đổi cho khớp.</string> <string name="setup_orientation_auto">Ngang tự động</string> <string name="setup_orientation_landscape">Ngang</string> <string name="setup_orientation_reverse">Ngang ngược</string> <string name="setup_fullscreen">Toàn màn hình</string> <string name="setup_fullscreen_on">Ẩn thanh trạng thái và thanh điều hướng của Android</string> <string name="setup_fullscreen_off">Hiện thanh trạng thái và thanh điều hướng của Android</string> + <string name="setup_page_swipe">Vuốt để chuyển trang</string> + <string name="setup_page_swipe_hint">Vuốt ngang trang để đổi thẻ.</string> <string name="setup_dual_screen_launcher">Trình khởi chạy hai màn hình</string> <string name="setup_dual_screen_launcher_hint">Tự động đưa các phần của trình khởi chạy (Steam, Thư viện, Cửa hàng và phần còn lại) lên màn hình thứ hai tích hợp của máy cầm tay. Bật dùng bất kỳ màn hình thứ hai nào. Tắt giữ trình khởi chạy trên một màn hình.</string> <string name="setup_dual_screen_sessions">Phiên chơi hai màn hình</string> @@ -1274,8 +1270,6 @@ <string name="gate_open_dev">Mở Tùy chọn cho nhà phát triển</string> <string name="gate_no_toggle">Phiên bản Android này không có công tắc cho việc đó, nên DroidDeck thay đổi nó qua Gỡ lỗi qua mạng không dây. Mất khoảng một phút, không cần máy tính.</string> <string name="gate_needs_wifi">Gỡ lỗi qua mạng không dây cần Wi-Fi. Mạng nào cũng được; không cần Internet.</string> - <string name="gate_needs_notifications">Mã ghép nối nằm trong một thông báo. Hãy cho phép thông báo cho DroidDeck, hoặc dùng Cách khác.</string> - <string name="gate_allow_notifications">Cho phép thông báo</string> <string name="gate_step1">Mở Settings → Developer options → Wireless debugging và bật nó lên</string> <string name="gate_step2">Nhấn “Pair device with pairing code”</string> <string name="gate_step3">Nhập mã vào thông báo của DroidDeck</string> @@ -1292,48 +1286,13 @@ <string name="gate_status">Trạng thái</string> <string name="gate_polling">Đang kiểm tra mỗi 2 giây. Trang này sẽ đóng khi nó tắt.</string> <string name="gate_other_ways">Cách khác</string> - <string name="gate_other_toggle">Gỡ lỗi qua mạng không dây, địa chỉ thủ công, ADB từ máy tính</string> - <string name="gate_other_no_toggle">Địa chỉ thủ công, ADB từ máy tính, Tùy chọn cho nhà phát triển</string> <string name="gate_use_wireless_instead">Dùng Gỡ lỗi qua mạng không dây thay vào đó</string> <string name="gate_some_roms">Một số ROM vẫn thêm công tắc này. Tìm “child process” trong Tùy chọn cho nhà phát triển.</string> - <string name="gate_manual_hint">Nếu thông báo không hoạt động, hãy tự nhập địa chỉ và mã của cửa sổ bật lên.</string> - <string name="gate_enter_manually">Nhập địa chỉ thủ công</string> <string name="gate_from_computer">Từ một máy tính có ADB:</string> <string name="gate_copy_command">Sao chép lệnh</string> <string name="gate_sidequest_steps">Kết nối kính với máy tính và mở SideQuest. Chọn “Run ADB Command”, rồi “Custom Command”, nhập lệnh hiển thị bên dưới và chọn “Run Command”.</string> <string name="gate_choose_display">Chọn màn hình để mở Android Settings.</string> <string name="gate_main_screen">Màn hình chính</string> - <string name="wadb_finding_port">Đã ghép nối. Đang tìm cổng Gỡ lỗi qua mạng không dây…</string> - <string name="wadb_enter_port">Đã ghép nối. Nhập cổng từ Settings.</string> - <string name="wadb_applying">Đã tìm thấy thiết bị. Đang áp dụng thiết lập…</string> - <string name="wadb_apply_failed">Không thể áp dụng tự động. Kiểm tra địa chỉ dưới đây và thử lại. %1$s</string> - <string name="wadb_title_wireless">Gỡ lỗi qua mạng không dây</string> - <string name="wadb_title_done">Đã cập nhật giới hạn tiến trình con</string> - <string name="wadb_title">Đổi giới hạn tiến trình con</string> - <string name="wadb_lede_compact0">Nếu thiếu tùy chọn này, hãy ghép nối qua Gỡ lỗi qua mạng không dây.</string> - <string name="wadb_lede_compact1">Đã ghép nối. Kiểm tra địa chỉ IP và cổng trong Gỡ lỗi qua mạng không dây.</string> - <string name="wadb_lede_done">Giới hạn tiến trình con đã được cập nhật.</string> - <string name="wadb_lede0">Dùng bước 2 nếu Tùy chọn cho nhà phát triển không có thiết lập tiến trình con. Mở Developer options → Wireless debugging → Pair device with pairing code.</string> - <string name="wadb_lede1">Đã ghép nối. Dùng địa chỉ dưới đây, hoặc cập nhật nó từ Wireless debugging → IP address & Port.</string> - <string name="wadb_lede_done_long">Giới hạn tiến trình con đã được cập nhật qua Gỡ lỗi qua mạng không dây.</string> - <string name="wadb_confirmed_on">Android xác nhận giới hạn đang bật.</string> - <string name="wadb_confirmed_off">Android xác nhận giới hạn đang tắt.</string> - <string name="wadb_pair_group">2 · Ghép nối Gỡ lỗi qua mạng không dây</string> - <string name="wadb_pair_address">Địa chỉ IP & cổng của cửa sổ bật lên ghép nối</string> - <string name="wadb_pin">Mã ghép nối (PIN)</string> - <string name="wadb_pin_placeholder">6 số</string> - <string name="wadb_pair">Ghép nối</string> - <string name="wadb_apply_group">2 · Áp dụng qua Gỡ lỗi qua mạng không dây</string> - <string name="wadb_connect_address">Địa chỉ IP & cổng kết nối</string> - <string name="wadb_pair_again">Ghép nối lại</string> - <string name="wadb_turn_off">Tắt giới hạn</string> - <string name="wadb_other_ways">Cách khác để đổi nó</string> - <string name="wadb_dev_try_first">1 · Tùy chọn cho nhà phát triển (thử trước)</string> - <string name="wadb_restrict_on">Đặt “Tắt các mục hạn chế đối với tiến trình con” thành tắt.</string> - <string name="wadb_restrict_off">Đặt “Tắt các mục hạn chế đối với tiến trình con” thành bật.</string> - <string name="wadb_computer_last">3 · ADB từ máy tính (phương án cuối)</string> - <string name="wadb_only_if">Chỉ khi Gỡ lỗi qua mạng không dây không khả dụng.</string> - <string name="wadb_computer_group">3 · ADB từ máy tính (phương án cuối)</string> <string name="ctrl_color">Màu</string> <string name="ctrl_custom">Tùy chỉnh</string> <string name="ctrl_opacity">Độ mờ</string> @@ -1615,8 +1574,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">Đã xóa %1$d thư mục log phiên.</item> </plurals> - <string name="main_wadb_pair_failed">Ghép nối Gỡ lỗi qua mạng không dây thất bại</string> - <string name="main_wadb_command_failed">Lệnh Gỡ lỗi qua mạng không dây thất bại</string> <string name="main_wadb_unavailable">Gỡ lỗi qua mạng không dây không khả dụng</string> <string name="main_adb_copied">Đã sao chép lệnh ADB</string> <string name="main_pick_roms">Chọn thư mục ROM</string> @@ -2436,10 +2393,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Hiển thị phiên</string> - <string name="display_resolution">Độ phân giải</string> + <string name="display_zero_copy">Hiển thị không sao chép</string> + <string name="display_resolution_landscape">Độ phân giải chiều ngang</string> + <string name="display_resolution_portrait">Độ phân giải chiều dọc</string> + <string name="display_follow_landscape">Theo chiều ngang (%1$d×%2$d)</string> + <string name="display_follow_portrait">Theo chiều dọc (%1$d×%2$d)</string> <string name="display_game_fit">Khớp game 16:9</string> <string name="display_game_fit_hint">Cách game 16:9 khớp với màn hình này. Từ phiên sau.</string> <string name="display_game_fit_unavailable">Chọn Khớp màn hình hoặc một kích thước tùy chỉnh hẹp hơn 16:9.</string> + <string name="display_avoid_notch">Tránh tai thỏ</string> + <string name="display_avoid_notch_hint">Giữ hình ảnh tránh khỏi phần khuyết camera. Áp dụng khi bạn quay lại phiên.</string> <string name="display_preserve">Giữ tỷ lệ</string> <string name="display_stretch">Kéo giãn để khớp màn hình</string> <string name="display_image_scaling">Chia tỷ lệ hình ảnh</string> @@ -2726,6 +2689,7 @@ <string name="stores_login_error_ssl">Kết nối đến trang đăng nhập không an toàn.</string> <string name="stores_login_error_verification">Không thể xác minh đăng nhập. Hãy thử lại.</string> <string name="stores_login_error_generic">Đăng nhập thất bại. Hãy thử lại.</string> + <string name="stores_login_continue_in_browser">%1$s cần thêm một bước. Hãy hoàn tất trong trình duyệt vừa mở, rồi thử lại.</string> <string name="common_close">Đóng</string> <string name="common_back">Quay lại</string> <string name="common_edit">Sửa</string> @@ -3106,7 +3070,7 @@ <string name="hand_camera_done">Xong</string> <string name="glasses_xreal_network_missing">Đang chờ kết nối USB Ethernet của kính. Điện thoại này có thể không cho ứng dụng truy cập kết nối đó.</string> <string name="glasses_xreal_connection_failed">Kết nối XREAL bị gián đoạn hoặc trả về phản hồi không được hỗ trợ. Đang thử lại…</string> - <string name="glasses_xreal_experimental">Hỗ trợ 1S thử nghiệm. Dùng chế độ Follow và tắt ổn định hình ảnh trong menu của kính. Hướng theo dõi và các chế độ hiển thị vẫn cần thử nghiệm trên thiết bị.</string> + <string name="glasses_xreal_experimental">Hỗ trợ thử nghiệm cho XREAL 1S, One, One Pro, One Pro+ và Aura. Dùng chế độ Follow và tắt ổn định hình ảnh trong menu của kính; trên Aura, hãy tắt cả Spatial Anchor. Tính năng theo dõi đầu và chuyển đổi 2D/3D đã được thử nghiệm trên Aura và One Pro+.</string> <string name="glasses_pro2_experimental">Theo dõi chuyển động đầu thử nghiệm cho Pro 2. Chưa hỗ trợ điều chỉnh độ sáng, âm lượng và chuyển chế độ hiển thị.</string> <string name="cardboard_title">Cardboard VR</string> <string name="cardboard_mode">Chế độ Cardboard</string> @@ -3980,6 +3944,7 @@ <string name="addons_sort_downloads">Tải nhiều nhất</string> <string name="addons_category_all">Tất cả danh mục</string> <string name="addons_none_found">Không tìm thấy addon</string> + <string name="addons_curse_busy">Hãy đóng CurseForge trước</string> <string name="addons_unreachable">Không thể kết nối tới %1$s</string> <string name="addons_no_file">Không có tệp cho phiên bản trò chơi này</string> <string name="input_reset_positions">Đặt lại vị trí</string> @@ -4083,4 +4048,6 @@ <string name="theme_custom_signal">Điểm nhấn</string> <string name="theme_custom_good">Thành công</string> <string name="theme_custom_error">Lỗi</string> + <string name="hud_only_during_game">Chỉ hiển thị HUD khi đang chơi</string> + <string name="hud_only_during_game_hint">Ẩn HUD khi không phát hiện khung hình trò chơi.</string> </resources> diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 4343a946ba..e95780a79c 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 输出</string> <string name="mode_hdr_unavailable">不可用:%1$s。</string> - <string name="mode_hdr_restart">重启应用以生效。</string> <string name="mode_drivers">驱动</string> <string name="mode_gpu_drivers">GPU 驱动</string> <string name="mode_gpu_drivers_hint">由 Steam 和桌面共享。在“组件”页面设置。</string> @@ -333,7 +332,6 @@ <string name="mode_startup">启动</string> <string name="mode_startup_session">启动时打开</string> <string name="mode_startup_session_hint">DroidDeck 启动时开始此会话。</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">正在检查发布版本…</string> <string name="mode_decky_ready">已就绪,可安装 %1$s。</string> <string name="mode_decky_none">未找到兼容的构建。请稍后重试。</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">已是最新 · %1$s</string> <string name="mode_decky_loader">加载器</string> <string name="mode_decky_install_latest">安装最新版</string> - <string name="decky_channel">更新通道</string> - <string name="decky_channel_hint">要安装哪种 Decky Loader 版本。Decky 自带的更新程序也使用相同的通道。</string> <string name="decky_channel_stable">稳定版</string> <string name="decky_channel_prerelease">预发布版</string> <string name="decky_channel_testing">测试版</string> <string name="decky_channel_failed">无法保存 Decky 更新通道</string> - <string name="mode_decky_on">随 Steam 启动。开启期间,本设备上的其他应用可能可以控制 Steam。</string> - <string name="mode_decky_off">已关闭。Steam 的远程调试端口保持关闭。</string> <string name="mode_decky_remove_title">卸载 Decky Loader?</string> <string name="mode_decky_remove_text">移除加载器。你的插件和设置会保留。</string> <string name="mode_client">客户端</string> @@ -950,13 +944,15 @@ <string name="setup_launcher_orientation_auto">跟随设备旋转</string> <string name="setup_orientation_portrait">竖屏</string> <string name="setup_session_orientation">会话方向</string> - <string name="setup_session_orientation_hint">适用于 Steam、游戏、桌面和手柄编辑器。分辨率预设会随会话旋转;自定义宽度和高度保持输入值不变。</string> + <string name="setup_session_orientation_hint">适用于 Steam、游戏、桌面和手柄编辑器。分辨率预设会随会话旋转;当一个方向跟随另一个方向时,自定义宽度和高度会互换以保持一致。</string> <string name="setup_orientation_auto">自动横屏</string> <string name="setup_orientation_landscape">横屏</string> <string name="setup_orientation_reverse">反向横屏</string> <string name="setup_fullscreen">全屏</string> <string name="setup_fullscreen_on">隐藏 Android 状态栏和导航栏</string> <string name="setup_fullscreen_off">显示 Android 状态栏和导航栏</string> + <string name="setup_page_swipe">滑动切换页面</string> + <string name="setup_page_swipe_hint">在页面上滑动即可切换标签。</string> <string name="setup_dual_screen_launcher">双屏启动器</string> <string name="setup_dual_screen_launcher_hint">自动会把启动器的各个板块(Steam、库、商店等)放到带内置副屏的掌机的第二块屏幕上。开启使用任意第二块显示屏。关闭则让启动器只显示在一块屏幕上。</string> <string name="setup_dual_screen_sessions">双屏会话</string> @@ -1357,8 +1353,6 @@ <string name="gate_open_dev">打开开发者选项</string> <string name="gate_no_toggle">此 Android 版本没有该开关,因此 DroidDeck 通过无线调试来修改。大约需要一分钟,无需电脑。</string> <string name="gate_needs_wifi">无线调试需要 Wi-Fi。任何网络都可以,不需要互联网。</string> - <string name="gate_needs_notifications">配对码会出现在通知中。请允许 DroidDeck 的通知,或使用“其他方式”。</string> - <string name="gate_allow_notifications">允许通知</string> <string name="gate_step1">打开“设置”→“开发者选项”→“无线调试”,并将其开启</string> <string name="gate_step2">点按“使用配对码配对设备”</string> <string name="gate_step3">在 DroidDeck 通知中输入配对码</string> @@ -1375,48 +1369,13 @@ <string name="gate_status">状态</string> <string name="gate_polling">每 2 秒检查一次。该设置关闭后,本页面会自动关闭。</string> <string name="gate_other_ways">其他方式</string> - <string name="gate_other_toggle">无线调试、手动地址、电脑 ADB</string> - <string name="gate_other_no_toggle">手动地址、电脑 ADB、开发者选项</string> <string name="gate_use_wireless_instead">改用无线调试</string> <string name="gate_some_roms">部分 Android ROM 仍会加入该开关。请在开发者选项中查找“子进程”。</string> - <string name="gate_manual_hint">若通知不起作用,请手动输入弹窗中的地址和配对码。</string> - <string name="gate_enter_manually">手动输入地址</string> <string name="gate_from_computer">通过装有 ADB 的电脑:</string> <string name="gate_copy_command">复制命令</string> <string name="gate_sidequest_steps">将头显连接到电脑并打开 SideQuest。依次选择“Run ADB Command”和“Custom Command”,输入下方显示的命令,然后选择“Run Command”。</string> <string name="gate_choose_display">选择在哪个屏幕上打开 Android 设置。</string> <string name="gate_main_screen">主屏幕</string> - <string name="wadb_finding_port">已配对。正在查找无线调试端口…</string> - <string name="wadb_enter_port">已配对。请输入设置中的端口。</string> - <string name="wadb_applying">已找到设备。正在应用设置…</string> - <string name="wadb_apply_failed">无法自动应用。请检查下方地址并重试。%1$s</string> - <string name="wadb_title_wireless">无线调试</string> - <string name="wadb_title_done">子进程限制已更新</string> - <string name="wadb_title">更改子进程限制</string> - <string name="wadb_lede_compact0">若缺少该选项,请通过无线调试配对。</string> - <string name="wadb_lede_compact1">已配对。请在无线调试中查看 IP 地址和端口。</string> - <string name="wadb_lede_done">子进程限制已更新。</string> - <string name="wadb_lede0">若开发者选项中没有子进程设置,请使用第 2 步。打开开发者选项 → 无线调试 → 使用配对码配对设备。</string> - <string name="wadb_lede1">已配对。请使用下方地址,或从无线调试 → IP 地址与端口更新它。</string> - <string name="wadb_lede_done_long">子进程限制已通过无线调试更新。</string> - <string name="wadb_confirmed_on">Android 已确认限制处于开启状态。</string> - <string name="wadb_confirmed_off">Android 已确认限制处于关闭状态。</string> - <string name="wadb_pair_group">2 · 配对无线调试</string> - <string name="wadb_pair_address">配对弹窗 IP 地址与端口</string> - <string name="wadb_pin">配对码(PIN)</string> - <string name="wadb_pin_placeholder">6 位数字</string> - <string name="wadb_pair">配对</string> - <string name="wadb_apply_group">2 · 通过无线调试应用更改</string> - <string name="wadb_connect_address">连接 IP 地址与端口</string> - <string name="wadb_pair_again">重新配对</string> - <string name="wadb_turn_off">关闭限制</string> - <string name="wadb_other_ways">其他修改方式</string> - <string name="wadb_dev_try_first">1 · 开发者选项(优先尝试)</string> - <string name="wadb_restrict_on">把“停止限制子进程”设为关。</string> - <string name="wadb_restrict_off">把“停止限制子进程”设为开。</string> - <string name="wadb_computer_last">3 · 电脑 ADB(最后手段)</string> - <string name="wadb_only_if">仅在无线调试不可用时使用。</string> - <string name="wadb_computer_group">3 · 电脑 ADB(最后手段)</string> <string name="ctrl_color">颜色</string> <string name="ctrl_custom">自定义</string> <string name="ctrl_opacity">不透明度</string> @@ -1698,8 +1657,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">已清除 %1$d 个会话日志文件夹。</item> </plurals> - <string name="main_wadb_pair_failed">无线调试配对失败</string> - <string name="main_wadb_command_failed">无线调试命令执行失败</string> <string name="main_wadb_unavailable">无线调试不可用</string> <string name="main_adb_copied">已复制 ADB 命令</string> <string name="main_pick_roms">选择 ROM 文件夹</string> @@ -2513,10 +2470,16 @@ <string name="driver_tag_bundle">Android + Linux</string> <string name="phantom_warning">%1$s。%2$s\n\n%3$s</string> <string name="display_session">会话显示</string> - <string name="display_resolution">分辨率</string> + <string name="display_zero_copy">零拷贝呈现</string> + <string name="display_resolution_landscape">横屏分辨率</string> + <string name="display_resolution_portrait">竖屏分辨率</string> + <string name="display_follow_landscape">跟随横屏 (%1$d×%2$d)</string> + <string name="display_follow_portrait">跟随竖屏 (%1$d×%2$d)</string> <string name="display_game_fit">16:9 游戏适配</string> <string name="display_game_fit_hint">16:9 游戏如何适配此屏幕。下次会话生效。</string> <string name="display_game_fit_unavailable">请选择“匹配屏幕”或比 16:9 更窄的自定义尺寸。</string> + <string name="display_avoid_notch">避开刘海</string> + <string name="display_avoid_notch_hint">让画面避开摄像头挖孔区域。返回会话时生效。</string> <string name="display_preserve">保持比例</string> <string name="display_stretch">拉伸至屏幕</string> <string name="display_image_scaling">画面缩放</string> @@ -2800,6 +2763,7 @@ <string name="stores_login_error_ssl">与登录页面的连接不安全。</string> <string name="stores_login_error_verification">无法验证登录。请重试。</string> <string name="stores_login_error_generic">登录失败。请重试。</string> + <string name="stores_login_continue_in_browser">%1$s 还需要一个步骤。请在已打开的浏览器中完成,然后重试。</string> <string name="common_close">关闭</string> <string name="common_back">返回</string> <string name="common_edit">编辑</string> @@ -3106,7 +3070,7 @@ <string name="hand_camera_done">完成</string> <string name="glasses_xreal_network_missing">正在等待眼镜的 USB Ethernet 连接。这部手机可能不向应用开放此连接。</string> <string name="glasses_xreal_connection_failed">XREAL 连接中断或返回了不受支持的响应。正在重试…</string> - <string name="glasses_xreal_experimental">实验性 1S 支持。请在眼镜菜单中使用跟随模式并关闭防抖。追踪方向和显示模式仍需在设备上测试。</string> + <string name="glasses_xreal_experimental">实验性支持 XREAL 1S、One、One Pro、One Pro+ 和 Aura。请在眼镜菜单中使用 Follow 模式并关闭防抖;在 Aura 上还需关闭 Spatial Anchor。头部追踪和 2D/3D 切换已在 Aura 和 One Pro+ 上测试。</string> <string name="glasses_pro2_experimental">Pro 2 实验性头部追踪。暂不支持亮度、音量调节和显示模式切换。</string> <string name="stores_fact_developer">开发商</string> <string name="stores_fact_publisher">发行商</string> @@ -3980,6 +3944,7 @@ <string name="addons_sort_downloads">下载最多</string> <string name="addons_category_all">所有类别</string> <string name="addons_none_found">未找到插件</string> + <string name="addons_curse_busy">请先关闭 CurseForge</string> <string name="addons_unreachable">无法连接到 %1$s</string> <string name="addons_no_file">没有适用于此游戏版本的文件</string> <string name="input_reset_positions">重置位置</string> @@ -4083,4 +4048,6 @@ <string name="theme_custom_signal">高亮</string> <string name="theme_custom_good">成功</string> <string name="theme_custom_error">错误</string> + <string name="hud_only_during_game">仅在游戏期间显示 HUD</string> + <string name="hud_only_during_game_hint">未检测到游戏帧时隐藏 HUD。</string> </resources> diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 71ec80c4d0..28dcdcb49f 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 輸出</string> <string name="mode_hdr_unavailable">不可用:%1$s。</string> - <string name="mode_hdr_restart">重新啟動應用程式後生效。</string> <string name="mode_drivers">驅動程式</string> <string name="mode_gpu_drivers">GPU 驅動程式</string> <string name="mode_gpu_drivers_hint">Steam 和桌面共用,請在「組件」頁面設定。</string> @@ -333,7 +332,6 @@ <string name="mode_startup">啟動</string> <string name="mode_startup_session">啟動時開啟</string> <string name="mode_startup_session_hint">DroidDeck 啟動時開始此工作階段。</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">正在檢查發佈版本…</string> <string name="mode_decky_ready">可安裝 %1$s。</string> <string name="mode_decky_none">找不到兼容的版本,請稍後再試。</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">已是最新 · %1$s</string> <string name="mode_decky_loader">載入器</string> <string name="mode_decky_install_latest">安裝最新版本</string> - <string name="decky_channel">更新頻道</string> - <string name="decky_channel_hint">要安裝哪一種 Decky Loader 版本。Decky 本身的更新程式也會使用相同的頻道。</string> <string name="decky_channel_stable">穩定版</string> <string name="decky_channel_prerelease">預發佈版</string> <string name="decky_channel_testing">測試版</string> <string name="decky_channel_failed">無法儲存 Decky 更新頻道</string> - <string name="mode_decky_on">隨 Steam 啟動。啟用時,此裝置上的其他應用程式可能可以控制 Steam。</string> - <string name="mode_decky_off">已關閉。Steam 的遠端偵錯連接埠保持關閉。</string> <string name="mode_decky_remove_title">解除安裝 Decky Loader?</string> <string name="mode_decky_remove_text">移除載入器,你的插件和設定會保留。</string> <string name="mode_client">用戶端</string> @@ -949,13 +943,15 @@ <string name="setup_launcher_orientation_auto">跟隨裝置旋轉</string> <string name="setup_orientation_portrait">直向</string> <string name="setup_session_orientation">會話方向</string> - <string name="setup_session_orientation_hint">套用至 Steam、遊戲、桌面和控制器編輯器。解像度預設會隨會話旋轉;自訂的寬度和高度則維持輸入值。</string> + <string name="setup_session_orientation_hint">套用至 Steam、遊戲、桌面和控制器編輯器。解像度預設會隨會話旋轉;當一個方向跟隨另一個方向時,自訂的寬度和高度會互換以保持一致。</string> <string name="setup_orientation_auto">自動橫向</string> <string name="setup_orientation_landscape">橫向</string> <string name="setup_orientation_reverse">反向橫向</string> <string name="setup_fullscreen">全螢幕</string> <string name="setup_fullscreen_on">隱藏 Android 狀態列和導覽列</string> <string name="setup_fullscreen_off">顯示 Android 狀態列和導覽列</string> + <string name="setup_page_swipe">滑動切換頁面</string> + <string name="setup_page_swipe_hint">在頁面上滑動即可切換標籤。</string> <string name="setup_dual_screen_launcher">雙螢幕啟動器</string> <string name="setup_dual_screen_launcher_hint">自動會把啟動器各部分(Steam、收藏庫、商店及其他部分)放到內建雙螢幕手持裝置的第二螢幕。開啟會使用任何第二顯示器。關閉會將啟動器保持在單一螢幕。</string> <string name="setup_dual_screen_sessions">雙螢幕工作階段</string> @@ -1273,8 +1269,6 @@ <string name="gate_open_dev">開啟開發人員選項</string> <string name="gate_no_toggle">此 Android 版本沒有此開關,因此 DroidDeck 會透過無線偵錯更改。約需一分鐘,無需電腦。</string> <string name="gate_needs_wifi">無線偵錯需要 Wi-Fi。任何網絡都可以,無需連接互聯網。</string> - <string name="gate_needs_notifications">配對碼需在通知中輸入。請允許 DroidDeck 發出通知,或使用「其他方式」。</string> - <string name="gate_allow_notifications">允許通知</string> <string name="gate_step1">開啟「系統設定」→「開發人員選項」→「無線偵錯」,並將其開啟</string> <string name="gate_step2">輕按「使用配對碼配對裝置」</string> <string name="gate_step3">在 DroidDeck 通知中輸入配對碼</string> @@ -1291,48 +1285,13 @@ <string name="gate_status">狀態</string> <string name="gate_polling">每 2 秒檢查一次。關閉此開關後,本頁面會自動關閉。</string> <string name="gate_other_ways">其他方式</string> - <string name="gate_other_toggle">無線偵錯、手動輸入位址、電腦 ADB</string> - <string name="gate_other_no_toggle">手動輸入位址、電腦 ADB、開發人員選項</string> <string name="gate_use_wireless_instead">改用無線偵錯</string> <string name="gate_some_roms">部分 ROM 仍會提供此開關。請在開發人員選項中尋找「子進程」。</string> - <string name="gate_manual_hint">如果通知無效,請自行輸入彈出式視窗中的位址和配對碼。</string> - <string name="gate_enter_manually">手動輸入位址</string> <string name="gate_from_computer">在已安裝 ADB 的電腦上:</string> <string name="gate_copy_command">複製指令</string> <string name="gate_sidequest_steps">將頭戴裝置連接到電腦並開啟 SideQuest。依次選擇「Run ADB Command」和「Custom Command」,輸入下方顯示的指令,然後選擇「Run Command」。</string> <string name="gate_choose_display">選擇要在哪個螢幕開啟 Android 設定。</string> <string name="gate_main_screen">主螢幕</string> - <string name="wadb_finding_port">已配對,正在尋找無線偵錯連接埠…</string> - <string name="wadb_enter_port">已配對,請輸入「系統設定」中顯示的連接埠。</string> - <string name="wadb_applying">已找到裝置,正在套用設定…</string> - <string name="wadb_apply_failed">無法自動套用。請檢查下方的位址,然後重試。%1$s</string> - <string name="wadb_title_wireless">無線偵錯</string> - <string name="wadb_title_done">子進程限制已更新</string> - <string name="wadb_title">更改子進程限制</string> - <string name="wadb_lede_compact0">如果沒有此選項,請透過無線偵錯配對。</string> - <string name="wadb_lede_compact1">已配對。請檢查無線偵錯中的 IP 位址和連接埠。</string> - <string name="wadb_lede_done">子進程限制已更新。</string> - <string name="wadb_lede0">如果開發人員選項中沒有子進程設定,請使用步驟 2。開啟「開發人員選項」→「無線偵錯」→「使用配對碼配對裝置」。</string> - <string name="wadb_lede1">已配對。請使用下方的位址,或在「無線偵錯」→「IP 位址和連接埠」中更新。</string> - <string name="wadb_lede_done_long">已透過無線偵錯更新子進程限制。</string> - <string name="wadb_confirmed_on">Android 確認限制已開啟。</string> - <string name="wadb_confirmed_off">Android 確認限制已關閉。</string> - <string name="wadb_pair_group">2 · 配對無線偵錯</string> - <string name="wadb_pair_address">配對彈出式視窗中的 IP 位址和連接埠</string> - <string name="wadb_pin">配對碼(PIN)</string> - <string name="wadb_pin_placeholder">6 位數字</string> - <string name="wadb_pair">配對</string> - <string name="wadb_apply_group">2 · 透過無線偵錯套用</string> - <string name="wadb_connect_address">連線 IP 位址和連接埠</string> - <string name="wadb_pair_again">重新配對</string> - <string name="wadb_turn_off">關閉限制</string> - <string name="wadb_other_ways">其他更改方式</string> - <string name="wadb_dev_try_first">1 · 開發人員選項(請先嘗試)</string> - <string name="wadb_restrict_on">關閉「停用對子處理過程的限制」。</string> - <string name="wadb_restrict_off">開啟「停用對子處理過程的限制」。</string> - <string name="wadb_computer_last">3 · 電腦 ADB(最後手段)</string> - <string name="wadb_only_if">只在無法使用無線偵錯時使用。</string> - <string name="wadb_computer_group">3 · 電腦 ADB(最後手段)</string> <string name="ctrl_color">顏色</string> <string name="ctrl_custom">自訂</string> <string name="ctrl_opacity">不透明度</string> @@ -1614,8 +1573,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">已清除 %1$d 個會話記錄資料夾。</item> </plurals> - <string name="main_wadb_pair_failed">無線偵錯配對失敗</string> - <string name="main_wadb_command_failed">無線偵錯指令失敗</string> <string name="main_wadb_unavailable">無法使用無線偵錯</string> <string name="main_adb_copied">已複製 ADB 指令</string> <string name="main_pick_roms">選擇 ROM 資料夾</string> @@ -2433,10 +2390,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s。%2$s\n\n%3$s</string> <string name="display_session">會話顯示</string> - <string name="display_resolution">解像度</string> + <string name="display_zero_copy">零複製呈現</string> + <string name="display_resolution_landscape">橫向解析度</string> + <string name="display_resolution_portrait">直向解析度</string> + <string name="display_follow_landscape">跟隨橫向 (%1$d×%2$d)</string> + <string name="display_follow_portrait">跟隨直向 (%1$d×%2$d)</string> <string name="display_game_fit">16:9 遊戲顯示方式</string> <string name="display_game_fit_hint">16:9 遊戲如何配合此螢幕。下次會話生效。</string> <string name="display_game_fit_unavailable">請選擇「配合螢幕」或比 16:9 更窄的自訂尺寸。</string> + <string name="display_avoid_notch">避開瀏海</string> + <string name="display_avoid_notch_hint">讓畫面避開鏡頭挖孔區域。返回工作階段時生效。</string> <string name="display_preserve">保持比例</string> <string name="display_stretch">拉伸至螢幕</string> <string name="display_image_scaling">畫面縮放</string> @@ -2723,6 +2686,7 @@ <string name="stores_login_error_ssl">與登入頁面的連線不安全。</string> <string name="stores_login_error_verification">無法驗證登入,請再試一次。</string> <string name="stores_login_error_generic">登入失敗,請再試一次。</string> + <string name="stores_login_continue_in_browser">%1$s 還需要一個步驟。請在已開啟的瀏覽器中完成,然後再試一次。</string> <string name="common_close">關閉</string> <string name="common_back">返回</string> <string name="common_edit">編輯</string> @@ -3103,7 +3067,7 @@ <string name="hand_camera_done">完成</string> <string name="glasses_xreal_network_missing">正在等候眼鏡的 USB Ethernet 連線。這部手機可能不會向應用程式開放此連線。</string> <string name="glasses_xreal_connection_failed">XREAL 連線中斷或傳回不支援的回應。正在重試…</string> - <string name="glasses_xreal_experimental">實驗性 1S 支援。請在眼鏡選單中使用跟隨模式並關閉畫面穩定。追蹤方向和顯示模式仍需在裝置上測試。</string> + <string name="glasses_xreal_experimental">實驗性支援 XREAL 1S、One、One Pro、One Pro+ 和 Aura。請在眼鏡選單中使用 Follow 模式並關閉畫面穩定;在 Aura 上亦需關閉 Spatial Anchor。頭部追蹤和 2D/3D 切換已在 Aura 和 One Pro+ 上測試。</string> <string name="glasses_pro2_experimental">Pro 2 實驗性頭部追蹤。暫不支援亮度、音量調整及顯示模式切換。</string> <string name="stores_fact_developer">開發商</string> <string name="stores_fact_publisher">發行商</string> @@ -3980,6 +3944,7 @@ <string name="addons_sort_downloads">下載最多</string> <string name="addons_category_all">所有類別</string> <string name="addons_none_found">找不到插件</string> + <string name="addons_curse_busy">請先關閉 CurseForge</string> <string name="addons_unreachable">無法連接 %1$s</string> <string name="addons_no_file">沒有適用於此遊戲版本的檔案</string> <string name="input_reset_positions">重設位置</string> @@ -4083,4 +4048,6 @@ <string name="theme_custom_signal">重點標示</string> <string name="theme_custom_good">成功</string> <string name="theme_custom_error">錯誤</string> + <string name="hud_only_during_game">只在遊戲期間顯示 HUD</string> + <string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string> </resources> diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 105d095c98..a1f1534f67 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -281,7 +281,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 輸出</string> <string name="mode_hdr_unavailable">無法使用:%1$s。</string> - <string name="mode_hdr_restart">重新啟動應用程式後生效。</string> <string name="mode_drivers">驅動程式</string> <string name="mode_gpu_drivers">GPU 驅動程式</string> <string name="mode_gpu_drivers_hint">Steam 和桌面共用。請在「元件」頁面設定。</string> @@ -333,7 +332,6 @@ <string name="mode_startup">啟動</string> <string name="mode_startup_session">啟動時開啟</string> <string name="mode_startup_session_hint">DroidDeck 啟動時開始此工作階段。</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">正在檢查發行版本…</string> <string name="mode_decky_ready">已準備好安裝 %1$s。</string> <string name="mode_decky_none">未找到相容版本。請稍後再試。</string> @@ -342,14 +340,10 @@ <string name="mode_decky_current">已是最新 · %1$s</string> <string name="mode_decky_loader">載入器</string> <string name="mode_decky_install_latest">安裝最新版本</string> - <string name="decky_channel">更新頻道</string> - <string name="decky_channel_hint">要安裝哪一種 Decky Loader 版本。Decky 本身的更新程式也會使用相同的頻道。</string> <string name="decky_channel_stable">穩定版</string> <string name="decky_channel_prerelease">預先發行版</string> <string name="decky_channel_testing">測試版</string> <string name="decky_channel_failed">無法儲存 Decky 更新頻道</string> - <string name="mode_decky_on">隨 Steam 啟動。啟用後,此裝置上的其他應用程式可能可以控制 Steam。</string> - <string name="mode_decky_off">關閉。Steam 的遠端偵錯連接埠保持關閉。</string> <string name="mode_decky_remove_title">解除安裝 Decky Loader?</string> <string name="mode_decky_remove_text">移除載入器。你的外掛程式和設定會保留。</string> <string name="mode_client">用戶端</string> @@ -949,13 +943,15 @@ <string name="setup_launcher_orientation_auto">跟隨裝置旋轉</string> <string name="setup_orientation_portrait">直向</string> <string name="setup_session_orientation">工作階段方向</string> - <string name="setup_session_orientation_hint">套用至 Steam、遊戲、桌面和控制器編輯器。解析度預設會隨工作階段旋轉;自訂的寬度和高度則維持輸入值。</string> + <string name="setup_session_orientation_hint">套用至 Steam、遊戲、桌面和控制器編輯器。解析度預設會隨工作階段旋轉;當一個方向跟隨另一個方向時,自訂的寬度和高度會互換以保持一致。</string> <string name="setup_orientation_auto">自動橫向</string> <string name="setup_orientation_landscape">橫向</string> <string name="setup_orientation_reverse">反向橫向</string> <string name="setup_fullscreen">全螢幕</string> <string name="setup_fullscreen_on">隱藏 Android 狀態列和導覽列</string> <string name="setup_fullscreen_off">顯示 Android 狀態列和導覽列</string> + <string name="setup_page_swipe">滑動切換頁面</string> + <string name="setup_page_swipe_hint">在頁面上滑動即可切換分頁。</string> <string name="setup_dual_screen_launcher">雙螢幕啟動器</string> <string name="setup_dual_screen_launcher_hint">自動:在內建第二螢幕的掌機上,將啟動器區塊(Steam、收藏庫、商店等)放到第二螢幕。開啟:使用任一第二螢幕。關閉:啟動器維持在單一螢幕。</string> <string name="setup_dual_screen_sessions">雙螢幕工作階段</string> @@ -1273,8 +1269,6 @@ <string name="gate_open_dev">開啟開發人員選項</string> <string name="gate_no_toggle">此 Android 版本沒有該開關,因此 DroidDeck 會透過無線偵錯進行修改。大約需要一分鐘,無需電腦。</string> <string name="gate_needs_wifi">無線偵錯需要 Wi-Fi。任何網路都可以,不需要網際網路。</string> - <string name="gate_needs_notifications">配對碼會顯示在通知中。請允許 DroidDeck 傳送通知,或使用「其他方式」。</string> - <string name="gate_allow_notifications">允許通知</string> <string name="gate_step1">開啟「Android 設定」→「開發人員選項」→「無線偵錯」,並將其開啟</string> <string name="gate_step2">點擊「使用配對碼配對裝置」</string> <string name="gate_step3">將配對碼輸入 DroidDeck 通知中</string> @@ -1291,48 +1285,13 @@ <string name="gate_status">狀態</string> <string name="gate_polling">每 2 秒檢查一次。關閉此開關後此頁面會自動關閉。</string> <string name="gate_other_ways">其他方式</string> - <string name="gate_other_toggle">無線偵錯、手動輸入位址、電腦 ADB</string> - <string name="gate_other_no_toggle">手動輸入位址、電腦 ADB、開發人員選項</string> <string name="gate_use_wireless_instead">改用無線偵錯</string> <string name="gate_some_roms">部分 ROM 仍會提供此開關。請在開發人員選項中搜尋「子處理程序」。</string> - <string name="gate_manual_hint">如果通知方式沒有作用,請手動輸入彈出視窗中的位址和配對碼。</string> - <string name="gate_enter_manually">手動輸入位址</string> <string name="gate_from_computer">使用電腦上的 ADB:</string> <string name="gate_copy_command">複製指令</string> <string name="gate_sidequest_steps">將頭戴裝置連接到電腦並開啟 SideQuest。依序選擇「Run ADB Command」和「Custom Command」,輸入下方顯示的指令,然後選擇「Run Command」。</string> <string name="gate_choose_display">選擇在哪個螢幕上開啟 Android 設定。</string> <string name="gate_main_screen">主螢幕</string> - <string name="wadb_finding_port">已配對。正在尋找無線偵錯連接埠…</string> - <string name="wadb_enter_port">已配對。請輸入設定中的連接埠。</string> - <string name="wadb_applying">已找到裝置。正在套用設定…</string> - <string name="wadb_apply_failed">無法自動套用。請檢查下方位址後重試。%1$s</string> - <string name="wadb_title_wireless">無線偵錯</string> - <string name="wadb_title_done">子處理程序限制已更新</string> - <string name="wadb_title">變更子處理程序限制</string> - <string name="wadb_lede_compact0">如果沒有該選項,請透過無線偵錯進行配對。</string> - <string name="wadb_lede_compact1">已配對。請檢查無線偵錯中的 IP 位址和連接埠。</string> - <string name="wadb_lede_done">子處理程序限制已更新。</string> - <string name="wadb_lede0">如果開發人員選項中沒有子處理程序設定,請使用步驟 2。開啟開發人員選項 → 無線偵錯 → 使用配對碼配對裝置。</string> - <string name="wadb_lede1">已配對。請使用下面的位址,或在無線偵錯 → IP 位址和連接埠 中更新它。</string> - <string name="wadb_lede_done_long">已透過無線偵錯更新子處理程序限制。</string> - <string name="wadb_confirmed_on">Android 已確認限制處於開啟狀態。</string> - <string name="wadb_confirmed_off">Android 已確認限制處於關閉狀態。</string> - <string name="wadb_pair_group">2 · 配對無線偵錯</string> - <string name="wadb_pair_address">配對彈出視窗中的 IP 位址和連接埠</string> - <string name="wadb_pin">配對碼(PIN)</string> - <string name="wadb_pin_placeholder">6 位數字</string> - <string name="wadb_pair">配對</string> - <string name="wadb_apply_group">2 · 透過無線偵錯套用</string> - <string name="wadb_connect_address">連線 IP 位址和連接埠</string> - <string name="wadb_pair_again">重新配對</string> - <string name="wadb_turn_off">關閉限制</string> - <string name="wadb_other_ways">其他變更方式</string> - <string name="wadb_dev_try_first">1 · 開發人員選項(優先嘗試)</string> - <string name="wadb_restrict_on">關閉「停止限制子程序」。</string> - <string name="wadb_restrict_off">開啟「停止限制子程序」。</string> - <string name="wadb_computer_last">3 · 電腦 ADB(最後手段)</string> - <string name="wadb_only_if">僅在無線偵錯無法使用時使用。</string> - <string name="wadb_computer_group">3 · 電腦 ADB(最後手段)</string> <string name="ctrl_color">顏色</string> <string name="ctrl_custom">自訂</string> <string name="ctrl_opacity">不透明度</string> @@ -1614,8 +1573,6 @@ <plurals name="main_logs_cleared"> <item quantity="other">已清除 %1$d 個工作階段日誌資料夾。</item> </plurals> - <string name="main_wadb_pair_failed">無線偵錯配對失敗</string> - <string name="main_wadb_command_failed">無線偵錯指令失敗</string> <string name="main_wadb_unavailable">無法使用無線偵錯</string> <string name="main_adb_copied">已複製 ADB 指令</string> <string name="main_pick_roms">選擇 ROM 資料夾</string> @@ -2433,10 +2390,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s。%2$s\n\n%3$s</string> <string name="display_session">工作階段顯示</string> - <string name="display_resolution">解析度</string> + <string name="display_zero_copy">零複製呈現</string> + <string name="display_resolution_landscape">橫向解析度</string> + <string name="display_resolution_portrait">直向解析度</string> + <string name="display_follow_landscape">跟隨橫向 (%1$d×%2$d)</string> + <string name="display_follow_portrait">跟隨直向 (%1$d×%2$d)</string> <string name="display_game_fit">16:9 遊戲顯示方式</string> <string name="display_game_fit_hint">16:9 遊戲如何配合此螢幕。下次工作階段生效。</string> <string name="display_game_fit_unavailable">請選擇「符合螢幕」或比 16:9 更窄的自訂尺寸。</string> + <string name="display_avoid_notch">避開瀏海</string> + <string name="display_avoid_notch_hint">讓畫面避開鏡頭挖孔區域。返回工作階段時生效。</string> <string name="display_preserve">維持比例</string> <string name="display_stretch">延展至螢幕</string> <string name="display_image_scaling">畫面縮放</string> @@ -2723,6 +2686,7 @@ <string name="stores_login_error_ssl">與登入頁面的連線不安全。</string> <string name="stores_login_error_verification">無法驗證登入。請再試一次。</string> <string name="stores_login_error_generic">登入失敗。請再試一次。</string> + <string name="stores_login_continue_in_browser">%1$s 還需要一個步驟。請在已開啟的瀏覽器中完成,然後再試一次。</string> <string name="common_close">關閉</string> <string name="common_back">返回</string> <string name="common_edit">編輯</string> @@ -3103,7 +3067,7 @@ <string name="hand_camera_done">完成</string> <string name="glasses_xreal_network_missing">正在等待眼鏡的 USB Ethernet 連線。這支手機可能不會向應用程式開放此連線。</string> <string name="glasses_xreal_connection_failed">XREAL 連線中斷或傳回不支援的回應。正在重試…</string> - <string name="glasses_xreal_experimental">實驗性 1S 支援。請在眼鏡選單中使用跟隨模式並關閉畫面穩定。追蹤方向和顯示模式仍需在實機上測試。</string> + <string name="glasses_xreal_experimental">實驗性支援 XREAL 1S、One、One Pro、One Pro+ 和 Aura。請在眼鏡選單中使用 Follow 模式並關閉畫面穩定;在 Aura 上還需關閉 Spatial Anchor。頭部追蹤和 2D/3D 切換已在 Aura 和 One Pro+ 上測試。</string> <string name="glasses_pro2_experimental">Pro 2 實驗性頭部追蹤。尚不支援亮度、音量調整及顯示模式切換。</string> <string name="stores_fact_developer">開發商</string> <string name="stores_fact_publisher">發行商</string> @@ -3980,6 +3944,7 @@ <string name="addons_sort_downloads">下載最多</string> <string name="addons_category_all">所有類別</string> <string name="addons_none_found">找不到插件</string> + <string name="addons_curse_busy">請先關閉 CurseForge</string> <string name="addons_unreachable">無法連線至 %1$s</string> <string name="addons_no_file">沒有適用於此遊戲版本的檔案</string> <string name="input_reset_positions">重設位置</string> @@ -4083,4 +4048,6 @@ <string name="theme_custom_signal">醒目標示</string> <string name="theme_custom_good">成功</string> <string name="theme_custom_error">錯誤</string> + <string name="hud_only_during_game">僅在遊戲期間顯示 HUD</string> + <string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string> </resources> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a2e6d905e8..69b03e75f6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -35,8 +35,9 @@ <string name="wall_settings_fps" translatable="false">Frame rate (fps)</string> <string name="wall_settings_match" translatable="false">Match screen</string> <string name="wall_settings_speed" translatable="false">Scroll speed</string> + <string name="loading_first_run">First launch also downloads Proton Experimental (about 400 MB) and sets Steam up. After this it starts much faster.</string> <string-array name="loading_hints"> - <item>First run downloads Steam. This may take a few minutes.</item> + <item>DroidDeck downloads Steam in the background while you set up, so your first launch is quicker.</item> <item>Your controller shows up to Steam as a Steam Deck controller. Switch it to a Steam Controller, DualShock 4, DualSense or Xbox 360 pad in the session settings; it applies next session.</item> <item>Hold Back on your controller to open Steam\'s Quick Access menu. Hold Back for Steam shortcuts must be on in the session settings.</item> <item>Background behavior decides what happens when you leave the app: Native readies Steam for sleep, Auto pauses it, Manual waits for Resume, Never keeps it running.</item> @@ -309,7 +310,6 @@ <string name="mode_hdr">HDR</string> <string name="mode_hdr10">HDR10 output</string> <string name="mode_hdr_unavailable">Not available: %1$s.</string> - <string name="mode_hdr_restart">Restart the app to apply.</string> <string name="mode_drivers">Drivers</string> <string name="mode_gpu_drivers">GPU drivers</string> <string name="mode_gpu_drivers_hint">Shared by Steam and Desktop. Set on the Components page.</string> @@ -324,6 +324,8 @@ <string name="mode_pen_button">Side button</string> <string name="mode_osc">On-screen controls</string> <string name="mode_osc_qam">Steam + QAM</string> + <string name="osc_rear_buttons">Rear buttons</string> + <string name="osc_trackpads">Trackpads</string> <string name="mode_osc_note">Auto shows the controls when no controller is connected.</string> <string name="osc_steam_touch">Steam touch (beta)</string> <string name="osc_style_next_session">Steam\'s touch controls start with the next Steam session</string> @@ -361,7 +363,6 @@ <string name="mode_startup">Startup</string> <string name="mode_startup_session">Open at launch</string> <string name="mode_startup_session_hint">Starts this session when DroidDeck launches.</string> - <string name="mode_decky">Decky</string> <string name="mode_decky_checking">Checking for releases…</string> <string name="mode_decky_ready">Ready to install %1$s.</string> <string name="mode_decky_none">No compatible build found. Try again later.</string> @@ -370,14 +371,10 @@ <string name="mode_decky_current">Up to date · %1$s</string> <string name="mode_decky_loader">Loader</string> <string name="mode_decky_install_latest">Install latest</string> - <string name="decky_channel">Update Channel</string> - <string name="decky_channel_hint">Which Decky Loader releases to install. Decky\'s own updater uses the same channel.</string> <string name="decky_channel_stable">Stable</string> <string name="decky_channel_prerelease">Prerelease</string> <string name="decky_channel_testing">Testing</string> <string name="decky_channel_failed">Could not save the Decky update channel</string> - <string name="mode_decky_on">Starts with Steam. While on, other apps on this device may be able to control Steam.</string> - <string name="mode_decky_off">Off. Steam\'s remote debugging port stays closed.</string> <string name="mode_decky_remove_title">Uninstall Decky Loader?</string> <string name="mode_decky_remove_text">Removes the loader. Your plugins and settings are kept.</string> <string name="mode_client">Client</string> @@ -707,6 +704,12 @@ <string name="drawer_open_qam">Open Quick Access Menu</string> <string name="drawer_prev_page">Previous page</string> <string name="drawer_next_page">Next page</string> + <string name="drawer_manage_pages">Arrange pages</string> + <string name="drawer_page_more">More</string> + <string name="drawer_more_back">Back to %1$s</string> + <string name="drawer_more_empty">Nothing is kept here. Arrange pages and move one below the More row.</string> + <string name="drawer_pages_reset">Reset</string> + <string name="drawer_pages_done">Done</string> <string name="drawer_hud">Performance HUD</string> <string name="drawer_hud_fps">Frame rate</string> <string name="drawer_hud_battery">Battery temperature</string> @@ -865,6 +868,7 @@ <string name="drawer_pc_keyboard">PC keyboard</string> <string name="drawer_android_keyboard">Android</string> <string name="drawer_second_screen">Second screen</string> + <string name="drawer_resize">Resize the menu</string> <string name="drawer_second_screen_shows">Shows</string> <string name="drawer_android_apps">Android apps</string> <string name="drawer_launch_app">Launch an app</string> @@ -1024,20 +1028,25 @@ <string name="setup_launcher_orientation_auto">Follow device rotation</string> <string name="setup_orientation_portrait">Portrait</string> <string name="setup_session_orientation">Session orientation</string> - <string name="setup_session_orientation_hint">Applies to Steam, games, desktop, and the controller editor. Resolution presets rotate with the session; custom width and height stay as entered.</string> + <string name="setup_session_orientation_hint">Applies to Steam, games, desktop, and the controller editor. Resolution presets rotate with the session; when one orientation follows the other, custom width and height flip to match.</string> <string name="setup_orientation_auto">Automatic landscape</string> <string name="setup_orientation_landscape">Landscape</string> <string name="setup_orientation_reverse">Reverse landscape</string> <string name="setup_fullscreen">Fullscreen</string> <string name="setup_fullscreen_on">Hides the Android status and navigation bars</string> <string name="setup_fullscreen_off">Shows the Android status and navigation bars</string> + <string name="setup_page_swipe">Swipe between pages</string> + <string name="setup_page_swipe_hint">Swipe across a page to change tabs.</string> + <string name="setup_controller_haptics">Controller haptics</string> + <string name="setup_controller_haptics_hint">A light tick when the D-pad, A or the shoulder buttons move or select in the launcher. Touch stays silent</string> <string name="setup_dual_screen_launcher">Dual screen launcher</string> <string name="setup_dual_screen_launcher_hint">Automatic puts the launcher sections (Steam, Library, Stores and the rest) on the second screen of handhelds with a built-in one. On uses any second display. Off keeps the launcher on one screen.</string> <string name="setup_dual_screen_sessions">Dual screen sessions</string> - <string name="setup_dual_screen_sessions_hint">Automatic docks the in-game menu on the built-in second screen instead of a pop-over. On uses any second display. Off keeps the menu on the game screen; you can still pick a second screen from it.</string> + <string name="setup_dual_screen_sessions_hint">Automatic docks the in-game menu on the built-in second screen instead of a pop-over. On uses any second display. On, game on second screen runs the game there and keeps the menu and controls on this screen, for a phone driving a monitor or TV. Off keeps the menu on the game screen; you can still pick a second screen from it.</string> <string name="setup_dual_screen_auto">Automatic</string> <string name="setup_dual_screen_on">On</string> <string name="setup_dual_screen_off">Off</string> + <string name="setup_dual_screen_swapped">On, game on second screen</string> <string name="setup_dual_screen_controls">Bottom screen controls in games</string> <string name="setup_android_text_field_keyboard">Android keyboard for text fields</string> <string name="setup_dual_screen_controls_hint">Opens a panel on the second screen when a session starts: the Deck buttons and trackpads with a Steam Deck or Steam Controller, otherwise the one you used last.</string> @@ -1413,13 +1422,12 @@ <string name="gate_title">One Android setting to change</string> <string name="gate_eyebrow">Steam</string> <string name="gate_lede">Android stops apps that start many background processes, and Steam starts dozens. Until this changes, games close without an error.</string> + <string name="gate_notifications_toast">The pairing code goes in a notification. Turn on notifications for DroidDeck, then try again.</string> <string name="gate_fix_for_me">Fix it for me</string> <string name="gate_toggle_steps">Turn on “Disable child process restrictions”, then come back. Leave Developer options on, or the switch turns off again.</string> <string name="gate_open_dev">Open Developer options</string> <string name="gate_no_toggle">This Android version has no switch for it, so DroidDeck changes it over Wireless debugging. Takes about a minute, no computer needed.</string> <string name="gate_needs_wifi">Wireless debugging needs Wi-Fi. Any network works; it doesn\'t need internet.</string> - <string name="gate_needs_notifications">The pairing code goes in a notification. Allow notifications for DroidDeck, or use Other ways.</string> - <string name="gate_allow_notifications">Allow notifications</string> <string name="gate_step1">Open Settings → Developer options → Wireless debugging and turn it on</string> <string name="gate_step2">Tap “Pair device with pairing code”</string> <string name="gate_step3">Type the code into the DroidDeck notification</string> @@ -1436,49 +1444,16 @@ <string name="gate_status">Status</string> <string name="gate_polling">Checking every 2 seconds. This page closes when it\'s off.</string> <string name="gate_other_ways">Other ways</string> - <string name="gate_other_toggle">Wireless debugging, manual address, computer ADB</string> - <string name="gate_other_no_toggle">Manual address, computer ADB, Developer options</string> + <string name="gate_other_toggle">Computer ADB</string> + <string name="gate_other_no_toggle">Computer ADB, Developer options</string> <string name="gate_use_wireless_instead">Use Wireless debugging instead</string> <string name="gate_some_roms">Some ROMs add the switch anyway. Look for “child process” in Developer options.</string> - <string name="gate_manual_hint">If the notification doesn\'t work, enter the pop-up\'s address and code yourself.</string> - <string name="gate_enter_manually">Enter address manually</string> <string name="gate_from_computer">From a computer with ADB:</string> <string name="gate_copy_command">Copy command</string> <string name="gate_sidequest" translatable="false">SideQuest</string> <string name="gate_sidequest_steps">Connect the headset to a computer and open SideQuest. Choose “Run ADB Command”, then “Custom Command”, type the command shown below and select “Run Command”.</string> <string name="gate_choose_display">Choose which display to open Android Settings on.</string> <string name="gate_main_screen">Main screen</string> - <string name="wadb_finding_port">Paired. Finding the Wireless debugging port…</string> - <string name="wadb_enter_port">Paired. Enter the port from Settings.</string> - <string name="wadb_applying">Device found. Applying the setting…</string> - <string name="wadb_apply_failed">Couldn\'t apply automatically. Check the address below and retry. %1$s</string> - <string name="wadb_title_wireless">Wireless debugging</string> - <string name="wadb_title_done">Child-process limit updated</string> - <string name="wadb_title">Change the child-process limit</string> - <string name="wadb_lede_compact0">If the option is missing, pair over Wireless debugging.</string> - <string name="wadb_lede_compact1">Paired. Check the IP address and port in Wireless debugging.</string> - <string name="wadb_lede_done">The child-process limit was updated.</string> - <string name="wadb_lede0">Use step 2 if Developer options has no child-process setting. Open Developer options → Wireless debugging → Pair device with pairing code.</string> - <string name="wadb_lede1">Paired. Use the address below, or update it from Wireless debugging → IP address & Port.</string> - <string name="wadb_lede_done_long">The child-process limit was updated over Wireless debugging.</string> - <string name="wadb_confirmed_on">Android confirmed the limit is on.</string> - <string name="wadb_confirmed_off">Android confirmed the limit is off.</string> - <string name="wadb_pair_group">2 · Pair Wireless debugging</string> - <string name="wadb_pair_address">Pairing pop-up IP address & port</string> - <string name="wadb_pin">Pairing code (PIN)</string> - <string name="wadb_pin_placeholder">6 digits</string> - <string name="wadb_pair">Pair</string> - <string name="wadb_apply_group">2 · Apply over Wireless debugging</string> - <string name="wadb_connect_address">Connection IP address & port</string> - <string name="wadb_pair_again">Pair again</string> - <string name="wadb_turn_off">Turn limit off</string> - <string name="wadb_other_ways">Other ways to change it</string> - <string name="wadb_dev_try_first">1 · Developer options (try first)</string> - <string name="wadb_restrict_on">Turn off “Disable child process restrictions”.</string> - <string name="wadb_restrict_off">Turn on “Disable child process restrictions”.</string> - <string name="wadb_computer_last">3 · Computer ADB (last resort)</string> - <string name="wadb_only_if">Only if Wireless debugging is unavailable.</string> - <string name="wadb_computer_group">3 · Computer ADB (last resort)</string> <string name="ctrl_color">Color</string> <string name="ctrl_custom">Custom</string> <string name="ctrl_opacity">Opacity</string> @@ -1830,8 +1805,6 @@ <item quantity="one">Cleared %1$d session log folder.</item> <item quantity="other">Cleared %1$d session log folders.</item> </plurals> - <string name="main_wadb_pair_failed">Wireless debugging pairing failed</string> - <string name="main_wadb_command_failed">Wireless debugging command failed</string> <string name="main_wadb_unavailable">Wireless debugging is unavailable</string> <string name="main_adb_copied">ADB command copied</string> <string name="main_pick_roms">Choose the ROMs folder</string> @@ -1868,6 +1841,7 @@ <string name="main_pick_game_storage">Choose the game storage folder</string> <string name="main_pick_decky_zip">Choose a Decky plugin ZIP</string> <string name="main_storage_not_usable">Not usable: %1$s</string> + <string name="main_storage_fat32">FAT32 cannot hold files over 4 GB, so some games will fail to install. Reformat as exFAT.</string> <string name="main_running_program">Program</string> <string name="main_removing_runtime">Removing Linux runtime</string> <string name="main_settings_main_screen">Could not open Settings on the bottom screen; opened it on the main screen.</string> @@ -2213,6 +2187,23 @@ <string name="fm_favorite_removed">Removed \"%1$s\" from Favorites</string> <string name="fm_empty_directory">Empty directory</string> <string name="fm_up_one_level">Up one level</string> + <string name="fm_edit_open">Open</string> + <string name="fm_edit_save">Save</string> + <string name="fm_edit_read_only">Read only</string> + <string name="fm_edit_binary">Binary</string> + <string name="fm_edit_modified">Modified</string> + <string name="fm_edit_position">Ln %1$d, Col %2$d</string> + <string name="fm_edit_find">Find</string> + <string name="fm_edit_find_previous">Find previous</string> + <string name="fm_edit_find_next">Find next</string> + <string name="fm_edit_replace">Replace</string> + <string name="fm_edit_replace_all">All</string> + <string name="fm_edit_discard_title">Discard changes?</string> + <string name="fm_edit_discard_text">Changes to \"%1$s\" will be lost.</string> + <string name="fm_edit_discard">Discard</string> + <string name="fm_edit_save_failed">Couldn\'t save \"%1$s\"</string> + <string name="fm_edit_open_failed">Couldn\'t open \"%1$s\"</string> + <string name="fm_edit_too_large">Too large to open (%1$s)</string> <string name="fm_choose_folder">Choose a folder</string> <string name="fm_choose_file">Choose a file</string> <string name="ctrl_tint_steam_blue">Steam blue</string> @@ -2716,10 +2707,16 @@ <string name="driver_tag_bundle">ANDROID + LINUX</string> <string name="phantom_warning">%1$s. %2$s\n\n%3$s</string> <string name="display_session">Session display</string> - <string name="display_resolution">Resolution</string> + <string name="display_zero_copy">Zero-copy presentation</string> + <string name="display_resolution_landscape">Landscape resolution</string> + <string name="display_resolution_portrait">Portrait resolution</string> + <string name="display_follow_landscape">Follow landscape (%1$d×%2$d)</string> + <string name="display_follow_portrait">Follow portrait (%1$d×%2$d)</string> <string name="display_game_fit">16:9 game fit</string> <string name="display_game_fit_hint">How 16:9 games fit this display. Next session.</string> <string name="display_game_fit_unavailable">Choose Match screen or a custom size that isn\'t 16:9.</string> + <string name="display_avoid_notch">Avoid notch</string> + <string name="display_avoid_notch_hint">Keeps the picture out of the camera cutout. Applies when you return to the session.</string> <string name="display_preserve">Keep proportions</string> <string name="display_stretch">Stretch to display</string> <string name="display_image_scaling">Image scaling</string> @@ -3037,6 +3034,7 @@ <string name="stores_login_error_ssl">The connection to the sign-in page is not secure.</string> <string name="stores_login_error_verification">The sign-in could not be verified. Try again.</string> <string name="stores_login_error_generic">Sign-in failed. Try again.</string> + <string name="stores_login_continue_in_browser">%1$s needs one more step. Finish it in the browser that opened, then try again.</string> <string name="common_close">Close</string> <string name="common_back">Back</string> <string name="common_edit">Edit</string> @@ -3455,7 +3453,7 @@ <string name="hand_camera_done">Done</string> <string name="glasses_xreal_network_missing">Waiting for the glasses’ USB Ethernet connection. This phone may not expose it to apps.</string> <string name="glasses_xreal_connection_failed">The XREAL connection was interrupted or returned an unsupported response. Retrying…</string> - <string name="glasses_xreal_experimental">Experimental XREAL 1S, One, One Pro, One Pro+ and Aura support. Use Follow mode and turn off stabilization in the glasses menu; on the Aura, also turn off Spatial Anchor. Head tracking and 2D/3D switching are tested on the Aura.</string> + <string name="glasses_xreal_experimental">Experimental XREAL 1S, One, One Pro, One Pro+ and Aura support. Use Follow mode and turn off stabilization in the glasses menu; on the Aura, also turn off Spatial Anchor. Head tracking and 2D/3D switching are tested on the Aura and One Pro+.</string> <string name="glasses_pro2_experimental">Experimental Pro 2 head tracking. Brightness, volume, and display switching are not supported yet.</string> <string name="display_picture_position">Picture position</string> <string name="display_position_top">Top</string> @@ -4122,6 +4120,8 @@ <string name="integration_wifi_denied">Location denied · allow it in App info</string> <string name="integration_brightness_hint">Steam’s slider sets screen brightness</string> <string name="integration_home_hint">Home opens the Steam menu in a session</string> + <string name="integration_bluetooth">Bluetooth controllers</string> + <string name="integration_bluetooth_hint">Lets DroidDeck connect to Steam Controllers and other Bluetooth pads</string> <string name="integration_shortcuts_hint">Alt+Tab, Win key and Home button stay in the session</string> <string name="integration_shortcuts_maybe_restricted">Greyed out in Android? App info → ⋮ → Allow restricted settings</string> <string name="integration_shortcuts_install_failed">System keys didn\'t install</string> @@ -4188,6 +4188,7 @@ <string name="addons_sort_downloads">Most downloaded</string> <string name="addons_category_all">All categories</string> <string name="addons_none_found">No addons found</string> + <string name="addons_curse_busy">Close CurseForge first</string> <string name="addons_unreachable">Could not reach %1$s</string> <string name="addons_no_file">No file for this game version</string> <string name="addons_source_wowi" translatable="false">WoWInterface</string> @@ -4309,6 +4310,27 @@ <string name="dev_preview_drawer">In-game menu</string> <string name="dev_preview_drawer_backdrop">In-game menu preview · Back to close</string> <string name="settings_place_tab">Tabs</string> + <string name="decky_status">Status</string> + <string name="decky_enable">Enable</string> + <string name="decky_release_channel">Release channel</string> + <string name="rail_decky">Decky</string> + <string name="rail_boot_movies">Boot movies</string> + <string name="decky_tab_installed">Installed · %1$d</string> + <string name="decky_tab_store">Store</string> + <string name="decky_tab_zip">From ZIP</string> + <string name="decky_none_installed">No plugins installed. Browse the Store or install a ZIP.</string> + <string name="decky_update_to">Update to %1$s</string> + <string name="decky_remove">Remove</string> + <string name="decky_remove_confirm">Remove %1$s?</string> + <string name="decky_remove_confirm_body">Deletes the plugin from Decky. Its settings are kept.</string> + <string name="decky_changes_next_session">Plugin changes apply the next time Steam starts.</string> + <string name="decky_store_search">Search plugins</string> + <string name="decky_store_failed">Could not reach the Decky plugin store</string> + <string name="decky_store_empty">No plugins found</string> + <string name="decky_store_more">Show %1$d more</string> + <string name="decky_store_downloading">Downloading %1$s…</string> + <string name="decky_store_download_failed">Could not download %1$s</string> + <string name="decky_store_remove_failed">Could not remove the plugin</string> <string name="rail_storage">Storage</string> <string name="rail_sync">Syncthing</string> <string name="downloads_settings">Download settings</string> @@ -4330,6 +4352,7 @@ <string name="drawer_hint_button">%1$s opens this menu</string> <string name="drawer_hint_steam_inverted">Back twice opens this menu · Back once opens Steam\'s menu</string> <string name="drawer_corner_tap">Corner tap opens this menu</string> + <string name="drawer_docked_menu_controller">Physical controls can use bottom screen</string> <string name="drawer_corner_tap_hint">Double-tap the top-right corner, for devices without a Back button</string> <string name="drawer_handle">Open the session menu</string> <string name="play_needs_you">Settings need you</string> @@ -4346,4 +4369,23 @@ <string name="tabs_reset_title">Reset tabs</string> <string name="tabs_reset_hint">Steam, Desktop, Library, Downloads, Settings and Updates on the bar, the rest under More.</string> <string name="tabs_reset_body">Your tab order and what sits under More or is hidden go back to the defaults.</string> + <string name="onboarding_title">Getting DroidDeck ready</string> + <string name="onboarding_summary">%1$d%% · you can keep using the app</string> + <string name="onboarding_step_runtime">Linux runtime</string> + <string name="onboarding_step_proton">DroidDeck Proton</string> + <string name="onboarding_step_steam">Steam client</string> + <string name="onboarding_waiting">Waiting</string> + <string name="onboarding_done">Ready</string> + <string name="onboarding_failed">Will retry</string> + <string name="onboarding_steam_downloading">Downloading the Steam client</string> + <string name="onboarding_steam_downloading_mb">Downloading the Steam client (%1$d MB)</string> + <string name="onboarding_steam_failed">The Steam client download will retry</string> + <string name="onboarding_limit_reason">Android can close Steam’s helper processes. Turn that off now, while the downloads run, and Play is ready the moment they finish.</string> + <string name="onboarding_limit_action">Do it for me</string> + <string name="onboarding_limit_while_waiting">Set up while you wait</string> + <string name="onboarding_chip">Getting ready · %1$d%% · %2$s</string> + <string name="hud_only_during_game">Show HUD only during a game</string> + <string name="hud_only_during_game_hint">Hide the HUD when no game frames are detected.</string> + <string name="onboarding_button_getting_ready">Getting ready · %1$d%%</string> + <string name="onboarding_button_finish">Finish setup · %1$d%%</string> </resources> diff --git a/app/src/test/java/com/droiddeck/launcher/FrontEndIntentSupersedeTest.kt b/app/src/test/java/com/droiddeck/launcher/FrontEndIntentSupersedeTest.kt new file mode 100644 index 0000000000..0eba5d4667 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/FrontEndIntentSupersedeTest.kt @@ -0,0 +1,85 @@ +package com.droiddeck.launcher + +import android.content.Intent +import com.droiddeck.launcher.core.SteamIntegration +import com.droiddeck.launcher.frontend.GameRequest +import com.droiddeck.launcher.session.LaunchCoordinator +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +/** + * A replacement activity intent invalidates everything this activity has not dispatched yet: a + * resolved but unhandled game link, and an accepted launch that is still waiting for its session. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class FrontEndIntentSupersedeTest { + private lateinit var activity: FrontEndActivity + private lateinit var coordinator: LaunchCoordinator<Intent, GameRequest> + + @Before + fun setUp() { + activity = Robolectric.buildActivity(FrontEndActivity::class.java).get() + coordinator = ReflectionHelpers.getField(activity, "launchCoordinator") + } + + @Test + fun aReplacementIntentDropsAResolvedPendingLink() { + val owner = Intent(activity, FrontEndActivity::class.java) + val ticket = coordinator.beginLink(owner) + assertTrue(coordinator.resolve(ticket, GameRequest(id = "app"))) + + supersede() + + assertFalse(coordinator.hasPending()) + assertNull(coordinator.pendingLink()) + } + + @Test + fun aReplacementIntentInvalidatesAnAcceptedLaunch() { + val ticket = coordinator.beginLaunch() + assertTrue(coordinator.isCurrent(ticket)) + + supersede() + + assertFalse(coordinator.isCurrent(ticket)) + assertNull(shadowOf(activity).nextStartedActivity) + } + + @Test + fun anActionSetupIntentSupersedesTheGameLinkItReplaced() { + val owner = Intent(activity, FrontEndActivity::class.java) + val ticket = coordinator.beginLink(owner) + assertTrue(coordinator.resolve(ticket, GameRequest(id = "app"))) + + deliver(Intent(activity, FrontEndActivity::class.java).setAction(SteamIntegration.ACTION_SETUP)) + + assertFalse(coordinator.hasPending()) + assertFalse(coordinator.isCurrent(ticket)) + assertNull(shadowOf(activity).nextStartedActivity) + } + + private fun supersede() { + ReflectionHelpers.callInstanceMethod<Void>(activity, "supersedeUncommittedLaunch") + } + + /** onNewIntent() is protected, which is exactly how the platform delivers a replacement intent. */ + private fun deliver(intent: Intent) { + val method = FrontEndActivity::class.java.getDeclaredMethod("onNewIntent", Intent::class.java) + method.isAccessible = true + try { + method.invoke(activity, intent) + } finally { + method.isAccessible = false + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt index 2e06a6d8fe..dacf38c34c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ProtonMenuAutoTest.kt @@ -35,6 +35,7 @@ import java.util.concurrent.atomic.AtomicInteger class ProtonMenuAutoTest { private val online = AutoComponents.online private val constrained = AutoComponents.unfavourable + private val firstRunHeldBack = AutoComponents.firstRunHeldBack private lateinit var activity: Activity private lateinit var menu: ProtonMenu private lateinit var root: File @@ -49,6 +50,7 @@ class ProtonMenuAutoTest { } AutoComponents.online = { true } AutoComponents.unfavourable = { false } + AutoComponents.firstRunHeldBack = { false } SessionState.running = false SessionState.phase = SessionPhase.IDLE SessionState.stopRequested = false @@ -63,6 +65,7 @@ class ProtonMenuAutoTest { menu.protonProblem = null menu.protonStage = null menu.protonPercent = -1 + menu.experimentalRefresh = { emptyList() } menu.installer = { tool, progress -> progress("Installing ${tool.name}", 50) install("${tool.prefix}-11-12") @@ -77,6 +80,7 @@ class ProtonMenuAutoTest { menu.protonPercent = -1 AutoComponents.online = online AutoComponents.unfavourable = constrained + AutoComponents.firstRunHeldBack = firstRunHeldBack SessionState.running = false SessionState.phase = SessionPhase.IDLE SessionState.stopRequested = false diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt index dc12206545..bdb58b2a39 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentStorageTest.kt @@ -11,13 +11,13 @@ class AgentStorageTest { @Test fun removingAFolderKeepsWhatItsLinksPointAt() { val base = Files.createTempDirectory("agent-storage") val outside = Files.createDirectories(base.resolve("sdcard")) - Files.write(outside.resolve("save.dat"), ByteArray(100)) + Files.write(outside.resolve("save.dat"), ByteArray(1 shl 20)) val item = Files.createDirectories(base.resolve("rootfs/android-sdk")) Files.write(item.resolve("a.jar"), ByteArray(10)) val linked = runCatching { Files.createSymbolicLink(item.resolve("saves"), outside) }.isSuccess assumeTrue("symbolic links need privileges on this OS", linked) - assertTrue(AgentStorage.size(item) < 100) + assertTrue(AgentStorage.size(item) < 1 shl 20) AgentStorage.delete(item) assertFalse(Files.exists(item)) assertTrue(Files.exists(outside.resolve("save.dat"))) diff --git a/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt b/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt index 6338889980..a554a647bb 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt @@ -11,4 +11,10 @@ class DeviceSupportTest { // A PowerVR HAL without usable DRM access also reaches this unavailable case. assertFalse(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = false)) } + + @Test fun bridgeServesEveryNonAdrenoWithoutASystemDriverRoute() { + assertTrue(DeviceSupport.bridgeUsable(adreno = false, systemDriverReady = false)) + assertFalse(DeviceSupport.bridgeUsable(adreno = true, systemDriverReady = false)) + assertFalse(DeviceSupport.bridgeUsable(adreno = false, systemDriverReady = true)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt b/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt new file mode 100644 index 0000000000..7fb3a7a68b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt @@ -0,0 +1,143 @@ +package com.droiddeck.launcher.files + +import java.io.ByteArrayInputStream +import java.io.File +import java.nio.charset.Charset +import java.nio.file.Files +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class TextEditorLogicTest { + + @Test + fun nulByteMarksBinary() { + val clean = "hello world".toByteArray() + assertFalse(editorIsBinary(clean)) + val withNul = byteArrayOf(1, 2, 0, 3) + assertTrue(editorIsBinary(withNul)) + } + + @Test + fun binaryScanStopsAtSampleLimit() { + val bytes = ByteArray(9000) { if (it == 8999) 0 else 65 } + assertFalse(editorIsBinary(bytes)) + assertTrue(editorIsBinary(bytes, sample = 9000)) + } + + @Test + fun utf8TextDecodesAsUtf8() { + val decoded = decodeEditorText("你好, world".toByteArray(Charsets.UTF_8)) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertFalse(decoded.lossy) + assertEquals("你好, world", decoded.text) + } + + @Test + fun gbkBytesFallBackToGb18030() { + val gbk = "你好".toByteArray(Charset.forName("GBK")) + val decoded = decodeEditorText(gbk) + assertEquals(EditorCharset.GB18030, decoded.charset) + assertFalse(decoded.lossy) + assertEquals("你好", decoded.text) + } + + @Test + fun undecodableBytesStayLossyUtf8() { + val decoded = decodeEditorText(byteArrayOf(0xFF.toByte())) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertTrue(decoded.lossy) + } + + @Test + fun literalReplacementCharStaysCleanUtf8() { + val decoded = decodeEditorText("�A".toByteArray(Charsets.UTF_8)) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertFalse(decoded.lossy) + } + + @Test + fun readCappedRefusesOverLimit() { + val data = ByteArray(100) { 65 } + assertArrayEquals(data, readCapped(ByteArrayInputStream(data), 100L)) + assertNull(readCapped(ByteArrayInputStream(data), 99L)) + } + + @Test + fun tabsExpandToTabStops() { + assertEquals("ab c", expandEditorTabs("ab\tc")) + assertEquals(" x", expandEditorTabs("\tx")) + assertEquals("abcd e", expandEditorTabs("abcd\te")) + assertEquals("abc def g", expandEditorTabs("abc\tdef\tg")) + assertEquals("a \n b", expandEditorTabs("a\t\n\tb")) + assertEquals("plain text", expandEditorTabs("plain text")) + } + + @Test + fun lineCountCountsTrailingEmptyLine() { + assertEquals(1, lineCountOf("")) + assertEquals(1, lineCountOf("abc")) + assertEquals(2, lineCountOf("a\nb")) + assertEquals(2, lineCountOf("a\n")) + } + + @Test + fun offsetMapsToZeroBasedLineAndOneBasedColumn() { + val text = "ab\ncd" + assertEquals(0, lineIndexOfOffset(text, 0)) + assertEquals(0, lineIndexOfOffset(text, 2)) + assertEquals(1, lineIndexOfOffset(text, 3)) + assertEquals(1, lineIndexOfOffset(text, 5)) + assertEquals(1, columnOfOffset(text, 0)) + assertEquals(3, columnOfOffset(text, 2)) + assertEquals(2, columnOfOffset(text, 4)) + assertEquals(3, columnOfOffset(text, 5)) + } + + @Test + fun findMatchesHonorsCaseAndLimit() { + val text = "abcABCabc" + val all = findEditorMatches(text, "abc", matchCase = false) + assertEquals(listOf(0..2, 3..5, 6..8), all) + val exact = findEditorMatches(text, "abc", matchCase = true) + assertEquals(listOf(0..2, 6..8), exact) + assertEquals(2, findEditorMatches(text, "abc", matchCase = false, limit = 2).size) + assertEquals(emptyList<IntRange>(), findEditorMatches(text, "")) + assertEquals(listOf(0..1), findEditorMatches("aaa", "aa")) + } + + @Test + fun replaceSpansEveryMatch() { + val text = "one two one" + val matches = findEditorMatches(text, "one", matchCase = true) + assertEquals("1 two 1", replaceEditorMatches(text, matches, "1")) + assertEquals(text, replaceEditorMatches(text, emptyList(), "x")) + } + + @Test + fun saveTargetResolvesSymbolicLink() { + val dir = Files.createTempDirectory("editor-link").toFile() + try { + val target = File(dir, "real.txt").apply { writeText("hi") } + val link = File(dir, "link.txt") + Files.createSymbolicLink(link.toPath(), target.toPath()) + assertEquals(target.canonicalFile, resolveEditorSaveTarget(link)) + } finally { + dir.deleteRecursively() + } + } + + @Test + fun saveTargetKeepsRegularFile() { + val dir = Files.createTempDirectory("editor-plain").toFile() + try { + val plain = File(dir, "plain.txt").apply { writeText("hi") } + assertEquals(plain, resolveEditorSaveTarget(plain)) + } finally { + dir.deleteRecursively() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedExesTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedExesTest.kt index e0fcc5593a..5409eee150 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/AddedExesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedExesTest.kt @@ -92,6 +92,38 @@ class AddedExesTest { } } + @Test fun reselectingTheCurrentExeKeepsItWhenTheRankingChanges() { + val storage = tmp.newFolder("Ranked") + exe(File(storage, "Example/Example.exe")) + exe(File(storage, "Example/Other.exe")) + SessionPrefs.setAddedGamesDirs(app, emptyList()) + SessionPrefs.setGameStorage(app, storage.path, "Card") + val folder = File(storage, "Example") + val current = AddedGames.scan(app).single { it.folder == folder }.exe + val other = listOf("Example.exe", "Other.exe").map { File(folder, it) }.single { it.path != current.path } + val existing = AddedGames.addExe(app, current) + assertTrue(existing is AddedGames.AddResult.Existing) + assertEquals(current.path, SessionPrefs.addedGameExe(app, folder.path)) + File(folder, "MicrosoftGame.config").writeText("<Executable Name=\"${other.name}\" />") + assertEquals(other.path, AddedGames.rank(folder).exes.first().path) + assertEquals(current.path, AddedGames.scan(app).single { it.folder == folder }.exe.path) + } + + @Test fun reselectingASteamInstallsExeThroughAnAliasStoresTheReachablePath() { + val storage = tmp.newFolder("Aliased") + val pick = exe(File(storage, "steamapps/common/Example/Example.exe")) + File(storage, "steamapps/appmanifest_123.acf").writeText("\"installdir\" \"Example\"") + SessionPrefs.setAddedGamesDirs(app, emptyList()) + SessionPrefs.setGameStorage(app, storage.path, "Card") + val alias = File(tmp.newFolder("Links"), "Example.exe") + java.nio.file.Files.createSymbolicLink(alias.toPath(), pick.toPath()) + assertTrue(AddedGames.addExe(app, alias) is AddedGames.AddResult.Existing) + assertEquals(pick.path, AddedExes.list(app).single { it.folder == pick.parentFile!!.path }.exe) + assertEquals(pick.path, SessionPrefs.addedGameExe(app, pick.parentFile!!.path)) + assertEquals(pick.path, AddedGames.scan(app).single { it.folder == pick.parentFile }.exe.path) + AddedExes.drop(app, pick.parentFile!!.path) + } + @Test fun anotherExeInTheSameGameSwitchesItsExe() { noGamesFolders() val first = onStorage("Games2/Hades/Hades.exe") @@ -297,6 +329,39 @@ class AddedExesTest { assertEquals(listOf(other.path), AddedGames.scan(app).map { it.exe.path }) } + private fun routeEveryGameTo(steamApp: Int) { + val config = File(SessionPrefs.activeSteamRoot(app), "userdata/123/config").apply { mkdirs() } + val routes = org.json.JSONObject() + AddedGames.scan(app).forEach { routes.put(it.appId.toString(), steamApp) } + File(config, ".droiddeck-routes.json").writeText(routes.toString()) + } + + @Test fun anotherProgramOfASteamInstallIsNotRoutedToTheSteamApp() { + noGamesFolders() + val main = onStorage("Games2/The Binding of Isaac Rebirth/isaac-ng.exe") + val launcher = onStorage("Games2/The Binding of Isaac Rebirth/REPENTOGONLauncher.exe") + AddedExes.put(app, AddedExes.Entry(main.parent!!, launcher.path)) + routeEveryGameTo(250900) + val game = AddedGames.scan(app).single() + assertEquals(launcher.path, game.exe.path) + assertEquals(main.path, game.candidates.first().path) + assertNull(game.steamAppId) + assertTrue(!game.steamProgram) + assertTrue(File(AddedGames.writeListing(app, listOf(game), emptyList()).path).readText().contains("\"route\":false")) + } + + @Test fun theSteamAppsOwnProgramStillRoutesToTheSteamApp() { + noGamesFolders() + val main = onStorage("Games2/The Binding of Isaac Rebirth/isaac-ng.exe") + onStorage("Games2/The Binding of Isaac Rebirth/REPENTOGONLauncher.exe") + AddedExes.put(app, AddedExes.Entry(main.parent!!, main.path)) + routeEveryGameTo(250900) + val game = AddedGames.scan(app).single() + assertEquals(250900, game.steamAppId) + assertTrue(game.steamProgram) + assertTrue(!File(AddedGames.writeListing(app, listOf(game), emptyList()).path).readText().contains("route")) + } + @Test fun aDifferentGameWithANumberedNameIsNotTakenAsAnotherBuild() { noGamesFolders() val held = onStorage("Games2/id/Doom/Doom.exe") diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSteamEditsTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSteamEditsTest.kt index 953c3989f1..6177547d58 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSteamEditsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSteamEditsTest.kt @@ -47,6 +47,11 @@ class AddedGamesSteamEditsTest { .writeText(JSONObject().put("games", JSONObject().put(appId.toString(), game)).toString()) } + private fun legacyAdoption(exe: File, seen: Int) { + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit() + .putString("addedExe:${folder.path}", exe.path).putInt("addedExeSeen:${folder.path}", seen).commit() + } + private fun scanned() = AddedGames.scan(context).single { it.folder == folder } @Test fun aTargetChangedInSteamBecomesTheAppsChoiceOnce() { @@ -68,6 +73,65 @@ class AddedGamesSteamEditsTest { assertEquals(main.path, SessionPrefs.addedGameExe(context, folder.path)) } + @Test fun aTargetChosenInSteamKeepsTheSteamAppsRouteBeforeAndAfterItIsAdopted() { + val first = scanned() + val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json") + routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString()) + assertEquals(250900, scanned().steamAppId) + + record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1) + val adopted = scanned() + assertEquals(other, adopted.exe) + assertEquals(250900, adopted.steamAppId) + assertTrue(adopted.steamProgram) + + val later = scanned() + assertEquals(other, later.exe) + assertEquals(250900, later.steamAppId) + assertTrue(later.steamProgram) + } + + @Test fun aTargetAdoptedBeforeTheMarkerExistedKeepsTheSteamAppsRoute() { + val first = scanned() + val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json") + routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString()) + record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1) + legacyAdoption(other, 1) + assertNull(SessionPrefs.addedGameAdopted(context, folder.path, "Exe")) + val legacy = scanned() + assertEquals(other, legacy.exe) + assertEquals(250900, legacy.steamAppId) + assertTrue(legacy.steamProgram) + assertEquals(other.path, SessionPrefs.addedGameAdopted(context, folder.path, "Exe")) + } + + @Test fun aProgramPickedInDroidDeckThatSteamNeverEditedStaysOutOfTheRoute() { + val first = scanned() + val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json") + routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString()) + record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/Example.exe", 1) + legacyAdoption(other, 1) + val picked = scanned() + assertEquals(other, picked.exe) + assertNull(picked.steamAppId) + assertTrue(!picked.steamProgram) + } + + @Test fun aProgramChosenInDroidDeckAfterASteamEditLeavesTheSteamAppsRoute() { + val first = scanned() + val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json") + routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString()) + record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1) + assertEquals(other, scanned().exe) + + val third = File(folder, "Third.exe").apply { writeBytes(ByteArray(4)) } + SessionPrefs.setAddedGameExe(context, folder.path, third.path) + val chosen = scanned() + assertEquals(third, chosen.exe) + assertNull(chosen.steamAppId) + assertTrue(!chosen.steamProgram) + } + @Test fun theListingTellsTheSessionWhichSteamEditTheAppHasTaken() { val first = scanned() record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 3) diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt index 1c61034221..bdacbc4d6a 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt @@ -66,6 +66,27 @@ class AddedGamesStoreScanTest { assertTrue(game.guestExe.endsWith("/Tools/Editor.exe")) } + @Test fun everyStoreKeepsItsLauncherWhenItsOwnExeIsReselected() { + for (store in listOf(Store.GOG, Store.AMAZON, Store.EPIC)) { + val folder = install(store, "own-${store.id}", "Own ${store.label}", "Binaries/Game.exe", launcher = true) + val own = File(folder, "Binaries/Game.exe") + val before = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertTrue(AddedGames.addExe(app, own) is AddedGames.AddResult.Existing) + val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertEquals(own.path, game.exe.path) + assertTrue(game.guestExe.endsWith("/" + StoreLaunch.LAUNCHER)) + assertEquals(before.appId, game.appId) + } + } + + @Test fun aDifferentPickedExeOnAnyStoreGameIsRunDirectly() { + val folder = install(Store.GOG, "tool", "Tool GOG", "Binaries/Game.exe", launcher = true) + val tool = File(folder, "Tools/Editor.exe").apply { parentFile!!.mkdirs(); writeText("tool") } + AddedExes.put(app, AddedExes.Entry(folder.path, tool.path, picked = true)) + val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertTrue(game.guestExe.endsWith("/Tools/Editor.exe")) + } + @Test fun anOlderSidecarsSteamSwitchIsIgnoredEveryInstallIsListed() { val folder = install(Store.AMAZON, "amzn1.adg.product.x", "Yakuza 0", "Yakuza0.exe") val file = StoreGameSidecar.file(folder) diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/WinComponentDetectorsTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/WinComponentDetectorsTest.kt index cdad5c09b7..d8b1ab708a 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/WinComponentDetectorsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/WinComponentDetectorsTest.kt @@ -54,6 +54,16 @@ class WinComponentDetectorsTest { assertEquals(emptyList<String?>(), WinCompSources.steamList(context, game, 409710, "Other", auto = true).map { it.component }) } + @Test fun eu4GetsTheNativeShaderCompilerItsMapEffectsNeed() { + val steamapps = tmp.newFolder("steamapps") + val game = File(steamapps, "common/Europa Universalis IV").apply { mkdirs() } + File(steamapps, "appmanifest_236850.acf").writeText("\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228983\"\t\t\"228980\"\n\t\t\"228990\"\t\t\"228980\"\n\t}\n}\n") + val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>() + val found = WinCompSources.steamList(context, game, 236850, "Europa Universalis IV", auto = true) + assertEquals(listOf("vcredist2010_dll", "d3dx9", "d3dcompiler_43"), found.map { it.component }) + assertTrue(found.all { it.auto && it.origin == WinCompSources.Origin.STEAM }) + } + @Test fun theGamesInstallScriptRedistsAreInstalledAsSteamWould() { val steamapps = tmp.newFolder("steamapps") val game = File(steamapps, "common/DiRT 3 Complete Edition").apply { mkdirs() } diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt index ba2d444afd..0f475b5b86 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/GlassesUsbTest.kt @@ -265,6 +265,34 @@ class GlassesUsbTest { assertEquals(null, Glasses.deviceModel(device(0x043e, 0x1234, "XREAL 1S"))) } + @Test fun xrealProPlusUsesEthernetPermissionAndItsOwnOptics() { + val pro = device(0x0444, 0x3318, "XREAL 1 Pro+") + manager.devices[pro.deviceName] = pro + field("linkDevice").set(null, pro) + field("link").set(null, object : GlassesLink { + override val hasImu = true + override fun send(msgId: Int, payload: ByteArray) = true + override fun close() {} + }) + try { + refresh(ask = true) + assertEquals("XREAL One Pro+", state.value.model) + assertEquals(Glasses.Permission.GRANTED, state.value.permission) + assertTrue(manager.requests.isEmpty()) + assertTrue(state.value.canControl) + assertTrue(state.value.hardwareControls) + assertTrue(state.value.supportsScreen3dof) + assertFalse(state.value.supportsSpatial) + assertEquals(57f, state.value.diagonalFovDeg, 0f) + assertEquals(9, state.value.brightnessMax) + assertEquals(0, state.value.volumeMax) + } finally { + field("link").set(null, null) + field("linkDevice").set(null, null) + (field("handler").get(null) as Handler).removeCallbacksAndMessages(null) + } + } + @Test fun rokidMaxRoutesThroughItsOwnModelAndSharedVendorIdNeedsTheName() { val max = Glasses.deviceModel(device(0x162f, 0x04d2, "Rokid Max")) assertTrue(max is RokidModel) diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/XrealLinkTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/XrealLinkTest.kt index 9273dfb4b9..9ba23d976a 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/XrealLinkTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/XrealLinkTest.kt @@ -38,7 +38,7 @@ class XrealLinkTest { override fun close() { closed = true; bytes.clear(); bytes.offer(-1) } } - private class Channels : XrealChannels { + private class Channels(private val displayMode: Int = 2) : XrealChannels { override val controlInput = Input() override val reports = Input() val wrote = LinkedBlockingQueue<Int>() @@ -53,7 +53,7 @@ class XrealLinkTest { val id = ByteBuffer.wrap(request.body).int and Int.MAX_VALUE wrote.offer(request.command) if (acknowledge) controlInput.add(XrealProtocolTest.response(request.command, id, - if (request.command == XrealProtocol.GET_DISPLAY) byteArrayOf(0x22, 2, 0x10, 2) else byteArrayOf(0x22, 0))) + if (request.command == XrealProtocol.GET_DISPLAY) byteArrayOf(0x22, 2, 0x10, displayMode.toByte()) else byteArrayOf(0x22, 0))) } } override fun close() { controlInput.close(); reports.close(); closed.countDown() } @@ -113,6 +113,27 @@ class XrealLinkTest { } finally { link.close() } } + @Test fun proPlusRejects1sOnlyModesAndKeepsBrightnessWithinTheSupportedRange() { + val channels = Channels(9) + val listener = Listener() + val link = XrealLink(object : XrealConnector { + override fun connect() = channels + override fun close() = channels.close() + }, listener, XrealModel.ONE_PRO_PLUS) + try { + assertTrue(listener.ready.await(2, TimeUnit.SECONDS)) + assertEquals(VitureProtocol.MSG_GET_DISPLAY to 9, listener.values.poll(2, TimeUnit.SECONDS)) + assertEquals(XrealProtocol.GET_DISPLAY, channels.wrote.poll(2, TimeUnit.SECONDS)) + assertFalse(link.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(29))) + assertFalse(link.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(2))) + assertFalse(link.send(VitureProtocol.MSG_BRIGHTNESS, byteArrayOf(10))) + assertTrue(channels.wrote.isEmpty()) + assertTrue(link.send(VitureProtocol.MSG_BRIGHTNESS, byteArrayOf(9))) + assertEquals(VitureProtocol.MSG_BRIGHTNESS to 9, listener.values.poll(2, TimeUnit.SECONDS)) + assertEquals(XrealProtocol.SET_BRIGHTNESS, channels.wrote.poll(2, TimeUnit.SECONDS)) + } finally { link.close() } + } + @Test fun missingNetworkIsReportedAndCloseCancelsRetry() { val listener = Listener() val closed = AtomicBoolean() diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/XrealOrientationFilterTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/XrealOrientationFilterTest.kt index abd38d30bf..1d1f945767 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/XrealOrientationFilterTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/XrealOrientationFilterTest.kt @@ -61,9 +61,9 @@ class XrealOrientationFilterTest { } @Test fun auraAxesAreNotFlippedLikeTheRestOfTheOneFamily() { - val aura = XrealOrientationFilter(flipYz = false).update(sample(1000000, accel = Vec3(0f, 9.81f, 0f)))!! + val aura = XrealOrientationFilter(XrealModel.AURA).update(sample(1000000, accel = Vec3(0f, 9.81f, 0f)))!! assertTrue(matrix(aura)[7] > 0.99f) - assertNull(XrealOrientationFilter(flipYz = false).update(sample(1000000, accel = Vec3(0f, 0f, 0f)))) + assertNull(XrealOrientationFilter(XrealModel.AURA).update(sample(1000000, accel = Vec3(0f, 0f, 0f)))) } @Test fun capturedNeutralGravityStartsUprightBeforeRecenter() { @@ -73,4 +73,93 @@ class XrealOrientationFilterTest { val screen = matrix(pose) assertTrue(screen[7] > 0.99f) } + + @Test fun proPlusMountStartsUprightBeforeRecenter() { + val neutral = sample(1000000) + val expected = matrix(XrealOrientationFilter().update(neutral)!!) + val actual = matrix(XrealOrientationFilter(XrealModel.ONE_PRO_PLUS).update(proPlusSample(neutral))!!) + assertArrayEquals(expected, actual, 0.0001f) + assertEquals(1f, actual[7], 0.0001f) + } + + @Test fun proPlusMountKeepsBothDirectionsOfEveryAxisCorrectThroughBothRecenterModes() { + for (axis in listOf("pitch", "yaw", "roll")) for (direction in listOf(-1, 1)) { + val ideal = XrealOrientationFilter() + val mounted = XrealOrientationFilter(XrealModel.ONE_PRO_PLUS) + val initial = sample(1000000) + val firstIdeal = matrix(ideal.update(initial)!!) + val firstMounted = matrix(mounted.update(proPlusSample(initial))!!) + var middleIdeal = firstIdeal + var middleMounted = firstMounted + var lastIdeal = firstIdeal + var lastMounted = firstMounted + val rate = direction * (Math.PI / 6).toFloat() + repeat(1000) { + val angle = rate * (it + 1) / 1000f + val accel = when (axis) { + "pitch" -> Vec3(0f, -9.81f * cos(angle), 9.81f * sin(angle)) + "yaw" -> Vec3(0f, -9.81f, 0f) + else -> Vec3(-9.81f * sin(angle), -9.81f * cos(angle), 0f) + } + val gyro = when (axis) { + "pitch" -> Vec3(rate, 0f, 0f) + "yaw" -> Vec3(0f, -rate, 0f) + else -> Vec3(0f, 0f, rate) + } + val frame = sample((it + 2) * 1000000L, gyro, accel) + lastIdeal = matrix(ideal.update(frame)!!) + lastMounted = matrix(mounted.update(proPlusSample(frame))!!) + if (it == 499) { + middleIdeal = lastIdeal + middleMounted = lastMounted + } + } + for (centerView in listOf(false, true)) { + val label = "$axis $direction centerView=$centerView" + val idealView = HeadPose.relative(HeadPose.recenter(firstIdeal, centerView), lastIdeal) + val mountedView = HeadPose.relative(HeadPose.recenter(firstMounted, centerView), lastMounted) + assertArrayEquals(label, axisMatrix(axis, rate), mountedView, 0.002f) + assertArrayEquals(label, idealView, mountedView, 0.0001f) + + val idealRecentered = HeadPose.relative(HeadPose.recenter(middleIdeal, centerView), lastIdeal) + val mountedRecentered = HeadPose.relative(HeadPose.recenter(middleMounted, centerView), lastMounted) + val recenteredAngle = if (centerView || axis == "yaw") rate / 2 else rate + assertArrayEquals("$label after mid-turn recenter", axisMatrix(axis, recenteredAngle), mountedRecentered, 0.002f) + assertArrayEquals("$label after mid-turn recenter", idealRecentered, mountedRecentered, 0.0001f) + } + } + } + + @Test fun recordedProPlusTurnAxesStayOnYawAndRoll() { + val recordedAxes = mapOf("yaw" to Vec3(0.052f, 0.867f, -0.496f), "roll" to Vec3(0.033f, 0.625f, 0.780f)) + for ((label, gyro) in recordedAxes) { + val filter = XrealOrientationFilter(XrealModel.ONE_PRO_PLUS) + val first = matrix(filter.update(sample(1000000))!!) + var last = first + repeat(100) { + last = matrix(filter.update(sample((it + 2) * 1000000L, gyro, Vec3(0f, 0f, 0f)))!!) + } + val view = HeadPose.relative(HeadPose.recenter(first, centerView = true), last) + val axis = Vec3(view[7] - view[5], view[2] - view[6], view[3] - view[1]).normalized() + val projection = if (label == "yaw") -axis.y else -axis.z + assertTrue("Recorded $label axis should be within 10 degrees of the display axis", + projection > cos(Math.toRadians(10.0).toFloat())) + } + } + + private fun proPlusSample(sample: XrealProtocol.Sample): XrealProtocol.Sample { + val angle = Math.toRadians(-35.0).toFloat() + fun mounted(v: Vec3) = Vec3(v.x, cos(angle) * v.y - sin(angle) * v.z, sin(angle) * v.y + cos(angle) * v.z) + return XrealProtocol.Sample(sample.timeNs, mounted(sample.gyro), mounted(sample.accel)) + } + + private fun axisMatrix(axis: String, angle: Float): FloatArray { + val c = cos(angle) + val s = sin(angle) + return when (axis) { + "pitch" -> floatArrayOf(1f, 0f, 0f, 0f, c, -s, 0f, s, c) + "yaw" -> floatArrayOf(c, 0f, s, 0f, 1f, 0f, -s, 0f, c) + else -> floatArrayOf(c, s, 0f, -s, c, 0f, 0f, 0f, 1f) + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/glasses/XrealProtocolTest.kt b/app/src/test/java/com/droiddeck/launcher/glasses/XrealProtocolTest.kt index 23f4f5af1c..901bcfeed0 100644 --- a/app/src/test/java/com/droiddeck/launcher/glasses/XrealProtocolTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/glasses/XrealProtocolTest.kt @@ -70,17 +70,24 @@ class XrealProtocolTest { } @Test fun stereoOnlyControlSwitches3dWithoutDisplayModeCommands() { - val output = ByteArrayOutputStream() - val replies = response(XrealProtocol.GET_INPUT, 1, byteArrayOf(0x22, 0)) + - response(XrealProtocol.SET_INPUT, 2, byteArrayOf(0x22, 0)) + - response(XrealProtocol.GET_INPUT, 3, byteArrayOf(0x22, 2, 0x10, 1)) - val control = XrealControl(channels(replies.inputStream(), output), stereoOnly = true, settleDelayMs = 0) - assertEquals(XrealModel.NATIVE_60HZ, control.display()) - assertEquals(5, control.changeDisplay(5)) - val written = output.toByteArray().inputStream() - val commands = List(3) { XrealProtocol.read(written).command } - assertEquals(listOf(XrealProtocol.GET_INPUT, XrealProtocol.SET_INPUT, XrealProtocol.GET_INPUT), commands) - assertFalse(commands.any { it == XrealProtocol.GET_DISPLAY || it == XrealProtocol.SET_DISPLAY }) + for (model in listOf(XrealModel.ONE, XrealModel.ONE_PRO, XrealModel.AURA)) { + assertFalse(model.hardwareControls) + assertFalse(model.hasSunblock) + assertEquals(listOf(60), model.rates2d) + assertFalse(model.supportsDisplayMode(9)) + assertFalse(model.supportsDisplayMode(3)) + val output = ByteArrayOutputStream() + val replies = response(XrealProtocol.GET_INPUT, 1, byteArrayOf(0x22, 0)) + + response(XrealProtocol.SET_INPUT, 2, byteArrayOf(0x22, 0)) + + response(XrealProtocol.GET_INPUT, 3, byteArrayOf(0x22, 2, 0x10, 1)) + val control = XrealControl(channels(replies.inputStream(), output), model = model, settleDelayMs = 0) + assertEquals(XrealModel.NATIVE_60HZ, control.display()) + assertEquals(5, control.changeDisplay(5)) + val written = output.toByteArray().inputStream() + val commands = List(3) { XrealProtocol.read(written).command } + assertEquals(listOf(XrealProtocol.GET_INPUT, XrealProtocol.SET_INPUT, XrealProtocol.GET_INPUT), commands) + assertFalse(commands.any { it == XrealProtocol.GET_DISPLAY || it == XrealProtocol.SET_DISPLAY }) + } } @Test fun unrelatedResponsesCannotKeepControlWaitingForever() { @@ -125,6 +132,44 @@ class XrealProtocolTest { assertThrows(IOException::class.java) { control.changeDisplay(5) } } + @Test fun proPlusKeeps1080pModesSeparateFrom1sNative1200p() { + val pro = XrealModel.ONE_PRO_PLUS + assertEquals(9, pro.mode(60, false)) + assertEquals(3, pro.mode(90, false)) + assertEquals(4, pro.mode(120, false)) + assertEquals(5, pro.mode(120, true)) + assertFalse(pro.sbs90) + assertEquals(listOf(60, 90, 120), pro.rates2d) + assertEquals(57f, pro.diagonalFovDeg, 0f) + assertEquals(29, XrealModel.ONE_S.mode(60, false)) + assertEquals(52f, XrealModel.ONE_S.diagonalFovDeg, 0f) + } + + @Test fun proPlusRejects1sOnlyDisplayResponsesAndCommands() { + for (mode in listOf(2, 29)) { + val response = response(XrealProtocol.GET_DISPLAY, 1, byteArrayOf(0x22, 2, 0x10, mode.toByte())) + val output = ByteArrayOutputStream() + val control = XrealControl(channels(response.inputStream(), output), model = XrealModel.ONE_PRO_PLUS) + assertThrows(IOException::class.java) { control.display() } + output.reset() + assertThrows(IllegalArgumentException::class.java) { control.changeDisplay(mode) } + assertEquals(0, output.size()) + } + } + + @Test fun proPlusCanReturnFromStereoToIts1080p60HzMode() { + val output = ByteArrayOutputStream() + val replies = response(XrealProtocol.SET_INPUT, 1, byteArrayOf(0x22, 0)) + + response(XrealProtocol.GET_DISPLAY, 2, byteArrayOf(0x22, 0)) + + response(XrealProtocol.GET_DISPLAY, 3, byteArrayOf(0x22, 2, 0x10, 9)) + val control = XrealControl(channels(replies.inputStream(), output), 0, XrealModel.ONE_PRO_PLUS) + assertEquals(9, control.changeDisplay(XrealModel.ONE_PRO_PLUS.mode(60, false))) + val requests = output.toByteArray().inputStream() + assertEquals(XrealProtocol.SET_INPUT, XrealProtocol.read(requests).command) + repeat(2) { assertEquals(XrealProtocol.GET_DISPLAY, XrealProtocol.read(requests).command) } + assertEquals(0, requests.available()) + } + companion object { fun sensor(time: Long = 123456789L): ByteArray = ByteBuffer.allocate(128).order(ByteOrder.LITTLE_ENDIAN) .putLong(8, time).putInt(24, 11).putFloat(32, 0.5f).putFloat(44, 9.81f).array() diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt index 963f9f739c..5dd2aa383e 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt @@ -11,6 +11,7 @@ class SocNamesTest { assertEquals("SG8350P", SocNames.model(props("ro.vendor.qti.soc_model" to "SG8350P", "ro.fota.platform" to "MSM_13.0"))) assertEquals("QCS8550", SocNames.model(props("ro.soc.model" to "QCS8550", "ro.vendor.qti.soc_model" to "other"))) assertEquals("", SocNames.model(props("ro.fota.platform" to "MSM_13.0"))) + assertEquals("QTI SM8750P", SocNames.model(props("ro.soc.model" to "unknown", "ro.vendor.qti.soc_model" to "QTI SM8750P"))) } @Test fun knownModelsAndPlatformsGetTheirNames() { @@ -26,6 +27,7 @@ class SocNamesTest { assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name("QTI SM8975", "")) assertEquals("Snapdragon 8 Elite Extreme Gen 6", SocNames.name(" qti sm8975 ", "")) assertEquals("Snapdragon 8 Elite Extreme Gen 6 (QTI SM8975)", SocNames.label("QTI SM8975", "")) + assertEquals("Snapdragon 8 Elite", SocNames.name("QTI SM8750P", "")) assertNull(SocNames.name("SM89750", "")) assertNull(SocNames.name("SM8975-PRO", "")) assertNull(SocNames.name("Qualcomm SM8975", "")) diff --git a/app/src/test/java/com/droiddeck/launcher/input/AxisPacingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/AxisPacingTest.kt new file mode 100644 index 0000000000..d88a9e7964 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/AxisPacingTest.kt @@ -0,0 +1,102 @@ +package com.droiddeck.launcher.input + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class AxisPacingTest { + @Test fun theFirstReportIsWrittenAtOnce() { + assertEquals(100L, AxisPacing(4).dueAt(100, true)) + } + + @Test fun stickMotionInsideTheIntervalWaitsForItsEnd() { + val pacing = AxisPacing(4) + pacing.wrote(100) + assertEquals(104L, pacing.dueAt(101, true)) + assertEquals(104L, pacing.dueAt(103, true)) + assertEquals(104L, pacing.dueAt(104, true)) + assertEquals(110L, pacing.dueAt(110, true)) + } + + @Test fun buttonsAndRestTransitionsAreNeverHeldBack() { + val pacing = AxisPacing(4) + pacing.wrote(100) + assertEquals(101L, pacing.dueAt(101, false)) + } + + @Test fun onlyMotionThatStaysOffRestIsPaced() { + assertTrue(AxisPacing.keepsMoving(0, 0)) + assertTrue(AxisPacing.keepsMoving(1200, 1300)) + assertTrue(AxisPacing.keepsMoving(-40, 25)) + assertFalse(AxisPacing.keepsMoving(0, 900)) + assertFalse(AxisPacing.keepsMoving(900, 0)) + } + + @Test fun theIntervalRunsFromTheFlushNotFromTheRequest() { + val pacing = AxisPacing(4) + assertEquals(100L, pacing.dueAt(100, true)) + pacing.wrote(110) + assertEquals(114L, pacing.dueAt(111, true)) + } + + @Test fun aHeldReportIsReleasedOnlyAtItsDeadline() { + val pacing = AxisPacing(4) + assertTrue(pacing.hold(104)) + assertFalse(pacing.hold(104)) + assertFalse(pacing.release(103)) + assertTrue(pacing.release(104)) + assertFalse(pacing.release(105)) + } + + @Test fun aCallbackFromACancelledHoldCannotPublishTheNextHoldEarly() { + val pacing = AxisPacing(4) + assertTrue(pacing.hold(104)) + assertTrue(pacing.cancel()) + pacing.wrote(104) + assertTrue(pacing.hold(pacing.dueAt(105, true))) + assertFalse(pacing.release(105)) + assertTrue(pacing.release(108)) + } + + @Test fun cancellingWithNothingHeldRemovesNoCallback() { + val pacing = AxisPacing(4) + assertFalse(pacing.cancel()) + assertTrue(pacing.hold(104)) + assertTrue(pacing.release(104)) + assertFalse(pacing.cancel()) + } + + @Test fun aThousandHertzPadReachesTheGuestAtTheIntervalRate() { + val writes = feed(AxisPacing(4), sampleMs = 1, durationMs = 1000) + assertTrue("$writes writes", writes in 249..251) + } + + @Test fun aPadSlowerThanTheIntervalIsNeverDelayed() { + val pacing = AxisPacing(4) + for (now in 0L until 1000L step 5) { + assertEquals(now, pacing.dueAt(now, true)) + pacing.wrote(now) + } + } + + private fun feed(pacing: AxisPacing, sampleMs: Long, durationMs: Long): Int { + var writes = 0 + var pendingAt = -1L + for (now in 0L until durationMs step sampleMs) { + if (pendingAt in 0..now) { + pacing.wrote(pendingAt) + writes++ + pendingAt = -1 + } + val due = pacing.dueAt(now, true) + if (due <= now) { + pacing.wrote(now) + writes++ + } else if (pendingAt < 0) { + pendingAt = due + } + } + return writes + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt index 7409d4558b..078b3e3fdc 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt @@ -23,6 +23,34 @@ class DualScreenTest { private val context: Context = ApplicationProvider.getApplicationContext() private val displays = context.getSystemService(DisplayManager::class.java) + @Test fun dockedMenuOnlyTakesTheControllerWhenOptedIn() { + assertFalse(DualScreen.menuOwnsController(open = false, docked = false, optIn = true)) + assertTrue(DualScreen.menuOwnsController(open = true, docked = false, optIn = false)) + assertFalse(DualScreen.menuOwnsController(open = true, docked = true, optIn = false)) + assertTrue(DualScreen.menuOwnsController(open = true, docked = true, optIn = true)) + } + + @Test fun theMenuComesBackOnStartWhenItIsTheSelectedModeOrWasShowingWhenTheScreenClosed() { + val menu = SecondScreenMode.MENU + val terminal = SecondScreenMode.TERMINAL + assertTrue(DualScreen.menuReturnsOnStart(menu, menuWasShown = false, menuUp = false)) + assertTrue(DualScreen.menuReturnsOnStart(menu, menuWasShown = true, menuUp = false)) + assertTrue(DualScreen.menuReturnsOnStart(terminal, menuWasShown = true, menuUp = false)) + assertFalse(DualScreen.menuReturnsOnStart(terminal, menuWasShown = false, menuUp = false)) + assertFalse(DualScreen.menuReturnsOnStart(menu, menuWasShown = true, menuUp = true)) + assertFalse(DualScreen.menuReturnsOnStart(terminal, menuWasShown = true, menuUp = true)) + } + + @Test fun aVisibleDockedMenuThatDoesNotOwnTheControllerIsIdle() { + assertFalse(DualScreen.menuIdleOnBottom(open = false, docked = false, pinned = false, optIn = false)) + assertFalse(DualScreen.menuIdleOnBottom(open = true, docked = false, pinned = false, optIn = false)) + assertTrue(DualScreen.menuIdleOnBottom(open = true, docked = true, pinned = false, optIn = false)) + assertTrue(DualScreen.menuIdleOnBottom(open = false, docked = true, pinned = true, optIn = false)) + assertTrue(DualScreen.menuIdleOnBottom(open = false, docked = true, pinned = true, optIn = true)) + assertFalse(DualScreen.menuIdleOnBottom(open = true, docked = true, pinned = false, optIn = true)) + assertFalse(DualScreen.menuIdleOnBottom(open = false, docked = true, pinned = false, optIn = false)) + } + @Test fun internalPanelsCountAsBuiltIn() { assertTrue(DualScreen.isBuiltIn(1, "Anything")) assertFalse(DualScreen.isBuiltIn(2, "Retroid Pocket Duo")) @@ -159,6 +187,18 @@ class DualScreenTest { assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenMode(context)) } + @Test @Config(sdk = [34]) fun gameOnSecondScreenUsesTheSameDisplayAsOn() { + withDisplay(EXTERNAL, "HDMI Screen") { monitor -> + assertEquals(monitor.displayId, DualScreen.display(context, displays, Display.DEFAULT_DISPLAY, DualScreen.MODE_SWAPPED)?.displayId) + assertNull(DualScreen.display(context, displays, Display.DEFAULT_DISPLAY, DualScreen.MODE_AUTO)) + } + } + + @Test fun gameOnSecondScreenIsASavedSessionMode() { + SessionPrefs.setDualScreenSessionMode(context, DualScreen.MODE_SWAPPED) + assertEquals(DualScreen.MODE_SWAPPED, SessionPrefs.dualScreenSessionMode(context)) + } + @Test fun launcherAndSessionsKeepSeparateModes() { SessionPrefs.setDualScreenMode(context, DualScreen.MODE_OFF) assertEquals(DualScreen.MODE_OFF, SessionPrefs.dualScreenMode(context)) diff --git a/app/src/test/java/com/droiddeck/launcher/input/GuestKeysTest.kt b/app/src/test/java/com/droiddeck/launcher/input/GuestKeysTest.kt new file mode 100644 index 0000000000..28e300aa33 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/GuestKeysTest.kt @@ -0,0 +1,52 @@ +package com.droiddeck.launcher.input + +import android.view.InputDevice +import android.view.KeyEvent +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE) +class GuestKeysTest { + @Test fun hardwareEscapeBypassesBackMenuAndReachesGuestWithMatchingRelease() { + val taps = mutableListOf<Boolean>() + val menu = BackQamInput({}, taps::add) + val guest = mutableListOf<Pair<Int, Boolean>>() + for (action in listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP)) { + val event = KeyEvent(10, 20, action, KeyEvent.KEYCODE_BACK, 0, + KeyEvent.META_SHIFT_ON, 43, 1, 0, InputDevice.SOURCE_KEYBOARD) + val normalized = GuestKeys.normalizeKeyboardEscape(event) + assertEquals(KeyEvent.KEYCODE_ESCAPE, normalized.keyCode) + assertEquals(event.action, normalized.action) + assertEquals(event.metaState, normalized.metaState) + assertEquals(event.deviceId, normalized.deviceId) + assertEquals(event.scanCode, normalized.scanCode) + assertEquals(event.source, normalized.source) + assertFalse(menu.onKeyEvent(normalized, true)) + assertTrue(GuestKeys.send(normalized) { code, down -> guest += code to down }) + } + assertEquals(listOf(1 to true, 1 to false), guest) + assertTrue(taps.isEmpty()) + } + + @Test fun navigationBackAndOtherPhysicalBackKeysAreUnchanged() { + for (scan in listOf(0, 158)) { + val event = KeyEvent(10, 20, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK, + 0, 0, 43, scan, 0, InputDevice.SOURCE_KEYBOARD) + assertSame(event, GuestKeys.normalizeKeyboardEscape(event)) + } + } + + @Test fun normalizedEscapePreservesRepeatAndCancellation() { + val event = KeyEvent(10, 20, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK, + 3, 0, 43, 1, KeyEvent.FLAG_CANCELED, InputDevice.SOURCE_KEYBOARD) + val normalized = GuestKeys.normalizeKeyboardEscape(event) + assertEquals(event.repeatCount, normalized.repeatCount) + assertEquals(event.flags, normalized.flags) + assertEquals(event.downTime, normalized.downTime) + assertEquals(event.eventTime, normalized.eventTime) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt index cdaa68a779..0bb917a5d7 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt @@ -132,6 +132,7 @@ class InputLayoutToolsTest { } @Test fun aScaledGamepadStaysGeneratedAndRegeneratesOnRotation() { + com.droiddeck.launcher.session.SessionPrefs.setSteamController(context, com.droiddeck.launcher.session.SessionPrefs.CONTROLLER_NONE) val (display, metrics) = InputLibraries.primaryDisplay(context) val long = maxOf(metrics.widthPixels, metrics.heightPixels) val short = minOf(metrics.widthPixels, metrics.heightPixels) diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt index 9c81655b0a..a5472bae6f 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt @@ -1,6 +1,8 @@ package com.droiddeck.launcher.input import android.content.Context +import android.content.ContextWrapper +import android.content.SharedPreferences import org.json.JSONObject import org.junit.Assert.* import org.junit.Before @@ -48,6 +50,100 @@ class InputLibraryTest { assertEquals(library, InputLibraries.decode(InputLibraries.encode(library))) } + @Test fun reopeningARedesignLibraryRestoresTheGamepadAndKeepsCustomBindings() { + val original = InputLibraries.read(context) + val overlay = original.activeLayout(false, InputRole.PRIMARY)!! + val custom = InputSurfaceElement(InputControl.A, .98f, .2f, .02f, .02f, id = "extra") + val preset = original.preset(original.profile("game").binding(InputRole.PRIMARY)) + val saved = original.copy( + layouts = original.layouts.map { if (it.id == overlay.id) it.copy(elements = listOf(custom), aspect = 0f) else it }, + bindings = original.bindings.map { + if (it.id == preset.id) it.copy(elements = it.elements + mapOf("extra" to InputAction.Keys(listOf(29)), + "legacy:a" to InputAction.Keys(listOf(30)))) else it + }, + ) + for (version in 15..16) { + val raw = JSONObject(InputLibraries.encode(saved)).put("version", version).toString() + prefs.edit().putString("library", raw).commit() + + val restored = InputLibraries.read(context) + val layout = restored.activeLayout(false, InputRole.PRIMARY)!! + assertTrue(layout.elements.any { it.id == "legacy:a" }) + assertEquals(custom.bounded(), layout.elements.single { it.id == "extra" }) + assertEquals(InputAction.Keys(listOf(30)), restored.preset(preset.id).elements["legacy:a"]) + assertEquals(InputAction.Keys(listOf(29)), restored.preset(preset.id).elements["extra"]) + assertEquals(raw, prefs.getString("library-before-controller-revert", null)) + assertEquals(restored, InputLibraries.read(context)) + assertEquals(restored, InputLibraries.update(context) { it }) + } + } + + @Test fun failedRollbackBackupLeavesTheLayoutUsableAndRetriesLater() { + val original = InputLibraries.read(context) + val raw = JSONObject(InputLibraries.encode(original)).put("version", 16).toString() + val backup = "library-before-controller-revert" + prefs.edit().putString("library", raw).putString(backup, "previous backup").commit() + + assertEquals(original, InputLibraries.read(contextWithFailedCommits())) + assertEquals(raw, prefs.getString("library", null)) + assertEquals("previous backup", prefs.getString(backup, null)) + + assertEquals(original, InputLibraries.read(context)) + assertEquals(14, JSONObject(prefs.getString("library", null)!!).getInt("version")) + assertEquals(raw, prefs.getString(backup, null)) + } + + @Test fun failedRecoveryRestoresBothValuesAndTheNextEditRetriesRecovery() { + val raw = "unreadable library" + val backup = "library-recovery." + java.util.UUID.nameUUIDFromBytes(raw.toByteArray(Charsets.UTF_8)) + prefs.edit().putString("library", raw).putString(backup, "previous backup").commit() + val failing = contextWithFailedCommits() + + repeat(2) { + assertThrows(IllegalStateException::class.java) { InputLibraries.update(failing) { it } } + assertEquals(raw, prefs.getString("library", null)) + assertEquals("previous backup", prefs.getString(backup, null)) + } + InputLibraries.update(context) { it } + assertEquals(raw, prefs.getString(backup, null)) + assertNotNull(InputLibraries.decode(prefs.getString("library", null)!!)) + } + + private fun contextWithFailedCommits(): Context = object : ContextWrapper(context) { + override fun getSharedPreferences(name: String, mode: Int): SharedPreferences { + val original = super.getSharedPreferences(name, mode) + if (name != "input-profiles") return original + return object : SharedPreferences by original { + override fun edit(): SharedPreferences.Editor { + val editor = original.edit() + return object : SharedPreferences.Editor by editor { + override fun putString(key: String, value: String?): SharedPreferences.Editor { + editor.putString(key, value) + return this + } + + override fun commit(): Boolean { + editor.apply() + return false + } + } + } + } + } + } + + @Test fun revertingKeepsIntentionallyEmptyGamepadsEmpty() { + val original = InputLibraries.read(context) + val doc = JSONObject(InputLibraries.encode(original)).put("version", 16) + val layouts = doc.getJSONArray("layouts") + val overlay = (0 until layouts.length()).map(layouts::getJSONObject) + .single { it.getString("id") == InputLibraries.OVERLAY } + overlay.put("kitless", true).put("elements", org.json.JSONArray()) + prefs.edit().putString("library", doc.toString()).commit() + + assertTrue(InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!!.elements.isEmpty()) + } + @Test fun legacyLowerScreenBindingsKeepTheirOriginalControlsWithoutSavedGeometry() { prefs.edit().putBoolean("migrated", true).putString("profile.game", """{"version":1,"bindings":[{"role":"SECONDARY","control":"a","action":{"type":"keys","codes":[57]}}]}""").commit() diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt index cfe027586a..1fa557b6d9 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.input import android.content.Context import android.graphics.Rect +import com.droiddeck.launcher.session.SessionPrefs import org.json.JSONObject import org.junit.Assert.* import org.junit.Before @@ -26,6 +27,16 @@ class OnScreenLayoutTest { private fun px(e: InputSurfaceElement, w: Int, h: Int) = floatArrayOf(e.x * w, e.y * h, e.width * w, e.height * h) + private val shortcuts = setOf(InputControl.SELECT, InputControl.START, InputControl.GUIDE, InputControl.QAM) + + private fun assertOnlyShortcutPositionsChanged(before: List<InputSurfaceElement>, after: List<InputSurfaceElement>) { + assertEquals(before.map { it.id }, after.map { it.id }) + for ((original, placed) in before.zip(after)) { + val expected = if (original.control in shortcuts) original.copy(x = placed.x, y = placed.y) else original + assertEquals(expected, placed) + } + } + private fun assertSquare(e: InputSurfaceElement, w: Int, h: Int) = assertEquals(e.width * w, e.height * h, 1.5f) private fun assertInside(elements: List<InputSurfaceElement>, w: Int, h: Int, safe: Rect = Rect()) { @@ -38,7 +49,43 @@ class OnScreenLayoutTest { } } + @Test fun theFloatingSteamPadOffersIndependentVisibilityAndLowersOnlyTheDefaultShortcuts() { + val w = 1280 + val h = 960 + val safe = Rect(24, 8, 12, 16) + val layout = gamepad() + val original = LegacyGamepadLayout(context, w, h, safe).regenerate(layout.elements) + val extraRear = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5) + val extraPads = setOf(InputControl.LEFT_PAD, InputControl.RIGHT_PAD) + fun placed(rear: Boolean, pads: Boolean) = + OnScreenLayout.elements(context, layout, w, h, safe, rearButtons = rear, trackpads = pads) + for (type in listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM)) { + SessionPrefs.setSteamController(context, type) + val base = placed(false, false) + for (control in listOf(InputControl.SELECT, InputControl.START)) { + val old = original.single { it.control == control } + val moved = base.single { it.control == control } + assertTrue(control.id, moved.y > old.y) + } + val standard = base.map { it.control }.toSet() + assertEquals(extraRear, placed(true, false).map { it.control }.toSet() - standard) + assertEquals(extraPads, placed(false, true).map { it.control }.toSet() - standard) + val both = placed(true, true) + assertEquals(extraRear + extraPads, both.map { it.control }.toSet() - standard) + assertInside(both, w, h, safe) + assertEquals(base, both.filter { it.control in standard }) + } + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) + assertEquals(original.map { it.id }, placed(true, true).map { it.id }) + assertEquals(placed(false, false), placed(true, true)) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val edited = layout.copy(elements = layout.elements.map { e -> if (e.control == InputControl.START) e.copy(y = .3f) else e }, aspect = w.toFloat() / h) + val fitted = OnScreenLayout.elements(context, edited, w, h, safe) + assertTrue(fitted.single { it.control == InputControl.START }.y < .5f) + } + @Test fun theBuiltInGamepadIsRegeneratedForEverySizeWithoutStretching() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) val layout = gamepad() for ((w, h) in listOf(1200 to 540, 540 to 1200, 900 to 850)) { val placed = OnScreenLayout.elements(context, layout, w, h, Rect()) @@ -51,6 +98,7 @@ class OnScreenLayoutTest { @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") fun aBuiltInGamepadSavedAtTheDisplaySizeRegeneratesForTheMeasuredSurface() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) val saved = gamepad().copy(elements = LegacyGamepadLayout(context, 2608, 1200).elements(), aspect = 2608f / 1200) val placed = OnScreenLayout.elements(context, saved, 2048, 1200, Rect()) assertEquals(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed) @@ -58,6 +106,7 @@ class OnScreenLayoutTest { @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") fun previouslyGeneratedEdgeSticksRegenerateWithoutOverridingCustomGeometry() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM) val w = 2608 val h = 1200 ControllerPrefs.setLayout(context, w, h, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f))) @@ -66,7 +115,7 @@ class OnScreenLayoutTest { val current = generator.elements() assertTrue(old.filter { it.control == InputControl.LS || it.control == InputControl.RS }.zip(current.filter { it.control == InputControl.LS || it.control == InputControl.RS }).any { (a, b) -> kotlin.math.abs(a.width - b.width) > .01f }) val saved = gamepad().copy(elements = old, aspect = w.toFloat() / h) - assertEquals(LegacyGamepadLayout(context, 2048, h).regenerate(old), OnScreenLayout.elements(context, saved, 2048, h, Rect())) + assertOnlyShortcutPositionsChanged(LegacyGamepadLayout(context, 2048, h).regenerate(old), OnScreenLayout.elements(context, saved, 2048, h, Rect())) val custom = saved.copy(elements = old.map { if (it.id == "legacy:a") it.copy(x = .4f) else it }) assertEquals(OnScreenLayout.fit(custom.elements, custom.aspect, 1f, 2048, h, Rect()), OnScreenLayout.elements(context, custom, 2048, h, Rect())) } @@ -122,11 +171,12 @@ class OnScreenLayoutTest { val original = gamepad() val moved = original.copy(elements = original.elements.map { if (it.id == "legacy:a") it.copy(x = .3f) else it }, aspect = w.toFloat() / h) val reset = LegacyGamepadLayout(context, w, h).regenerate(moved.elements) - assertEquals(LegacyGamepadLayout(context, w, h).regenerate(original.elements), OnScreenLayout.elements(context, moved.copy(elements = reset), w, h, Rect())) + assertEquals(OnScreenLayout.elements(context, original, w, h, Rect()), OnScreenLayout.elements(context, moved.copy(elements = reset), w, h, Rect())) } } @Test fun regenerationKeepsTheUsersButtonStylesAndRemovedButtons() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) val layout = gamepad().let { g -> g.copy(elements = g.elements.filterNot { it.id == "legacy:y" }.map { if (it.id == "legacy:a") it.copy(opacity = .4f, icon = 0, name = "Jump") else it }) } val placed = OnScreenLayout.elements(context, layout, 2000, 1000, Rect()) assertNull(placed.firstOrNull { it.id == "legacy:y" }) @@ -136,6 +186,47 @@ class OnScreenLayoutTest { assertEquals(LegacyGamepadLayout(context, 2000, 1000).elements().first { it.id == "legacy:a" }.x, a.x, .0001f) } + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun theDefaultDeckUsesTheRedesignReferenceGeometry() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect(), rearButtons = true, trackpads = true) + fun center(control: InputControl): Pair<Float, Float> = placed.single { it.id == "legacy:${control.id}" } + .let { (it.x + it.width / 2f) * 1600f to (it.y + it.height / 2f) * 900f } + fun assertCenter(control: InputControl, x: Float, y: Float) { + val (cx, cy) = center(control) + assertEquals(control.id, x, cx, .01f) + assertEquals(control.id, y, cy, .01f) + } + assertCenter(InputControl.LT, 120f, 96f) + assertCenter(InputControl.LB, 310f, 96f) + assertCenter(InputControl.RB, 1290f, 96f) + assertCenter(InputControl.RT, 1480f, 96f) + assertCenter(InputControl.UP, 220f, 242.5f) + assertCenter(InputControl.RIGHT, 322.5f, 345f) + assertCenter(InputControl.LS, 290f, 640f) + assertCenter(InputControl.RS, 1310f, 640f) + assertCenter(InputControl.LEFT_PAD, 470f, 360f) + assertCenter(InputControl.RIGHT_PAD, 1130f, 360f) + assertCenter(InputControl.SELECT, 660f, 850f) + assertCenter(InputControl.START, 940f, 850f) + assertInside(placed, 1600, 900) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-xxxhdpi") + fun theDeckShortcutRowStaysApartOnSmallDenseSurfaces() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val row = listOf("builtin:keyboard", "legacy:guide", "legacy:select", "legacy:start", "legacy:qam") + for ((size, safe) in listOf(800 to 450 to Rect(), 600 to 450 to Rect(), 600 to 450 to Rect(0, 0, 120, 0), + 600 to 450 to Rect(120, 0, 0, 0), 1600 to 900 to Rect())) { + val (w, h) = size + val placed = OnScreenLayout.elements(context, gamepad(), w, h, safe) + for ((left, right) in row.map { id -> placed.single { it.id == id } }.zipWithNext()) { + assertTrue("${left.id} reaches ${right.id} at ${w}x$h $safe", (left.x + left.width) * w <= right.x * w + .5f) + } + assertInside(placed, w, h, safe) + } + } + @Test fun anEditedLayoutKeepsItsAspectAndCornersWhenTheScreenRotates() { val corner = InputSurfaceElement(InputControl.A, .85f, .7f, .1f, .2f) val left = InputSurfaceElement(InputControl.LS, .05f, .5f, .2f, .4f) @@ -188,6 +279,7 @@ class OnScreenLayoutTest { } @Test fun theUnfoldedStripUsesTheDockGeometryInLandscapeAndPortrait() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) for ((size, portrait) in listOf((2208 to 800) to false, (1080 to 1300) to true)) { val (w, h) = size val placed = OnScreenLayout.elements(context, gamepad(), w, h, Rect(), dock = OnScreenLayout.Dock(portrait, grips = true)) @@ -215,6 +307,86 @@ class OnScreenLayoutTest { assertEquals(.1f * 2208f / 1768 / .2f, fitted.width * 2208 / (fitted.height * 800), .01f) } + @Test fun controlsEditedInPortraitKeepTheirPlacesInThePanelBelowTheGame() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) + val (w, h) = 1080 to 2400 + val stock = gamepad() + val shown = OnScreenLayout.editorElements(context, stock, w, h) + val moved = shown.map { if (it.id == "legacy:a") it.copy(x = .05f) else if (it.id == "legacy:ls") it.copy(x = .6f) else it } + val edited = OnScreenLayout.withFrame(context, stock, OnScreenLayout.editorFrame(stock, moved), w.toFloat() / h) + val shownA = shown.first { it.id == "legacy:a" } + for (panelHeight in listOf(1100, 800)) { + val placed = OnScreenLayout.elements(context, edited, w, panelHeight, Rect(), dock = OnScreenLayout.Dock(true, false)) + val a = placed.first { it.id == "legacy:a" } + val ls = placed.first { it.id == "legacy:ls" } + val b = placed.first { it.id == "legacy:b" } + assertTrue(a.x < .2f) + assertTrue(ls.x > .5f) + assertTrue(b.x > a.x) + assertNull(placed.firstOrNull { it.id == "builtin:keyboard" || it.control == InputControl.GUIDE || it.control == InputControl.QAM }) + assertInside(placed, w, panelHeight) + assertEquals(shownA.width * w / (shownA.height * h), a.width * w / (a.height * panelHeight), .01f) + val untouched = OnScreenLayout.elements(context, stock, w, panelHeight, Rect(), dock = OnScreenLayout.Dock(true, false)) + assertTrue(untouched.first { it.id == "legacy:a" }.x > .5f) + assertTrue(untouched.first { it.id == "legacy:ls" }.x < .5f) + } + val landscape = OnScreenLayout.elements(context, edited, 2400, 1080, Rect()) + assertTrue(landscape.first { it.id == "legacy:a" }.x > .5f) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val deck = OnScreenLayout.elements(context, edited, w, 1100, Rect(), dock = OnScreenLayout.Dock.deck(true, null), trackpads = true) + assertTrue(deck.none { it.id == "legacy:rs" }) + assertTrue(deck.any { it.kind == InputElementKind.TRACKPAD && it.x + it.width / 2f > .5f }) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) + val tiny = stock.copy(aspect = .45f, elements = stock.elements.map { + when (it.id) { + "legacy:a" -> it.copy(x = .05f, y = .05f, width = .1f, height = .045f) + "legacy:b" -> it.copy(x = .16f, y = .05f, width = .1f, height = .045f) + "legacy:ls" -> it.copy(x = .8f, y = .85f, width = .15f, height = .1f) + else -> it + } + }, rotated = emptyList()) + val short = OnScreenLayout.elements(context, tiny, w, 385, Rect(), dock = OnScreenLayout.Dock(true, false)) + val sa = short.first { it.id == "legacy:a" } + val sb = short.first { it.id == "legacy:b" } + assertTrue(sa.x + sa.width <= sb.x) + assertEquals(1f, sa.width * w / (sa.height * 385), .01f) + } + + @Test fun thePortraitAndBelowGameKitsKeepDirectionalArtClearOfTheSticksAndFaceButtons() { + val directions = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) + val face = setOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y) + val types = listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM, SessionPrefs.CONTROLLER_XBOX360, + SessionPrefs.CONTROLLER_DS4, SessionPrefs.CONTROLLER_DUALSENSE) + val layout = gamepad() + val w = 1080 + for (type in types) { + SessionPrefs.setSteamController(context, type) + val steam = type == SessionPrefs.CONTROLLER_DECK || type == SessionPrefs.CONTROLLER_STEAM + val deckDock = if (steam) OnScreenLayout.Dock.deck(true, null) else OnScreenLayout.Dock(true, false) + for ((h, dock) in listOf(1920 to null, 1300 to deckDock, 385 to deckDock)) { + val placed = OnScreenLayout.elements(context, layout, w, h, Rect(), dock = dock, + rearButtons = true, trackpads = true) + assertInside(placed, w, h) + val dpad = placed.filter { it.control in directions } + assertEquals(4, dpad.size) + val rightEdge = dpad.maxOf { it.x + it.width } + val bottomEdge = dpad.maxOf { it.y + it.height } + assertTrue(type, placed.filter { it.control in face && it.id != "builtin:keyboard" }.all { it.x > rightEdge }) + assertTrue(type, placed.filter { it.kind == InputElementKind.STICK || it.kind == InputElementKind.TRACKPAD }.all { it.y > bottomEdge }) + if (dock == null) { + val row = placed.filter { it.control in shortcuts || it.id == "builtin:keyboard" } + assertEquals(5, row.size) + assertTrue(row.all { it.y > bottomEdge }) + assertEquals(steam, placed.any { it.kind == InputElementKind.TRACKPAD }) + } else { + assertFalse(placed.any { it.control == InputControl.GUIDE || it.control == InputControl.QAM }) + assertEquals(steam, placed.any { it.kind == InputElementKind.TRACKPAD }) + assertEquals(!steam, placed.any { it.control == InputControl.RS }) + } + } + } + } + private val legacyKeys = "29+33:0.3,0.7,44::Find::0.6:1:1:1" private fun importedOn(library: InputLibrary) = library.activeLayout(false, InputRole.PRIMARY)!!.elements.filter { it.id.startsWith("imported:") } @@ -310,6 +482,7 @@ class OnScreenLayoutTest { } @Test fun aDeckStripPutsTheDeckGamepadSurfacesInTheStickSlotsAndOtherPadsKeepSticks() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) val stock = InputStockLayouts.layouts().first { it.id == DeckPanel.GAMEPAD.layout } val deck = OnScreenLayout.Dock.deck(false, stock) assertEquals(OnScreenLayout.Dock(false, true, InputControl.LS, InputControl.RIGHT_PAD), deck) @@ -366,4 +539,164 @@ class OnScreenLayoutTest { assertEquals(InputStockLayouts.layouts().filter { it.id != DeckPanel.GAMEPAD.layout }.map { it.elements }, others.filter { l -> InputStockLayouts.layouts().any { it.id == l.id } }.map { it.elements }) } + + private val kits = listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM, SessionPrefs.CONTROLLER_XBOX360, + SessionPrefs.CONTROLLER_DS4, SessionPrefs.CONTROLLER_DUALSENSE) + + private fun List<InputSurfaceElement>.at(control: InputControl) = single { it.id == "legacy:${control.id}" } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun everyKitPutsTriggersBesideTheirBumpers() { + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect(), rearButtons = true, trackpads = true) + val lt = placed.at(InputControl.LT); val lb = placed.at(InputControl.LB) + val rb = placed.at(InputControl.RB); val rt = placed.at(InputControl.RT) + for ((outer, inner) in listOf(lt to lb, rt to rb)) assertEquals(kit, outer.y + outer.height / 2f, inner.y + inner.height / 2f, .001f) + assertTrue(kit, lt.x + lt.width <= lb.x) + assertTrue(kit, rb.x + rb.width <= rt.x) + assertInside(placed, 1600, 900) + } + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun buttonSizeGrowsAndShrinksControlsOnAScreenWhoseHeightAlreadyLimitsTheLayout() { + val (display, _) = InputLibraries.primaryDisplay(context) + val stock = gamepad() + fun at(scale: Float) = OnScreenLayout.elements(context, stock.copy(scale = scale, + elements = LegacyGamepadLayout(display, 1600, 900, scale = scale).regenerate(stock.elements)), 1600, 900, Rect()) + fun List<InputSurfaceElement>.centre(controls: List<InputControl>) = controls.map { at(it) }.let { c -> + c.sumOf { (it.x + it.width / 2).toDouble() } / c.size to c.sumOf { (it.y + it.height / 2).toDouble() } / c.size } + val face = listOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y) + val dpad = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val normal = at(1f) + for (scale in listOf(.8f, 1.25f)) { + val placed = at(scale) + assertEquals("$kit $scale", normal.at(InputControl.A).width * scale, placed.at(InputControl.A).width, .002f) + assertEquals("$kit $scale", normal.at(InputControl.LS).height * scale, placed.at(InputControl.LS).height, .002f) + if (scale > 1f) for (cluster in listOf(face, dpad)) { + val (x0, y0) = normal.centre(cluster); val (x1, y1) = placed.centre(cluster) + assertEquals("$kit", x0, x1, .01); assertEquals("$kit", y0, y1, .01) + } + assertInside(placed, 1600, 900) + } + } + } + + @Test @Config(qualifiers = "w1280dp-h800dp-land-mdpi") + fun tabletOverlaysStayInTheLowerHalfOfTheScreen() { + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val placed = OnScreenLayout.elements(context, gamepad(), 1280, 800, Rect(), rearButtons = true, trackpads = true) + for (e in placed) assertTrue("$kit ${e.id}", e.y >= .45f) + assertInside(placed, 1280, 800) + } + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun phoneOverlaysStillUseTheFullHeight() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect()) + assertTrue(placed.at(InputControl.LT).y < .15f) + assertTrue(placed.at(InputControl.START).let { it.y + it.height } > .9f) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aLayoutEditedInOneOrientationKeepsTheKitInTheOther() { + for (kit in kits) { + SessionPrefs.setSteamController(context, kit) + val layout = gamepad() + val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()) + val moved = landscape.map { if (it.control == InputControl.A) it.copy(x = .5f, y = .5f) else it } + val edited = layout.copy(elements = moved, aspect = 1600f / 900f) + assertEquals(kit, .5f, OnScreenLayout.elements(context, edited, 1600, 900, Rect()).at(InputControl.A).x, .001f) + val kitPortrait = OnScreenLayout.elements(context, layout, 900, 1600, Rect()) + val editedPortrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect()) + for (control in listOf(InputControl.A, InputControl.LT, InputControl.RB, InputControl.LS, InputControl.UP)) + assertEquals("$kit ${control.id}", kitPortrait.at(control), editedPortrait.at(control)) + } + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun eachOrientationKeepsItsOwnEdits() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) + val layout = gamepad() + val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()).map { if (it.control == InputControl.A) it.copy(x = .5f, y = .5f) else it } + val edited = OnScreenLayout.withFrame(context, layout, landscape, 1600f / 900f) + val portrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect()).map { if (it.control == InputControl.B) it.copy(x = .1f, y = .2f) else it } + val both = OnScreenLayout.withFrame(context, edited, portrait, 900f / 1600f) + assertEquals(landscape.map { it.id to floatArrayOf(it.x, it.y).toList() }, both.elements.map { it.id to floatArrayOf(it.x, it.y).toList() }) + val wide = OnScreenLayout.elements(context, both, 1600, 900, Rect()) + val tall = OnScreenLayout.elements(context, both, 900, 1600, Rect()) + assertEquals(.5f, wide.at(InputControl.A).x, .001f) + assertEquals(.1f, tall.at(InputControl.B).x, .001f) + assertEquals(.2f, tall.at(InputControl.B).y, .001f) + val renamed = OnScreenLayout.withFrame(context, both, both.elements.map { if (it.control == InputControl.A) it.copy(name = "Jump") else it }, both.aspect) + assertEquals("Jump", OnScreenLayout.elements(context, renamed, 900, 1600, Rect()).at(InputControl.A).name) + assertEquals(.1f, OnScreenLayout.elements(context, renamed, 900, 1600, Rect()).at(InputControl.B).x, .001f) + val library = InputLibraries.read(context).withLayout(both) + assertEquals(both, InputLibraries.decode(InputLibraries.encode(library))!!.layouts.first { it.id == both.id }) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aRemovedRearButtonStaysRemovedWhileTheOthersRemain() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val layout = gamepad() + val displayed = OnScreenLayout.elements(context, layout, 1600, 900, Rect(), rearButtons = true, trackpads = true) + val frozen = OnScreenLayout.editorFrame(layout, displayed).filterNot { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD } + val edited = layout.copy(elements = frozen, aspect = 1600f / 900f) + for ((w, h) in listOf(1600 to 900, 900 to 1600)) { + val placed = OnScreenLayout.elements(context, edited, w, h, Rect(), rearButtons = true, trackpads = true).map { it.control } + assertFalse(InputControl.L4 in placed) + assertFalse(InputControl.LEFT_PAD in placed) + assertTrue(InputControl.R5 in placed) + assertTrue(InputControl.RIGHT_PAD in placed) + } + val hidden = OnScreenLayout.elements(context, edited, 1600, 900, Rect(), rearButtons = false, trackpads = false).map { it.control } + assertFalse(InputControl.R5 in hidden) + assertFalse(InputControl.RIGHT_PAD in hidden) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aPortraitMainLayoutUsesTheStockControlsInLandscape() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360) + val layout = gamepad() + val portrait = OnScreenLayout.elements(context, layout, 900, 1600, Rect()).map { if (it.control == InputControl.A) it.copy(x = .1f, y = .1f) else it } + val edited = layout.copy(elements = portrait, aspect = 900f / 1600f) + assertEquals(OnScreenLayout.elements(context, layout, 1600, 900, Rect()), OnScreenLayout.elements(context, edited, 1600, 900, Rect())) + assertEquals(.1f, OnScreenLayout.elements(context, edited, 900, 1600, Rect()).at(InputControl.A).x, .001f) + } + + @Test @Config(qualifiers = "w800dp-h450dp-land-320dpi") + fun aPortraitSaveKeepsOptionalControlsInThePortraitFrameOnly() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val layout = gamepad() + val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()) + val edited = OnScreenLayout.withFrame(context, layout, landscape, 1600f / 900f) + val portrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect(), rearButtons = true, trackpads = true) + .map { if (it.control == InputControl.B) it.copy(x = .1f, y = .2f) else it } + assertTrue(portrait.any { it.control == InputControl.L4 }) + val both = OnScreenLayout.withFrame(context, edited, portrait, 900f / 1600f) + assertTrue(both.elements.none { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD }) + assertTrue(both.rotated.any { it.control == InputControl.L4 }) + assertEquals(OnScreenLayout.elements(context, edited, 1600, 900, Rect(), rearButtons = true, trackpads = true), + OnScreenLayout.elements(context, both, 1600, 900, Rect(), rearButtons = true, trackpads = true)) + val tall = OnScreenLayout.elements(context, both, 900, 1600, Rect(), rearButtons = true, trackpads = true) + for (control in listOf(InputControl.L4, InputControl.LEFT_PAD, InputControl.B)) assertEquals(control.id, portrait.at(control), tall.at(control)) + assertTrue(OnScreenLayout.elements(context, both, 900, 1600, Rect(), rearButtons = false, trackpads = false) + .none { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD }) + } + + @Test fun stockControlsUseTheKitArtworkWhileAddedAndTrackpadControlsStillUseTheTint() { + for (kit in listOf(PadKit.XBOX, PadKit.DUALSENSE)) { + SessionPrefs.setSteamController(context, if (kit == PadKit.XBOX) SessionPrefs.CONTROLLER_XBOX360 else SessionPrefs.CONTROLLER_DUALSENSE) + val layout = gamepad() + assertTrue(kit.name, layout.elements.all { kit.artwork(it) }) + val added = InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, "custom", name = "Fire") + assertFalse(kit.artwork(added)) + assertFalse(kit.artwork(layout.elements.first { it.control == InputControl.A }.copy(image = "picture"))) + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt index 566a091c42..d49a937e05 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt @@ -53,14 +53,10 @@ class SecondScreenModeTest { assertEquals(-1, SecondScreenDisplays.selection(-1, emptyList(), false)) } - @Test fun withNothingRememberedDeckPadsGetControlsAndOthersTheDashboard() { - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true, dashboard = true)) - assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true)) - } - - @Test fun withNothingRememberedAndNoDashboardTheControllerPicksThePanel() { - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad = false)) + @Test fun withNothingRememberedTheDroidDeckMenuOpens() { + for (deckPad in listOf(false, true)) for (dashboard in listOf(false, true)) for (desktop in listOf(false, true)) { + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening(null, deckPad, dashboard, desktop)) + } } @Test fun thePanelTheUserPickedLastOpensAgain() { @@ -70,9 +66,18 @@ class SecondScreenModeTest { assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("keyboard-trackpad", deckPad = true)) } + @Test fun theMenuIsAModeAndOpensAgainWhenItWasPickedLast() { + for (deckPad in listOf(false, true)) { + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("menu", deckPad, dashboard = true, bottomDesktop = true)) + } + assertEquals("menu", SecondScreenMode.MENU.id) + assertEquals(false, SecondScreenMode.MENU.controls) + assertEquals(null, SecondScreenMode.MENU.bindings) + } + @Test fun deckControlsNeedTheDeckPad() { - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false, dashboard = true)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("deck-controls", deckPad = false)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("deck-controls", deckPad = false, dashboard = true)) } @Test fun customControlsReopenWithEitherControllerType() { @@ -81,37 +86,23 @@ class SecondScreenModeTest { } } - @Test fun anUnknownOrClosedChoiceFallsBackToTheDefault() { - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("none", deckPad = true, dashboard = true)) - assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening("gone", deckPad = false, dashboard = true)) - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("none", deckPad = true)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("gone", deckPad = false)) + @Test fun anUnknownOrClosedChoiceFallsBackToTheMenu() { + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("none", deckPad = true, dashboard = true)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("gone", deckPad = false, dashboard = true)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("none", deckPad = true)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("gone", deckPad = false)) } @Test fun theDashboardOpensAgainOnlyWhileItHasPages() { assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = true)) - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = false)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("dashboard", deckPad = false)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = false)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("dashboard", deckPad = false)) } @Test fun theDesktopOpensAgainOnlyWhileItCanRun() { assertEquals(SecondScreenMode.DESKTOP, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true, bottomDesktop = true)) - assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("desktop", deckPad = false)) - } - - @Test fun withNothingRememberedTheDesktopIsNeverPicked() { - assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true, bottomDesktop = true)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad = false, bottomDesktop = true)) - } - - @Test fun desktopSessionsOpenTheTrackpadUntilTheUserPicksAnotherPanel() { - for (deckPad in listOf(false, true)) for (dashboard in listOf(false, true)) { - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad, dashboard, desktopSession = true)) - assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("gone", deckPad, dashboard, desktopSession = true)) - assertEquals(SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.opening("custom-controls", deckPad, dashboard, desktopSession = true)) - assertEquals(SecondScreenMode.TERMINAL, SecondScreenMode.opening("terminal", deckPad, dashboard, desktopSession = true)) - } + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true)) + assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("desktop", deckPad = false)) } @Test fun theEditorOpensOnTheChosenBottomScreenUnlessAnotherAppHoldsIt() { diff --git a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt index 669db39752..d32edcdd8d 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenProfileMigrationTest.kt @@ -48,20 +48,14 @@ class SecondScreenProfileMigrationTest { SessionState.deckPad = previousDeckPad } - @Test fun firstOpeningKeepsTheLibraryAndOpensTheTrackpadOnDesktopAndTheControllerPanelInGames() { + @Test fun firstOpeningKeepsTheLibraryAndOpensTheMenuOverTheTrackpad() { for (desktop in listOf(false, true)) for (deckPad in listOf(false, true)) { val original = customLibrary(desktop) open(desktop, deckPad) assertEquals(original, InputLibraries.read(activity)) assertNull(SessionPrefs.secondScreenPanel(activity, desktop)) - val dashboard = ReflectionHelpers.callInstanceMethod<List<*>>(activity, "bottomPages").isNotEmpty() - val expected = when { - desktop -> SecondScreenMode.KEYBOARD_TRACKPAD - deckPad -> SecondScreenMode.DECK_CONTROLS - dashboard -> SecondScreenMode.DASHBOARD - else -> SecondScreenMode.KEYBOARD_TRACKPAD - } - assertEquals(expected, SessionState.secondScreenMode) + assertEquals(SecondScreenMode.MENU, ReflectionHelpers.callInstanceMethod<SecondScreenMode>(activity, "openingPanel")) + assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SessionState.secondScreenMode) } } @@ -107,14 +101,22 @@ class SecondScreenProfileMigrationTest { customLibrary(desktop) SessionState.deckPad = false show(SecondScreenMode.DECK_CONTROLS) - val fallback = ReflectionHelpers.callInstanceMethod<SecondScreenMode>(activity, "openingPanel") - assertNotEquals(SecondScreenMode.DECK_CONTROLS, fallback) - if (desktop) assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, fallback) + val fallback = ReflectionHelpers.callInstanceMethod<SecondScreenMode>(activity, "openingSurface") + assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, fallback) assertEquals(fallback, SessionState.secondScreenMode) assertNotEquals(InputLibraries.DECK, routedLayout()?.id) } } + @Test fun pickingAnotherModeClearsTheMenuRestoreLeftByATeardown() { + customLibrary(desktop = false) + SessionState.bottomMenu = true + ReflectionHelpers.callInstanceMethod<Unit>(activity, "pickSecondScreenMode", + ReflectionHelpers.ClassParameter.from(SecondScreenMode::class.java, SecondScreenMode.KEYBOARD_TRACKPAD)) + assertFalse(SessionState.bottomMenu) + assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD.id, SessionPrefs.secondScreenPanel(activity, false)) + } + private fun customLibrary(desktop: Boolean): InputLibrary { session(desktop) return InputLibraries.update(activity) { library -> diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt index f74528c725..2ada13c310 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt @@ -73,72 +73,6 @@ class BattleNetTest { assertEquals(crc or 0x80000000L, BattleNet.APP_ID) } - @Test fun theNewestD2rfixIsTheHighestFexThenTheHighestFix() { - val items = listOf( - item("FEXCore-2610-linux.wcp"), - item("FEXCore-2609-d2rfix25-linux.wcp"), - item("FEXCore-2610-d2rfix9-linux.wcp"), - item("FEXCore-2610-d2rfix28-linux.wcp"), - item("FEXCore-2509.1-d2rfix40-linux.wcp"), - ) - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.newestD2rFix(items)?.file) - assertEquals("FEXCore-2610.1-d2rfix1-linux.wcp", BattleNet.newestD2rFix(items + item("FEXCore-2610.1-d2rfix1-linux.wcp"))?.file) - assertEquals("FexCore-2611-D2RFIX2-linux.wcp", BattleNet.newestD2rFix(items + item("FexCore-2611-D2RFIX2-linux.wcp"))?.file) - } - - @Test fun onlyFexD2rfixPackagesCount() { - assertNull(BattleNet.newestD2rFix(listOf(item("FEXCore-2610-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp", comp = "dxvk")))) - assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp.part")) - assertNull(BattleNet.d2rfix("FEXCore-2610-d2rfix-linux.wcp")) - assertEquals(listOf(2610L) to 28L, BattleNet.d2rfix("FEXCore-2610-d2rfix28-linux.wcp")) - } - - @Test fun theNewestStoredBuildIsSetForThePrefix() { - catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp", "FEXCore-2610-linux.wcp") - store("FEXCore-2610-d2rfix28-linux.wcp") - - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh)) - - assertEquals(mapOf("fex" to "FEXCore-2610-d2rfix28-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", BattleNet.ensureFex(context, ::noRefresh)) - } - - @Test fun aNewerBuildReplacesTheOldOne() { - catalog("FEXCore-2609-d2rfix25-linux.wcp") - store("FEXCore-2609-d2rfix25-linux.wcp") - BattleNet.ensureFex(context, ::noRefresh) - catalog("FEXCore-2609-d2rfix25-linux.wcp", "FEXCore-2610-d2rfix28-linux.wcp") - store("FEXCore-2610-d2rfix28-linux.wcp") - - BattleNet.ensureFex(context, ::noRefresh) - - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"]) - } - - @Test fun aStaleListingIsFetchedAgain() { - catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1) - store("FEXCore-2610-d2rfix28-linux.wcp") - - BattleNet.ensureFex(context) { listOf(item("FEXCore-2609-d2rfix25-linux.wcp"), item("FEXCore-2610-d2rfix28-linux.wcp")) } - - assertEquals("FEXCore-2610-d2rfix28-linux.wcp", ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())["fex"]) - } - - @Test fun aFailedFetchFallsBackOnTheCachedListing() { - catalog("FEXCore-2609-d2rfix25-linux.wcp", fetchedAt = 1) - store("FEXCore-2609-d2rfix25-linux.wcp") - - assertEquals("FEXCore-2609-d2rfix25-linux.wcp", BattleNet.ensureFex(context) { error("offline") }) - } - - @Test fun aListingWithoutD2rfixIsAnError() { - catalog("FEXCore-2610-linux.wcp") - var refreshed = 0 - assertThrows(IllegalStateException::class.java) { BattleNet.ensureFex(context) { refreshed++; emptyList() } } - assertEquals(1, refreshed) - assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) - } - @Test fun installedIsTheLauncherInThePrefix() { assertFalse(BattleNet.installed(context)) launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } @@ -152,9 +86,9 @@ class BattleNetTest { } @Test fun removeTakesThePrefixItsMenuEntryAndCacheButNothingItLinksTo() { - catalog("FEXCore-2610-d2rfix28-linux.wcp") - store("FEXCore-2610-d2rfix28-linux.wcp") - BattleNet.ensureFex(context, ::noRefresh) + store("FEXCore-2610-linux.wcp") + ComponentsManager.setGameComponent(context, BattleNet.APP_ID.toString(), "fex", "FEXCore-2610-linux.wcp") + assertEquals(mapOf("fex" to "FEXCore-2610-linux.wcp"), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) val root = LinuxRuntime.rootDir(context) fun put(relative: String) = File(root, relative).apply { parentFile!!.mkdirs(); writeText("x") } launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } @@ -176,7 +110,7 @@ class BattleNetTest { assertTrue(otherMenu.isFile) assertFalse(log.parentFile!!.exists()) assertTrue(otherPrefix.isFile) - assertNull(BattleNet.fexInUse(context)) + assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, BattleNet.APP_ID.toString())) outside.deleteRecursively() } @@ -420,13 +354,15 @@ class BattleNetTest { assertEquals(codes.distinct(), codes) assertTrue("Fen" in codes && "OSI" in codes && "WTCG" in codes) assertFalse(BattleNet.STORE.any { it.uid == "d3cn" || it.uid == "fen" }) - assertFalse(BattleNet.STORE.any { it.code == "WoWC" || it.code == "WoWF" }) + assertFalse(BattleNet.STORE.any { it.code == "WoWC" }) + assertEquals("wow_forever", BattleNet.STORE.first { it.code == "WoWF" }.uid) assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid) assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) }) val installed = listOf("fenris", "diablo3_enus", null) val offered = BattleNet.STORE.filter { BattleNet.notInstalled(it, installed) }.map { it.code } assertFalse("Fen" in offered || "D3" in offered) - assertTrue("OSI" in offered) + assertTrue("OSI" in offered && "WoWF" in offered) + assertFalse("WoWF" in BattleNet.STORE.filter { BattleNet.notInstalled(it, listOf("wow_forever")) }.map { it.code }) } @Test fun aBattleNetGameStartsWithoutSteamThroughItsShortcutUntilThatIsSwitchedOff() { @@ -481,6 +417,22 @@ class BattleNetTest { assertTrue(BattleNet.ensureVideoMemory(context)) } + @Test fun theProfileDefaultsAreSetForTheBattleNetProgramOrOnceInstalledAndNeverForAnythingElse() { + File(context.filesDir, "game-environment.json").delete() + val manager = context.getSystemService(android.app.ActivityManager::class.java) + org.robolectric.Shadows.shadowOf(manager).setMemoryInfo(android.app.ActivityManager.MemoryInfo().apply { totalMem = 11113L shl 20 }) + val scope = BattleNet.APP_ID.toString() + BattleNet.ensureDefaults(context, null) + assertNull(GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + BattleNet.ensureDefaults(context, BattleNet.PROGRAM) + assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + assertTrue(com.droiddeck.launcher.session.SessionPrefs.battleNetNoSteamSet(context)) + File(context.filesDir, "game-environment.json").delete() + launcher().apply { parentFile!!.mkdirs(); writeText("MZ") } + BattleNet.ensureDefaults(context, null) + assertEquals(BattleNet.videoMemoryOptions(2048), GameEnvironmentStore.read(context).games[scope]?.get("DXVK_CONFIG")) + } + private fun launcher() = File(BattleNet.prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe") private fun varint(value: Long): ByteArray { @@ -496,21 +448,6 @@ class BattleNetTest { private fun varintField(number: Int, value: Long) = varint((number shl 3).toLong()) + varint(value) private fun message(vararg fields: ByteArray) = fields.fold(ByteArray(0)) { all, f -> all + f } - private fun noRefresh(context: Context): List<ComponentsManager.CatalogItem> = error("the cached listing was fresh") - - private fun item(file: String, comp: String = "fex") = ComponentsManager.CatalogItem( - file, comp, "FexCore-Linux", "https://github.com/The412Banner/Nightlies/releases/download/FexCore-Linux/$file", 4, "sha256:" + "ab".repeat(32), - ) - - private fun catalog(vararg files: String, fetchedAt: Long = System.currentTimeMillis() / 1000) { - val cache = File(context.filesDir, "components/catalog.json") - cache.parentFile!!.mkdirs() - val items = JSONArray() - for (file in files) items.put(JSONObject().put("file", file).put("comp", "fex").put("release", "FexCore-Linux") - .put("url", item(file).url).put("size", 4).put("digest", item(file).digest)) - cache.writeText(JSONObject().put("items", items).put("fetchedAt", fetchedAt).toString()) - } - private fun store(file: String) { val wcp = File(context.filesDir, "components/packages/$file") wcp.parentFile!!.mkdirs() diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt index cf78bed84f..5bf02cacc9 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt @@ -75,6 +75,32 @@ class BwrapSpawnerTest { assertEquals("x11", x11["SDL_VIDEODRIVER"]) } + @Test fun sourcesNamedByTheirKernelPathReachTheSessionsMounts() { + val files = "/data/user/0/com.droiddeck.launcher/files" + val kernel = "/data/data/com.droiddeck.launcher/files" + val binds = session + Bind(files, files) + val aliased = BwrapSpawner.withKernelPaths(binds) { it.replace("/data/user/0/", "/data/data/") } + val runtime = "/linuxfs/root/.local/share/flatpak/runtime/org.example.Platform/aarch64/1/abc/files" + assertEquals("$files$runtime", BwrapSpawner.hostPath(aliased, "$files/linuxfs", "$kernel$runtime")) + assertEquals("$files$runtime", BwrapSpawner.hostPath(aliased, "$files/linuxfs", "$files$runtime")) + assertEquals("$files/linuxfs/usr/bin/env", BwrapSpawner.hostPath(aliased, "$files/linuxfs", "/usr/bin/env")) + } + + @Test fun kernelPathsLeaveOtherMountsAlone() { + assertEquals(session, BwrapSpawner.withKernelPaths(session) { it }) + val renamed = listOf(Bind("/data/user/0/x", "/mnt/x"), Bind("/data/user/0/y", "/data/user/0/y"), Bind("/elsewhere", "/data/data/y")) + assertEquals(renamed, BwrapSpawner.withKernelPaths(renamed) { it.replace("/data/user/0/", "/data/data/") }) + assertEquals(session, BwrapSpawner.withKernelPaths(session) { throw java.io.IOException(it) }) + } + + @Test fun prootGetsNoGuestPreloadOfItsOwn() { + val plan = BwrapSpawner.Plan(File("/sandbox"), emptyList(), "/", listOf("/app/bin/apply_extra"), + mapOf("LD_PRELOAD" to "/run/droiddeck-preload/libddsession.so", "FLATPAK_ID" to "org.example.Ext")) + assertEquals(mapOf("FLATPAK_ID" to "org.example.Ext"), BwrapSpawner.prootEnvironment(plan, false)) + assertTrue(BwrapSpawner.prootEnvironment(plan, true).isEmpty()) + assertEquals("/run/droiddeck-preload/libddsession.so", plan.env["LD_PRELOAD"]) + } + @Test fun normalizeResolvesDotsLexically() { assertEquals("/usr/lib/x", BwrapSpawner.normalize("/usr/lib/GL/../x")) assertEquals("/", BwrapSpawner.normalize("/../..")) @@ -146,6 +172,20 @@ class BwrapSpawnerPlanTest { assertEquals(mapOf("DD_DESKTOP" to "1"), unavailable) } + @Test fun theRuntimeGlExtensionVulkanDirectoryListsOnlyTheSessionDriver() { + val lib = File(runtime, "usr/lib/aarch64-linux-gnu/libvulkan_freedreno.so") + lib.parentFile!!.mkdirs() + lib.writeText("") + val root = File(dir, "root").apply { mkdirs() } + val glIcd = "/usr/lib/aarch64-linux-gnu/GL/vulkan/icd.d" + val binds = BwrapSpawner.gpu(runtime.path, root, mutableMapOf("DD_DESKTOP" to "1"), true, glIcd = true)!! + val listed = File(binds.single { it.guest == glIcd }.host).listFiles()!!.map { it.name } + assertEquals(listOf("freedreno_icd.json"), listed) + assertTrue(File(binds.single { it.guest == glIcd }.host, "freedreno_icd.json").readText().contains("/run/droiddeck-gpu/libvulkan_freedreno.so")) + assertTrue(BwrapSpawner.gpu(runtime.path, root, mutableMapOf("DD_DESKTOP" to "1"), true)!!.none { it.guest == glIcd }) + assertEquals(null, BwrapSpawner.gpu(runtime.path, root, mutableMapOf("VK_DRIVER_FILES" to "/custom/icd.json"), true, glIcd = true)) + } + @Test fun buildsTheTreeFlatpakAsksFor() { val context = RuntimeEnvironment.getApplication() val info = Base64.encodeToString("[Application]\nname=org.example.Game\n".toByteArray(), Base64.NO_WRAP) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt new file mode 100644 index 0000000000..6400c0162e --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt @@ -0,0 +1,607 @@ +package com.droiddeck.launcher.runtime + +import android.app.Application +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.After +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], manifest = Config.NONE, application = Application::class) +class CurseForgeAppTest { + @get:Rule val temp = TemporaryFolder() + + private val original = CurseForgeApp.guest + private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED) + + @After + fun restoreGuest() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + launches.forEach { CurseForgeApp.stop(context, app, null, it) } + holder.get()?.set(true) + CurseForgeApp.guest = original + } + + private val launches = mutableListOf<java.util.concurrent.atomic.AtomicBoolean>() + + private fun launch(): java.util.concurrent.atomic.AtomicBoolean = java.util.concurrent.atomic.AtomicBoolean(false).also { launches += it } + + private val holder = java.util.concurrent.atomic.AtomicReference<java.util.concurrent.atomic.AtomicBoolean?>() + private val released = java.util.concurrent.CountDownLatch(1) + + private fun fakeGuest(startExit: Int, ready: Boolean = true): MutableList<List<String>> { + val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>()) + CurseForgeApp.guest = { _, argv, cancelled, onLine -> + calls += argv + when { + argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> { + if (startExit == 0) { + holder.set(cancelled) + onLine(url) + while (cancelled?.get() != true) Thread.sleep(10) + released.countDown() + } else onLine("busy") + startExit + } + argv[0] == CurseForgeApp.HELPER -> 0 + ready -> { onLine(JSONObject().put("ok", true).put("value", """{"value":true}""").toString()); 0 } + else -> { onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "no")).toString()); 0 } + } + } + return calls + } + + private val search = """{"success":true,"injectedCount":0, + "pagination":{"index":0,"pageSize":20,"resultCount":20,"totalCount":150}, + "mods":[ + {"id":486246,"name":"RestedXP Guide","summary":"Leveling guide","downloads":12345678, + "thumbnailUrl":"https://media.forgecdn.net/avatars/rxp.png","authors":[{"name":"RestedXP"}], + "updateVersion":{"id":7,"filename":"RXPGuides.zip","fileDate":"2026-11-20T10:00:00.000Z"}}, + {"id":2,"name":"Plain","downloads":5,"thumbnailUrl":"http://insecure/x.png","primaryAuthor":{"name":"Main"}, + "authors":[{"name":"Other"}],"projectLatestReleaseDate":"2026-01-01T00:00:00Z"}, + {"id":0,"name":"No id"}, + {"id":3,"name":""} + ]}""" + + @Test + fun searchResultsBecomeCatalogEntries() { + val page = CurseForgeApp.parseSearch(JSONObject(search)) + assertEquals(listOf("486246", "2"), page.items.map { it.id }) + val rxp = page.items[0] + assertEquals("RestedXP Guide", rxp.name) + assertEquals("RestedXP", rxp.author) + assertEquals(12345678L, rxp.downloads) + assertEquals(java.time.Instant.parse("2026-11-20T10:00:00Z").toEpochMilli(), rxp.updated) + assertEquals("https://media.forgecdn.net/avatars/rxp.png", rxp.thumb) + assertEquals("Main", page.items[1].author) + assertNull(page.items[1].thumb) + assertTrue(page.more) + } + + @Test + fun theLastPageHasNoMore() { + val last = JSONObject(search).put("pagination", JSONObject("""{"index":140,"resultCount":10,"totalCount":150}""")) + assertFalse(CurseForgeApp.parseSearch(last).more) + assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.parseSearch(JSONObject("""{"success":false}""")) } + assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.parseSearch(null) } + } + + @Test + fun searchRequestsUseTheInstanceAndOneBasedPages() { + val request = CurseForgeApp.searchRequest("guid-1", " Rested ", WowAddonCatalog.Sort.NAME, 0) + assertEquals(1, request.getInt("gameId")) + assertEquals("Rested", request.getString("searchText")) + assertEquals(1, request.getInt("page")) + assertEquals(1, request.getInt("sortColumn")) + assertEquals(1, request.getInt("sortOrder")) + assertEquals("guid-1", request.getString("gameInstanceGuid")) + assertEquals(2, CurseForgeApp.searchRequest("g", "", WowAddonCatalog.Sort.DOWNLOADS, 1).getInt("page")) + assertEquals(WowAddonCatalog.Sort.entries.size, WowAddonCatalog.Sort.entries.map(CurseForgeApp::sortOf).toSet().size) + } + + @Test + fun installRequestsInstallTheLatestFileIntoTheInstance() { + val request = CurseForgeApp.installRequest("guid-1", "486246") + assertEquals("guid-1", request.getString("instanceId")) + assertEquals(486246L, request.getLong("projectId")) + assertTrue(request.getBoolean("installLatestFile")) + } + + @Test + fun theInstanceIsPickedByItsFlavorFolder() { + val instances = JSONArray("""[ + {"guid":"retail","installPath":"/root/Games/WoW/_retail_/"}, + {"guid":"forever","installPath":"/root/Games/WoW/_forever_/"} + ]""") + assertEquals("forever", CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_forever_", "retail")) + assertEquals("retail", CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_retail_", null)) + assertNull(CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_classic_", "retail")) + val single = JSONArray("""[{"guid":"retail","installPath":"/root/Games/WoW/_retail_/"}]""") + assertNull(CurseForgeApp.instanceFor(single, "/root/Games/WoW/_classic_", "retail")) + assertEquals("retail", CurseForgeApp.instanceFor(single, "/root/Games/WoW/_retail_", "other")) + assertEquals("only", CurseForgeApp.instanceFor(JSONArray(), "/x/_forever_", "only")) + assertEquals("only", CurseForgeApp.instanceFor(null, "/x/_forever_", "only")) + assertNull(CurseForgeApp.instanceFor(JSONArray(), "/x/_forever_", "")) + } + + @Test + fun answersAreUnwrapped() { + val ok = JSONObject().put("ok", true).put("value", """{"value":{"resultStatus":3,"gameInstanceGuid":"g"}}""") + assertEquals("g", (CurseForgeApp.unwrap(ok) as JSONObject).getString("gameInstanceGuid")) + assertEquals(true, CurseForgeApp.unwrap(JSONObject().put("ok", true).put("value", """{"value":true}"""))) + val missing = JSONObject().put("ok", true).put("value", """{"missing":true}""") + assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(missing) } + val failed = JSONObject().put("ok", false).put("error", JSONObject().put("code", "NO_TARGET").put("message", "no node")) + val failure = assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(failed) } + assertEquals("no node", failure.message) + assertEquals("NO_TARGET", failure.code) + assertFalse(failure.gone) + val lost = JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "refused")) + assertTrue(assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(lost) }.gone) + } + + @Test + fun expressionsDriveTheHiddenDesktopWindow() { + val text = CurseForgeApp.expression("ProjectAppService", "search", JSONArray().put(JSONObject().put("searchText", "it's \"x\""))) + assertTrue(text.startsWith("(() => { const w = require('electron').BrowserWindow.getAllWindows()")) + assertTrue(text.contains("desktop.html")) + assertTrue(text.contains("executeJavaScript(")) + assertTrue(text.contains("let m = globalThis.__droiddeckServices; if (!m || !m[\\\"ProjectAppService\\\"]) m = globalThis.__droiddeckServices = ")) + assertFalse(text.contains("show()")) + val probe = CurseForgeApp.expression("InstalledProjectsAppService", "installAddon", null) + assertFalse(probe.contains("await s[")) + val connect = CurseForgeApp.expression("CoreService", "connect", JSONArray(), "r => true") + assertTrue(connect.contains("(r => true)(await s[\\\"connect\\\"](...[]))")) + } + + @Test + fun installedProjectsAndExitCodes() { + val projects = CurseForgeApp.parseProjects(JSONArray("""[ + {"id":"486246","installedModId":"a_486246","status":3,"locked":false,"folders":["RXPGuides","RXPGuides_Extra"]}, + {"id":"2","installedModId":"b_2","status":2,"locked":true,"folders":[]}, + {"id":null}]""")) + assertEquals(listOf("486246", "2"), projects.map { it.id }) + assertEquals("486246", CurseForgeApp.owner(projects, "RXPGuides_Extra")?.id) + assertNull(CurseForgeApp.owner(projects, "TomTom")) + assertFalse(projects[1].update) + assertTrue(CurseForgeApp.parseProjects(JSONObject()).isEmpty()) + assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0)) + assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3)) + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(4)) + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(5)) + } + + @Test + fun onlyASecretInspectorUrlIsTaken() { + val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + assertEquals(url, CurseForgeApp.inspectorUrl("noise\n$url\n")) + assertNull(CurseForgeApp.inspectorUrl("ready\n")) + assertNull(CurseForgeApp.inspectorUrl("ws://127.0.0.1:9229/\n")) + assertNull(CurseForgeApp.inspectorUrl("ws://10.0.0.2:43117/0f8fad5b-d9cb-469f-a165-70867728950e")) + assertNull(CurseForgeApp.inspectorUrl("$url/json")) + } + + @Test + fun theWowRootIsTheParentOfEveryFlavor() { + val root = temp.newFolder("World of Warcraft") + for (flavor in listOf("_classic_", "_classic_era_")) { + File(root, "$flavor/Interface/AddOns").mkdirs() + File(root, "$flavor/.flavor.info").writeText("x") + } + val title = BattleNet.TITLES.first { it.flavor == "_classic_" } + val targets = WowAddons.targets(title, File(root, "_classic_")) + assertEquals(listOf("_classic_", "_classic_era_"), targets.map { it.flavor }.sorted()) + for (target in targets) { + assertEquals(root, WowAddons.root(target)) + assertEquals(File(root, target.flavor), WowAddons.flavorDir(target)) + } + } + + @Test + fun theAppStartsInTheGuestWithoutASessionAndIsAskedThroughItsInspector() { + val calls = fakeGuest(0) + val started = CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch()) + assertEquals(CurseForgeApp.Start.READY, started.state) + assertEquals(url, started.inspector) + assertEquals(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge"), calls.first()) + val probe = calls[1] + assertEquals(listOf(CurseForgeApp.AGENT, "--cdp-inspector", url), probe.take(3)) + assertEquals("10.0", probe[3]) + assertTrue(probe[4].contains("InstalledProjectsAppService")) + } + + @Test + fun theLaunchLivesUntilItIsStopped() { + fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val hold = launch() + assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.start(context, app, hold).state) + assertEquals(false, holder.get()?.get()) + assertEquals(1L, released.count) + CurseForgeApp.stop(context, app, url, hold) + assertTrue(released.await(5, java.util.concurrent.TimeUnit.SECONDS)) + } + + @Test + fun anAppThatIsAlreadyOpenIsNeitherUsedNorStopped() { + val calls = fakeGuest(3) + assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch()).state) + assertEquals(listOf(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge")), calls) + } + + @Test + fun stoppingAsksTheAppToQuitThenStopsItsHeadlessLaunchOnce() { + val calls = fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val hold = launch() + CurseForgeApp.start(context, app, hold) + calls.clear() + CurseForgeApp.stop(context, app, url, hold) + assertEquals(CurseForgeApp.AGENT, calls[0][0]) + assertTrue(calls[0][4].contains("shutdown")) + assertEquals(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge"), calls[1]) + assertTrue(hold.get()) + calls.clear() + CurseForgeApp.stop(context, app, url, hold) + assertTrue(calls.isEmpty()) + } + + @Test + fun aLateStopLeavesTheNewerLaunchRunning() { + val calls = fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val old = launch() + val newer = launch() + CurseForgeApp.start(context, app, old) + CurseForgeApp.start(context, app, newer) + assertTrue(old.get()) + calls.clear() + CurseForgeApp.stop(context, app, url, old) + assertTrue(calls.isEmpty()) + assertEquals(false, newer.get()) + CurseForgeApp.stop(context, app, null, newer) + assertEquals(listOf(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge")), calls) + } + + @Test + fun aStoppedLaunchNeverStarts() { + val calls = fakeGuest(0) + val hold = launch().apply { set(true) } + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, hold).state) + assertTrue(calls.isEmpty()) + } + + @Test + fun anAppWithoutADirectoryIsNeverLaunched() { + val calls = fakeGuest(0) + val bare = UserApps.App("appimage:d", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, emptyList(), feed = CurseForgeApp.FEED) + val hold = launch() + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), bare, hold).state) + CurseForgeApp.stop(org.robolectric.RuntimeEnvironment.getApplication(), bare, url, hold) + assertTrue(calls.isEmpty()) + } + + @Test + fun aGameFolderCurseForgeAlreadyKnowsSkipsTheFolderDetection() { + val flavor = "/root/Games/World of Warcraft/_retail_" + val curse = fakeCurse(flavor = flavor) + val context = org.robolectric.RuntimeEnvironment.getApplication() + assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor)) + assertFalse("detectGameFromPath" in curse.methods) + } + + @Test + fun aGameFolderCurseForgeDoesNotKnowIsDetectedOnce() { + val flavor = "/root/Games/World of Warcraft/_retail_" + val curse = fakeCurse(flavor = flavor) + curse.known = false + val context = org.robolectric.RuntimeEnvironment.getApplication() + assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor)) + assertEquals(1, curse.methods.count { it == "detectGameFromPath" }) + assertEquals(listOf("getGameInstances", "detectGameFromPath", "getGameInstances"), curse.methods.filter { it != "connect" }) + } + + @Test + fun curseForgeConnectsOncePerLaunch() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + val launched = "ws://127.0.0.1:43118/${java.util.UUID.randomUUID()}" + CurseForgeApp.projects(context, launched, "g") + CurseForgeApp.projects(context, launched, "g") + CurseForgeApp.instance(context, launched, "/root", "") + assertEquals(1, curse.methods.count { it == "connect" }) + } + + @Test + fun theInspectorUrlIsRedactedFromCommandLogs() { + val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ") + assertTrue(line.contains(url)) + assertTrue(!GuestCommand.redacted(line, CurseForgeApp.INSPECTOR).contains("127.0.0.1")) + assertTrue(!GuestCommand.redacted(url, CurseForgeApp.INSPECTOR).contains(url)) + } + + private class Curse(val addOns: File, val flavor: String = "") { + val projects = java.util.concurrent.CopyOnWriteArrayList<JSONObject>() + val methods = java.util.Collections.synchronizedList(mutableListOf<String>()) + @Volatile var unreachableAfterDelete = false + @Volatile var unreachable = false + @Volatile var known = true + + fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status) + + fun add(id: String, folders: List<String>, status: Int, onDisk: List<String> = folders) { + onDisk.forEach { File(addOns, it).mkdirs() } + projects += JSONObject().put("id", id).put("installedModId", "m_$id").put("status", status).put("locked", false).put("folders", JSONArray(folders)) + } + + private fun folders(p: JSONObject) = (0 until p.getJSONArray("folders").length()).map { p.getJSONArray("folders").getString(it) } + + fun answer(expression: String): Any? { + val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(expression)?.groupValues?.get(1) ?: return true + methods += method + return when (method) { + "scanGameInstance" -> { + projects.removeAll { p -> !File(addOns, p.getJSONArray("folders").getString(0)).isDirectory } + true + } + "getProjects" -> JSONArray(projects.map { JSONObject(it.toString()) }) + "updateMod" -> { + projects.forEach { it.put("status", 1) } + true + } + "detectGameFromPath" -> { + known = true + JSONObject().put("gameInstanceGuid", "g") + } + "getGameInstances" -> if (known) JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) else JSONArray() + "deleteMods" -> { + projects.removeAll { p -> + (p.getString("installedModId") in expression).also { gone -> + if (gone) folders(p).forEach { name -> WowAddons.folder(addOns, name)?.deleteRecursively() } + } + } + if (unreachableAfterDelete) unreachable = true + JSONArray() + } + else -> true + } + } + } + + private fun fakeCurse(addOns: File = temp.newFolder("AddOns"), flavor: String = "", calls: MutableList<List<String>> = mutableListOf()): Curse { + val curse = Curse(addOns, flavor) + CurseForgeApp.guest = { _, argv, cancelled, onLine -> + calls += argv + when { + argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> { + onLine(url) + while (cancelled?.get() != true) Thread.sleep(10) + 0 + } + argv[0] == CurseForgeApp.HELPER -> 0 + curse.unreachable -> { + onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "gone")).toString()) + 0 + } + else -> { + val value = JSONObject().put("value", curse.answer(argv[4]) ?: JSONObject.NULL) + onLine(JSONObject().put("ok", true).put("value", value.toString()).toString()) + 0 + } + } + } + return curse + } + + private fun wow(): WowAddons.Target { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val games = temp.newFolder("Games") + val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() } + com.droiddeck.launcher.session.SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games")) + return WowAddons.Target("_retail_", addOns) + } + + @Test + fun anEntryCurseForgeStillListsShowsAsNotInstalledOnceItsFolderIsGone() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 1) + curse.add("18808", "TomTom", 1) + assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively()) + val listed = CurseForgeApp.projects(context, url, "g") + assertEquals(listOf("298842", "18808"), listed.map { it.id }) + assertEquals(listOf("18808"), CurseForgeApp.onDisk(listed, curse.addOns).map { it.id }) + } + + @Test + fun aProjectWithAnyFolderMissingOrNoFoldersIsNotInstalled() { + val addOns = temp.newFolder("Split") + File(addOns, "DBM-Core").mkdirs() + val split = CurseForgeApp.Project("3358", "m_3358", listOf("DBM-Core", "DBM-StatusBarTimers"), false) + val bare = CurseForgeApp.Project("1", "m_1", emptyList(), false) + assertTrue(CurseForgeApp.onDisk(listOf(split, bare), addOns).isEmpty()) + File(addOns, "DBM-StatusBarTimers").mkdirs() + assertEquals(listOf("3358"), CurseForgeApp.onDisk(listOf(split, bare), addOns).map { it.id }) + } + + @Test + fun aDeleteWhileCurseForgeIsLinkedGoesThroughItsUninstall() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("298842", "Leatrix_Maps", 1) + curse.add("18808", "TomTom", 1) + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + assertTrue(com.droiddeck.launcher.ui.CurseLink.live() === link) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertTrue("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id }) + } finally { + link.close(context) + } + assertNull(com.droiddeck.launcher.ui.CurseLink.live()) + } + + @Test + fun aDeleteWithoutALiveLinkRemovesTheFolderAtOnceWithoutStartingCurseForge() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>()) + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls) + curse.add("298842", "Leatrix_Maps", 1) + assertNull(com.droiddeck.launcher.ui.CurseLink.live()) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertTrue(calls.isEmpty()) + assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).none { it.id == "298842" }) + } + + @Test + fun aLinkThatNeverStartedIsNotUsedToDelete() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>()) + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls) + curse.add("298842", "Leatrix_Maps", 1) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps", com.droiddeck.launcher.ui.CurseLink(app)) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertTrue(calls.isEmpty()) + } + + @Test + fun anAddonWhoseFolderWasDeletedShowsAsNotInstalledAfterTheRescan() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 1) + assertEquals(listOf("298842"), CurseForgeApp.projects(context, url, "g", rescan = true).map { it.id }) + assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively()) + assertTrue(CurseForgeApp.projects(context, url, "g").isNotEmpty()) + assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).isEmpty()) + assertTrue("scanGameInstance" in curse.methods) + } + + @Test + fun aNewerFileShowsAsAnUpdateUntilCurseForgeUpdatesIt() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 2) + curse.add("18808", "TomTom", 1) + val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update } + assertEquals(mapOf("298842" to true, "18808" to false), before) + assertNotNull(CurseForgeApp.update(context, url, "g", "298842")) + assertTrue("updateMod" in curse.methods) + assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update }) + } + + @Test + fun uninstallingThroughCurseForgeClearsItsListAndTheFolder() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 1) + curse.add("18808", "TomTom", 1) + val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!! + assertNotNull(CurseForgeApp.uninstall(context, url, "g", project)) + assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id }) + assertFalse(File(curse.addOns, "Leatrix_Maps").exists()) + assertTrue(File(curse.addOns, "TomTom").isDirectory) + } + + @Test + fun anUninstallThatRemovedTheFolderBeforeCurseForgeWentAwayCountsAsDeleted() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("298842", "Leatrix_Maps", 1) + curse.unreachableAfterDelete = true + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + val before = WowAddons.imports + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertTrue("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertTrue(WowAddons.imports > before) + } finally { + kotlinx.coroutines.runBlocking { link.close(context).join() } + } + } + + @Test + fun aLocalDeleteInAProjectWithAMissingFolderKeepsItsOtherFolders() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("3358", listOf("DBM-Core", "DBM-GUI", "DBM-StatusBarTimers"), 1, onDisk = listOf("DBM-Core", "DBM-GUI")) + curse.add("298842", "Leatrix_Maps", 1) + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + com.droiddeck.launcher.ui.deleteAddon(context, target, "DBM-Core") + assertFalse("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "DBM-Core").exists()) + assertTrue(File(target.addOns, "DBM-GUI").isDirectory) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertTrue("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + } finally { + kotlinx.coroutines.runBlocking { link.close(context).join() } + } + } + + @Test + fun foldersMatchCurseForgesNamesWhateverTheirCase() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("12345", listOf("Questie"), 1, onDisk = listOf("questie")) + val listed = CurseForgeApp.projects(context, url, "g") + assertEquals(listOf("12345"), CurseForgeApp.onDisk(listed, target.addOns).map { it.id }) + assertEquals("12345", CurseForgeApp.byFolder(listed)["questie"]?.id) + assertEquals("questie", WowAddons.folder(target.addOns, "Questie")?.name) + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie") + assertTrue("deleteMods" in curse.methods) + assertNull(WowAddons.folder(target.addOns, "Questie")) + } finally { + kotlinx.coroutines.runBlocking { link.close(context).join() } + } + } + + @Test + fun aLocalDeleteFindsTheFolderWhateverItsCaseAndAnAbsentFolderIsAlreadyDeleted() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + File(target.addOns, "questie").mkdirs() + File(target.addOns, "TomTom").mkdirs() + com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie", null) + assertNull(WowAddons.folder(target.addOns, "Questie")) + assertTrue(File(target.addOns, "TomTom").isDirectory) + val before = WowAddons.imports + com.droiddeck.launcher.ui.deleteAddon(context, target, "Gone", null) + assertTrue(WowAddons.imports > before) + } + + @Test + fun theAgentAnswerIsTheLastJsonLine() { + assertEquals("a", CurseForgeApp.lastJson(listOf("noise", """{"v":"a"}""", "== done"))?.getString("v")) + assertNull(CurseForgeApp.lastJson(listOf("noise"))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt new file mode 100644 index 0000000000..67bf7d8614 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt @@ -0,0 +1,47 @@ +package com.droiddeck.launcher.runtime + +import com.droiddeck.launcher.ui.deckyStoreMatches +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) +@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class) +class DeckyStoreTest { + private val hash = "a".repeat(64) + private val listing = """[ + {"id":1,"name":"Alpha","author":"Ann","description":"Does alpha things","tags":["audio"],"image_url":"https://cdn.example/a.png", + "versions":[{"name":"2.0.0","hash":"$hash","downloads":10},{"name":"1.0.0","hash":"${"b".repeat(64)}","downloads":5}]}, + {"id":2,"name":"Beta","author":"Bob","description":"Themes","tags":["css"],"versions":[{"name":"1.0.0","hash":"${"c".repeat(64)}","downloads":100}]}, + {"id":3,"name":"NoVersions","author":"X","description":"","tags":[],"versions":[]}, + {"id":4,"name":"BadHash","author":"X","description":"","tags":[],"versions":[{"name":"1","hash":"nope","downloads":1}]} + ]""" + + @Test fun listingKeepsOnlyPluginsWithAUsableVersionAndSumsDownloads() { + val plugins = DeckyStore.parseListing(listing) + assertEquals(listOf("Alpha", "Beta"), plugins.map { it.name }) + assertEquals("2.0.0", plugins[0].latest?.name) + assertEquals(15L, plugins[0].downloads) + assertEquals("https://cdn.example/a.png", plugins[0].imageUrl) + assertEquals("", plugins[1].imageUrl) + } + + @Test fun searchMatchesNameAuthorDescriptionAndTagsAndSortsByDownloads() { + val plugins = DeckyStore.parseListing(listing) + assertEquals(listOf("Beta", "Alpha"), deckyStoreMatches(plugins, "").map { it.name }) + assertEquals(listOf("Alpha"), deckyStoreMatches(plugins, "ann audio").map { it.name }) + assertEquals(listOf("Beta"), deckyStoreMatches(plugins, "THEMES").map { it.name }) + assertTrue(deckyStoreMatches(plugins, "missing").isEmpty()) + } + + @Test fun anUpdateNeedsAKnownInstalledVersionThatDiffersFromTheLatest() { + val alpha = DeckyStore.parseListing(listing).first() + assertTrue(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", "1.0.0"), alpha)) + assertFalse(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", "2.0.0"), alpha)) + assertFalse(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", ""), alpha)) + assertFalse(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", "1.0.0"), null)) + assertNull(DeckyStore.parseListing("[]").firstOrNull()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt new file mode 100644 index 0000000000..3b4b008c50 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt @@ -0,0 +1,62 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.droiddeck.launcher.core.DownloadSource +import com.droiddeck.launcher.core.Downloader +import java.net.ServerSocket +import java.util.concurrent.CopyOnWriteArrayList +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class DesktopLanguageIndexSourceTest { + private val base = "https://github.com/Droid-Deck/desktop/releases/download/t/" + private val tunnels = CopyOnWriteArrayList<String>() + private lateinit var context: Context + private lateinit var proxy: ServerSocket + + @Before fun setUp() { + proxy = ServerSocket(0) + Thread { + try { + while (!proxy.isClosed) { + proxy.accept().use { socket -> + val line = socket.getInputStream().bufferedReader().readLine() ?: return@use + tunnels += line.removePrefix("CONNECT ").substringBefore(':') + socket.getOutputStream().write("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n".toByteArray()) + } + } + } catch (_: Exception) { + } + }.apply { isDaemon = true }.start() + context = ApplicationProvider.getApplicationContext() + DownloadSource.init(context) + DownloadSource.setMode(context, DownloadSource.MODE_MIRROR) + DownloadSource.setProxy(context, "127.0.0.1:${proxy.localPort}") + } + + @After fun tearDown() { + DownloadSource.setMode(context, DownloadSource.MODE_AUTO) + DownloadSource.setProxy(context, "") + proxy.close() + } + + @Test fun mirrorModeWouldOtherwiseSendTheIndexThroughAMirror() { + Downloader.downloadString(base + "desktop-kde.i18n.txt") + assertTrue(tunnels.toString(), tunnels.any { host -> DownloadSource.MIRRORS.any { it.host == host } }) + } + + @Test fun indexIsFetchedOnlyFromGithubInMirrorMode() { + assertNull(DesktopLanguage.fetchIndex(base)) + assertEquals(listOf("github.com"), tunnels.toList()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt index ee745b7d14..dea3a46859 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/LinuxNetworkLinkComponentTest.kt @@ -155,4 +155,37 @@ class LinuxNetworkLinkComponentTest { }) assertEquals(before, link) } + + @Test fun parallelPublishersFromSeparateComponentsAllLandAndLeaveNoStagedCopy() { + val context = ApplicationProvider.getApplicationContext<Context>() + val link = properties("10.0.0.1/24").route("1.0.0.0", 8).route("128.0.0.0", 1) + val failures = java.util.concurrent.atomic.AtomicInteger() + val threads = (0 until 8).map { + Thread { + val component = LinuxNetworkLinkComponent(context, temporary.root) + repeat(25) { + runCatching { + ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", + from(java.io.File::class.java, temporary.root.resolve("etc/droiddeck-net").apply { parentFile!!.mkdirs() }), + from(String::class.java, "if tun0 $it\n")) + }.onFailure { failures.incrementAndGet() } + } + }.apply { start() } + } + threads.forEach { it.join() } + assertEquals(0, failures.get()) + assertFalse(temporary.root.resolve("etc/droiddeck-net.staged").exists()) + assertEquals("if tun0 24\n", temporary.root.resolve("etc/droiddeck-net").readText()) + } + + @Test fun anUnchangedFileIsNotRewritten() { + val context = ApplicationProvider.getApplicationContext<Context>() + val component = LinuxNetworkLinkComponent(context, temporary.root) + val file = temporary.root.resolve("etc/resolv.conf").apply { parentFile!!.mkdirs(); writeText("nameserver 1.1.1.1\n") } + assertTrue(file.setLastModified(1_000_000L)) + ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 1.1.1.1\n")) + assertEquals(1_000_000L, file.lastModified()) + ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 8.8.8.8\n")) + assertEquals("nameserver 8.8.8.8\n", file.readText()) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt index 3188eb4e62..d8ea5ee185 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt @@ -44,18 +44,57 @@ class NativeGuestTest { val root = rootWithLoader() val command = NativeGuest.command(root, "/usr/bin/env", listOf("-i", "A=1")) assertEquals(File(root, "usr/lib/ld-linux-aarch64.so.1").path, command[0]) - assertEquals(listOf("--argv0", "env", File(root, "usr/bin/env").path, "-i", "A=1"), command.drop(1)) + assertEquals(listOf("--library-path", NativeGuest.libraryPath(root), "--argv0", "env", File(root, "usr/bin/env").path, "-i", "A=1"), command.drop(1)) + assertTrue("LD_LIBRARY_PATH" !in NativeGuest.environment(root, "/usr/bin/env")) + } + + @Test + fun builderKeepsCallerLibraryPathAheadOfRootfsDirectories() { + val root = rootWithLoader() + val rootDirs = NativeGuest.libraryPath(root).split(':') + val callerPath = "/custom/lib:${rootDirs[1]}:/other/lib" + val builder = NativeGuest.builder(root, "/", listOf("/usr/bin/env"), mapOf("LD_LIBRARY_PATH" to callerPath)) + val command = builder.command() + assertEquals(listOf("/custom/lib", rootDirs[1], "/other/lib") + rootDirs.filterNot { it == rootDirs[1] }, + command[command.indexOf("--library-path") + 1].split(':')) + assertEquals(callerPath, builder.environment()["LD_LIBRARY_PATH"]) + } + + @Test + fun builderPreservesEmptyCallerLibraryPathComponents() { + val root = rootWithLoader() + val rootPath = NativeGuest.libraryPath(root) + for (callerPath in listOf(":/custom/lib", "/custom/lib:", ":/custom/lib::")) { + val builder = NativeGuest.builder(root, "/", listOf("/usr/bin/env"), mapOf("LD_LIBRARY_PATH" to callerPath)) + val command = builder.command() + assertEquals("$callerPath:$rootPath", command[command.indexOf("--library-path") + 1]) + assertEquals(callerPath, builder.environment()["LD_LIBRARY_PATH"]) + } + for (env in listOf(emptyMap(), mapOf("LD_LIBRARY_PATH" to ""))) { + val command = NativeGuest.builder(root, "/", listOf("/usr/bin/env"), env).command() + assertEquals(rootPath, command[command.indexOf("--library-path") + 1]) + } } @Test fun mountsWithoutADestinationMapToThemselves() { val root = rootWithLoader() - val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b")) + val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b"), "/usr/bin/env") assertEquals("/dev:/dev|/a:/b", env["DDNATV_BINDS"]) assertEquals(root.path, env["DDNATV_ROOT"]) + assertTrue("LD_LIBRARY_PATH" !in env) assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so")) } + @Test + fun theProgramTheLoaderRunsIsNamedInItsEnvironment() { + val root = rootWithLoader() + val program = NativeGuest.command(root, "/usr/bin/env", listOf("-i"))[5] + assertEquals(program, NativeGuest.sessionEnvironment(root, listOf("/dev"), "/usr/bin/env")["DDNATV_REAL_EXE"]) + assertEquals(program, NativeGuest.environment(root, "/usr/bin/env")["DDNATV_REAL_EXE"]) + assertEquals(program, NativeGuest.builder(root, "/", listOf("/usr/bin/env", "-i"), emptyMap()).environment()["DDNATV_REAL_EXE"]) + } + private val linkRoot = "/data/user/0/app/files/linuxfs" private val sdBinds = listOf( "/mnt/media_rw/CARD/files/steam:/mnt/droiddeck-sd", diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/UserAppsFeedTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/UserAppsFeedTest.kt new file mode 100644 index 0000000000..e1c152b059 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/UserAppsFeedTest.kt @@ -0,0 +1,67 @@ +package com.droiddeck.launcher.runtime + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class UserAppsFeedTest { + private val feed = "https://example.com/apps/linux/latest-linux.yml" + private val sha = "ajcSve2Wq1CgocS5zWlmdfb0pI0C+JqNvbFx6Vm9j9/fW1Q/u2dnnNvNGmi0gulEXp7tnRkYCCc7rfwtjKcoNw==" + + private fun body(path: String = "App-1.2.0-7.AppImage", hash: String = sha) = """ + version: 1.2.0-7 + files: + - url: App-1.2.0-7.AppImage + sha512: $hash + size: 100 + - url: App_1.2.0-7_amd64.deb + sha512: other + path: $path + sha512: $hash + releaseDate: '2026-11-15T18:08:09.118Z' + """.trimIndent() + + @Test fun feedGivesTheAppImageRelease() { + val release = UserApps.parseFeed(feed, body())!! + assertEquals("1.2.0-7", release.tag) + assertEquals("App-1.2.0-7.AppImage", release.asset) + assertEquals("https://example.com/apps/linux/App-1.2.0-7.AppImage", release.url) + assertEquals("2026-11-15T18:08:09.118Z", release.published) + assertEquals(128, release.sha512!!.length) + assertEquals("6a3712bded96ab50a0a1c4b9cd696675f6f4a48d02f89a8dbdb171e959bd8fdfdf5b543fbb67679cdbcd1a68b482e9445e9eed9d191808273badfc2d8ca72837", release.sha512) + assertNull(release.sha256) + } + + @Test fun feedWithoutAnAppImageOrHashIsRefused() { + assertNull(UserApps.parseFeed(feed, body(path = "App_1.2.0-7_amd64.deb"))) + assertNull(UserApps.parseFeed(feed, body(path = "../App.AppImage"))) + assertNull(UserApps.parseFeed(feed, body(path = "sub/App.AppImage"))) + assertNull(UserApps.parseFeed(feed, body(hash = "c2hvcnQ="))) + assertNull(UserApps.parseFeed("http://example.com/latest-linux.yml", body())) + assertNull(UserApps.parseFeed(feed, "path: App.AppImage\n")) + } + + @Test fun curseForgeIsFoundByItsFeed() { + val other = UserApps.App("appimage:a", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, emptyList()) + val official = UserApps.App("appimage:b", UserApps.Kind.APPIMAGE, "Mods", null, null, AppImageManager.LAUNCHER, emptyList(), feed = CurseForgeApp.FEED) + assertEquals("appimage:b", CurseForgeApp.find(listOf(other, official))?.key) + assertNull(CurseForgeApp.find(listOf(other))) + } + + @Test fun olderOrEqualFeedReleasesAreNotOffered() { + val release = UserApps.parseFeed(feed, body())!! + assertTrue(UserApps.isNewer(release, "2026-11-01T00:00:00.000Z", "1.0")) + assertFalse(UserApps.isNewer(release, "2099-01-01T00:00:00.000Z", "9.9")) + assertFalse(UserApps.isNewer(release, "", release.tag)) + assertTrue(UserApps.isNewer(release, "", "0.1")) + } + + @Test fun publicationTimesCompareAsInstantsWhateverTheirPrecision() { + val release = UserApps.parseFeed(feed, body())!! + assertTrue(UserApps.isNewer(release, "2026-11-15T18:08:09Z", "1.0")) + assertFalse(UserApps.isNewer(release, "2026-11-15T18:08:09.118000Z", "1.0")) + assertFalse(UserApps.isNewer(release, "2026-11-15T18:08:10Z", "1.0")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt index 43bb29bb48..e298c39822 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt @@ -15,7 +15,7 @@ class WowAddonCatalogTest { private val context get() = RuntimeEnvironment.getApplication() private val files = """[ - {"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"]}, + {"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"],"UIDir":["Bartender4"," Bartender4_Options "]}, {"UID":"2","UICATID":"20","UIVersion":"2.0","UIDate":100,"UIName":"Zygor","UIAuthorName":"Kappa","UIDownloadTotal":"900","UICompatibility":[{"version":"1.15.7","name":"Classic"},{"version":"4.4.2","name":"Cataclysm Classic"}],"UIIMG_Thumbs":null}, {"UID":"3","UICATID":"21","UIVersion":"3.0","UIDate":200,"UIName":"Alpha","UIAuthorName":"bartuser","UIDownloadTotal":"10","UIDownloadMonthly":"9","UICompatibility":null}, {"UID":"4","UICATID":"19","UIVersion":"4.0","UIDate":400,"UIName":"TBCOnly","UIAuthorName":"x","UIDownloadTotal":"20","UIDownloadMonthly":"5","UICompatibility":[{"version":"2.5.4","name":"The Burning Crusade Classic"}]} @@ -44,6 +44,12 @@ class WowAddonCatalogTest { assertEquals("19", e[0].category) } + @Test fun fileListEntriesCarryTheirAddonFolders() { + val e = WowAddonCatalog.parseWowiFiles(files) + assertEquals(listOf("Bartender4", "Bartender4_Options"), e[0].addon.folders) + assertEquals(emptyList<String>(), e[1].addon.folders) + } + @Test fun versionsMapToFlavors() { assertEquals("_retail_", WowAddonCatalog.flavorOf("12.1.0")) assertEquals("_retail_", WowAddonCatalog.flavorOf("11.0.5")) @@ -150,8 +156,8 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf @Test fun wowiDetailsGiveUrlAndMd5() { val d = WowAddonCatalog.parseWowiDetails("""[{"UID":"1","UIMD5":"abc","UIDownload":"https://cdn.wowinterface.com/downloads/getfile.php?id=1"}]""") - assertEquals("https://cdn.wowinterface.com/downloads/getfile.php?id=1", d?.first) - assertEquals("abc", d?.second) + assertEquals("https://cdn.wowinterface.com/downloads/getfile.php?id=1", d?.url) + assertEquals("abc", d?.md5) assertNull(WowAddonCatalog.parseWowiDetails("""[{"UID":"1","UIDownload":""}]""")) assertNull(WowAddonCatalog.parseWowiDetails("[]")) } @@ -162,9 +168,66 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf assertTrue(WowAddonCatalog.isHttps("https://example.com/a.zip")) } - @Test fun curseForgeUrlAddsTheSearchText() { - assertEquals("https://www.curseforge.com/wow/search?class=addons", WowAddonCatalog.curseForgeUrl(" ")) - assertEquals("https://www.curseforge.com/wow/search?class=addons&search=deadly+boss+%26+mods", WowAddonCatalog.curseForgeUrl(" deadly boss & mods ")) + private fun entry(id: String, version: String) = + WowAddonCatalog.Entry(WowAddonCatalog.Addon(id, "Addon $id", "author", version, 0L, 0L, null), "1", null) + + @Test fun updatesComeFromTheInstalledSourceVersion() { + val entries = listOf(entry("10", "2.1.0"), entry("20", "v5"), entry("30", "")) + val installed = listOf( + WowAddons.Installed("Old", "2.0.9", "10"), + WowAddons.Installed("OldPart", "2.0.9", "10"), + WowAddons.Installed("Same", "5", "20"), + WowAddons.Installed("NoLatest", "1", "30"), + WowAddons.Installed("Unknown", "1", "99"), + WowAddons.Installed("Local", "1", null), + WowAddons.Installed("NoVersion", null, "10"), + ) + val updates = WowAddonCatalog.findUpdates(entries, installed) + assertEquals(setOf("Old"), updates.keys) + assertEquals("2.1.0", updates.getValue("Old").summary) + } + + @Test fun aCurrentRowDoesNotHideAnOutdatedRowWithTheSameSource() { + val installed = listOf(WowAddons.Installed("A", "2", "10"), WowAddons.Installed("B", "1", "10")) + assertEquals(setOf("B"), WowAddonCatalog.findUpdates(listOf(entry("10", "2")), installed).keys) + } + + @Test fun wowiDetailsCarryTheDownloadedVersion() { + val d = WowAddonCatalog.parseWowiDetails("""[{"UIDownload":"https://cdn.wowinterface.com/a.zip","UIVersion":" 2.0 "}]""") + assertEquals("2.0", d?.version) + assertNull(WowAddonCatalog.parseWowiDetails("""[{"UIDownload":"https://cdn.wowinterface.com/a.zip"}]""")?.version) + } + + @Test fun versionsCompareWithoutPrefixOrCase() { + assertTrue(WowAddonCatalog.sameVersion("v1.2.3", "1.2.3")) + assertTrue(WowAddonCatalog.sameVersion(" 1.2-Beta ", "1.2-beta")) + assertFalse(WowAddonCatalog.sameVersion("1.2.3", "1.2.4")) + } + + @Test fun versionsCompareNumericSegmentsFirst() { + assertEquals(true, WowAddonCatalog.newer("v4.11.38-7-ge56e9d8", "4.11.39")) + assertEquals(true, WowAddonCatalog.newer("1.9", "1.10")) + assertEquals(true, WowAddonCatalog.newer("2", "2.0.1")) + assertEquals(false, WowAddonCatalog.newer("11.2.0", "6.2.5")) + assertEquals(false, WowAddonCatalog.newer("2.0", "2")) + assertNull(WowAddonCatalog.newer("11.4.10-beta1", "11.4.10")) + assertNull(WowAddonCatalog.newer("release", "1.0")) + } + + @Test fun anUpdateIsOfferedOnlyForANewerVersionOrTheSameSourcesCurrentFile() { + assertTrue(WowAddonCatalog.offersUpdate("1.9", "1.10", sameSource = false)) + assertFalse(WowAddonCatalog.offersUpdate("11.2.0", "6.2.5", sameSource = true)) + assertFalse(WowAddonCatalog.offersUpdate("v1.2", "1.2", sameSource = true)) + assertTrue(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = true)) + assertFalse(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = false)) + assertFalse(WowAddonCatalog.offersUpdate(null, "1.0", sameSource = true)) + assertFalse(WowAddonCatalog.offersUpdate("1.0", "", sameSource = true)) + } + + @Test fun findUpdatesNeverOffersADowngrade() { + val installed = listOf(WowAddons.Installed("Ahead", "3.0", "10"), WowAddons.Installed("Tagged", "r55-alpha", "20")) + val updates = WowAddonCatalog.findUpdates(listOf(entry("10", "2.9"), entry("20", "r56")), installed) + assertEquals(setOf("Tagged"), updates.keys) } @Test fun md5Check() { diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsArchiveTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsArchiveTest.kt new file mode 100644 index 0000000000..2df9241d91 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsArchiveTest.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.runtime + +import org.apache.commons.compress.archivers.sevenz.SevenZOutputFile +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File +import java.nio.file.Files + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class WowAddonsArchiveTest { + @get:Rule val temp = TemporaryFolder() + + private fun target(): WowAddons.Target { + val root = temp.newFolder("World of Warcraft") + File(root, "_retail_").mkdirs() + return WowAddons.targets(BattleNet.title("wow")!!, root).single() + } + + private fun sevenZip(vararg files: Pair<String, String>): File { + val file = temp.newFile("addon-${System.nanoTime()}.bin") + SevenZOutputFile(file).use { out -> + for ((name, text) in files) { + val entry = out.createArchiveEntry(File(name), name) + out.putArchiveEntry(entry) + out.write(text.toByteArray()) + out.closeArchiveEntry() + } + } + return file + } + + private fun unpacked() = File(RuntimeEnvironment.getApplication().cacheDir, "wowaddons").listFiles().orEmpty().filter { it.name.startsWith("unpack-") } + + @Test fun sevenZipArchivesImportLikeZips() { + val target = target() + val names = WowAddons.import(sevenZip("Pack/Foo/Foo.toc" to "toc", "Pack/Foo/core.lua" to "lua", "Pack/Bar/Bar.toc" to "toc"), target, context = RuntimeEnvironment.getApplication()) + assertEquals(listOf("Bar", "Foo"), names.sorted()) + assertEquals("lua", File(target.addOns, "Foo/core.lua").readText()) + assertTrue(File(target.addOns, "Bar/Bar.toc").isFile) + assertTrue(unpacked().isEmpty()) + } + + @Test fun sevenZipArchivesWithoutAnAddonChangeNothing() { + val target = target() + assertEquals(emptyList<String>(), WowAddons.import(sevenZip("readme.txt" to "x"), target, context = RuntimeEnvironment.getApplication())) + assertFalse(target.addOns.exists()) + assertTrue(unpacked().isEmpty()) + } + + @Test fun aFolderWithAnyLinkIsRefusedWhole() { + val target = target() + val folder = temp.newFolder("unpacked") + File(folder, "Foo").mkdirs() + File(folder, "Foo/Foo.toc").writeText("toc") + Files.createSymbolicLink(File(folder, "Foo/link.lua").toPath(), File(folder, "Foo/Foo.toc").toPath()) + assertEquals(emptyList<String>(), WowAddons.importFolder(folder, target, null)) + assertFalse(target.addOns.exists()) + } + + @Test fun aFolderImportKeepsEveryFile() { + val target = target() + val folder = temp.newFolder("unpacked") + File(folder, "Foo/Libs").mkdirs() + File(folder, "Foo/Foo.toc").writeText("toc") + File(folder, "Foo/Libs/lib.lua").writeText("lib") + assertEquals(listOf("Foo"), WowAddons.importFolder(folder, target, null)) + assertEquals("lib", File(target.addOns, "Foo/Libs/lib.lua").readText()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt index 8350ef519b..6ea502407e 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt @@ -218,4 +218,100 @@ class WowAddonsTest { File(root, "_retail_").mkdirs() assertEquals(emptyList<String>(), WowAddons.targets(BattleNet.title("fenris")!!, root).map { it.flavor }) } + + @Test fun tocFieldsReadVersionAndSourceIds() { + val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n".lineSequence(), setOf("Version", "X-WoWI-ID", "X-Curse-Project-ID")) + assertEquals("1.4.2", fields["Version"]) + assertEquals("1234", fields["X-WoWI-ID"]) + assertEquals(null, fields["X-Curse-Project-ID"]) + } + + @Test fun tocFieldsKeepOnlyTheRequestedKeysAndStopOnceFound() { + var read = 0 + val lines = sequence { + yield("## Version: 2.0") + yield("## X-WoWI-ID: 5") + yield("## X-Curse-Project-ID: 9") + repeat(100_000) { read++; yield("## X-Data-$it: payload") } + } + val fields = WowAddons.tocFields(lines) + assertEquals(mapOf("Version" to "2.0", "X-WoWI-ID" to "5", "X-Curse-Project-ID" to "9"), fields) + assertEquals(0, read) + } + + @Test fun detailsSkipDataRowsInLargeTocs() { + val target = target() + val db = File(target.addOns, "BigDB").apply { mkdirs() } + File(db, "BigDB_Mists.toc").bufferedWriter().use { w -> + w.write("## Title: BigDB\nsrc\\main.lua\n") + repeat(50_000) { w.write("## X-Data-$it: ${"x".repeat(200)}\n") } + w.write("## Version: 3.1\n") + } + val details = WowAddons.details(target).single() + assertEquals("3.1", details.version) + assertEquals(null, details.wowiId) + } + + @Test fun detailsUseTheTocAndTheRecordedSource() { + val target = target() + val foo = File(target.addOns, "Foo").apply { mkdirs() } + File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n## X-Curse-Project-ID: 334372\n") + File(target.addOns, "Bar").mkdirs() + val details = WowAddons.details(target).associateBy { it.name } + assertEquals(setOf("Bar", "Foo"), details.keys) + assertEquals("1.0", details.getValue("Foo").version) + assertEquals("77", details.getValue("Foo").wowiId) + assertEquals("334372", details.getValue("Foo").curseId) + assertEquals(null, details.getValue("Bar").curseId) + assertEquals(null, details.getValue("Bar").version) + } + + @Test fun detailsFillFieldsTheMainTocLacksFromTheFlavourTocs() { + val target = target() + val questie = File(target.addOns, "Questie").apply { mkdirs() } + File(questie, "Questie.toc").writeText("## Interface: 00000\n## Title: Questie\n") + File(questie, "Questie_Vanilla.toc").writeText("## Version: 12.6.4\n## X-Curse-Project-ID: 334372\n") + File(questie, "Questie_Wrath.toc").writeText("## Version: 12.6.4\n") + val questieDetails = WowAddons.details(target).single() + assertEquals("12.6.4", questieDetails.version) + assertEquals("334372", questieDetails.curseId) + } + + @Test fun detailsKeepTheMainTocWhenItHasTheFields() { + val target = target() + val foo = File(target.addOns, "Foo").apply { mkdirs() } + File(foo, "Foo.toc").writeText("## Version: 2.0\n## X-Curse-Project-ID: 5\n") + File(foo, "Foo_Classic.toc").writeText("## Version: 1.0\n## X-Curse-Project-ID: 6\n## X-WoWI-ID: 7\n") + val fooDetails = WowAddons.details(target).single() + assertEquals("2.0", fooDetails.version) + assertEquals("5", fooDetails.curseId) + assertEquals("7", fooDetails.wowiId) + } + + @Test fun importRecordsTheSourceAndPlainImportsClearIt() { + val target = target() + WowAddons.import(zip("Foo/Foo.toc" to "## Version: 1.0\n"), target, WowAddons.Origin("55", "2.0")) + val recorded = WowAddons.details(target).single() + assertEquals("2.0", recorded.version) + assertEquals("55", recorded.wowiId) + WowAddons.import(zip("Foo/Foo.toc" to "## Version: 3.0\n"), target) + val plain = WowAddons.details(target).single() + assertEquals("3.0", plain.version) + assertEquals(null, plain.wowiId) + assertFalse(File(target.addOns, ".droiddeck-sources").exists()) + } + + @Test fun deleteForgetsTheRecordedSource() { + val target = target() + WowAddons.import(zip("Foo/Foo.toc" to "x", "Bar/Bar.toc" to "y"), target, WowAddons.Origin("55", "2.0")) + WowAddons.delete(target, "Foo") + assertEquals(mapOf("Bar" to "55"), WowAddons.parseOrigins(File(target.addOns, ".droiddeck-sources").readText()).mapValues { it.value.id }) + assertEquals(listOf("Bar"), WowAddons.installed(target)) + } + + @Test fun originsRoundTripAndSkipBrokenLines() { + val text = WowAddons.formatOrigins(mapOf("A" to WowAddons.Origin("1", "1.0 beta\t2"))) + assertEquals("1.0 beta 2", WowAddons.parseOrigins(text).getValue("A").version) + assertEquals(emptyMap<String, WowAddons.Origin>(), WowAddons.parseOrigins("bad line\nA\t\t1\n")) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/AvoidNotchPrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/AvoidNotchPrefsTest.kt new file mode 100644 index 0000000000..5f07411473 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/AvoidNotchPrefsTest.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class AvoidNotchPrefsTest { + private val app get() = RuntimeEnvironment.getApplication() + private val saved get() = app.getSharedPreferences("session", Context.MODE_PRIVATE) + + @Before fun clear() { saved.edit().clear().commit() } + + @Test fun theNotchIsLeftAloneUntilAskedToAvoidIt() { + assertFalse(SessionPrefs.avoidNotch(app)) + } + + @Test fun theChoiceIsKept() { + SessionPrefs.setAvoidNotch(app, true) + assertTrue(SessionPrefs.avoidNotch(app)) + SessionPrefs.setAvoidNotch(app, false) + assertFalse(SessionPrefs.avoidNotch(app)) + } + + @Test fun resettingSettingsTurnsItOff() { + SessionPrefs.setAvoidNotch(app, true) + assertTrue(SettingsReset.resetAll(app, gameProfiles = false)) + assertFalse(SessionPrefs.avoidNotch(app)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt index 74978ee30c..58d36b8166 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ComponentsRepublishTest.kt @@ -82,6 +82,37 @@ class ComponentsRepublishTest { private fun scopedTools() = rows().filter { it[0] == scope }.map { it[1] }.toSet() + @Test fun battleNetDropsAnOldPinnedFexOnceAndKeepsAnyOtherChoice() { + proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8") + packageFile() + ComponentsManager.setGameComponent(context, scope, "fex", fex) + ComponentsManager.setGameComponent(context, "123", "fex", fex) + assertTrue(rows().any { it[0] == scope }) + + ComponentsManager.migrateBattleNetFex(context) + + assertEquals(emptyMap<String, String>(), ComponentsManager.gameComponents(context, scope)) + assertEquals(fex, ComponentsManager.gameComponents(context, "123")["fex"]) + assertTrue(rows().none { it[0] == scope }) + assertTrue(rows().any { it[0] == "123" }) + + ComponentsManager.setGameComponent(context, scope, "fex", fex) + ComponentsManager.migrateBattleNetFex(context) + assertEquals(fex, ComponentsManager.gameComponents(context, scope)["fex"]) + } + + @Test fun battleNetKeepsAFexTheUserChoseThemselves() { + proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8") + val own = "FEXCore-2612-linux.wcp" + packageFile() + File(context.filesDir, "components/packages/$fex").copyTo(File(context.filesDir, "components/packages/$own")) + ComponentsManager.setGameComponent(context, scope, "fex", own) + + ComponentsManager.migrateBattleNetFex(context) + + assertEquals(own, ComponentsManager.gameComponents(context, scope)["fex"]) + } + private fun rows() = launchState().readLines().filter { it.isNotEmpty() }.map { it.split('\t') } private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv") diff --git a/app/src/test/java/com/droiddeck/launcher/session/ContentCadenceTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ContentCadenceTest.kt new file mode 100644 index 0000000000..2cb2e42fdb --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/ContentCadenceTest.kt @@ -0,0 +1,84 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ContentCadenceTest { + private val rates = intArrayOf(60, 90, 120, 144) + + @Test + fun aMeasuredRateSnapsToAStepAPanelRateDividesInto() { + assertEquals(45, ContentCadence.snap(44, rates)) + assertEquals(48, ContentCadence.snap(49, rates)) + assertEquals(72, ContentCadence.snap(72, rates)) + assertEquals(60, ContentCadence.snap(61, rates)) + assertEquals(0, ContentCadence.snap(53, rates)) + assertEquals(0, ContentCadence.snap(12, rates)) + assertEquals(0, ContentCadence.snap(45, intArrayOf(60))) + } + + @Test + fun aSteadyRateEngagesOnlyAfterItHolds() { + val cadence = ContentCadence() + assertFalse(cadence.note(45, rates)) + assertFalse(cadence.note(44, rates)) + assertEquals(0, cadence.rate) + assertTrue(cadence.note(45, rates)) + assertEquals(45, cadence.rate) + } + + @Test + fun aWanderingRateNeverEngages() { + val cadence = ContentCadence() + for (fps in intArrayOf(45, 53, 60, 71, 48, 45, 66, 45, 45, 58)) assertFalse(cadence.note(fps, rates)) + assertEquals(0, cadence.rate) + } + + @Test + fun oneOffSampleDoesNotReleaseAnEngagedRate() { + val cadence = ContentCadence() + repeat(3) { cadence.note(72, rates) } + assertFalse(cadence.note(55, rates)) + assertFalse(cadence.note(72, rates)) + assertFalse(cadence.note(51, rates)) + assertFalse(cadence.note(53, rates)) + assertEquals(72, cadence.rate) + assertTrue(cadence.note(55, rates)) + assertEquals(0, cadence.rate) + } + + @Test + fun aRateThatWasReleasedMustHoldLongerToEngageAgain() { + val cadence = ContentCadence() + repeat(3) { cadence.note(45, rates) } + repeat(3) { cadence.note(57, rates) } + assertEquals(0, cadence.rate) + repeat(5) { assertFalse(cadence.note(45, rates)) } + assertTrue(cadence.note(45, rates)) + assertEquals(45, cadence.rate) + } + + @Test + fun aReleasedRateDoesNotDelayARateThatWasNeverReleased() { + val cadence = ContentCadence() + repeat(3) { cadence.note(45, rates) } + repeat(3) { cadence.note(57, rates) } + assertEquals(0, cadence.rate) + repeat(2) { assertFalse(cadence.note(60, rates)) } + assertTrue(cadence.note(60, rates)) + assertEquals(60, cadence.rate) + } + + @Test + fun aResetDropsTheEngagedRateAndReportsTheChangeOnce() { + val cadence = ContentCadence() + repeat(3) { cadence.note(60, rates) } + assertTrue(cadence.reset()) + assertEquals(0, cadence.rate) + assertFalse(cadence.reset()) + repeat(2) { assertFalse(cadence.note(60, rates)) } + assertTrue(cadence.note(60, rates)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/DisplayDriverFromAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/session/DisplayDriverFromAutoTest.kt new file mode 100644 index 0000000000..1ab248db85 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/DisplayDriverFromAutoTest.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.gpu.TurnipDriver +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class DisplayDriverFromAutoTest { + private val context: Context get() = RuntimeEnvironment.getApplication() + + @Before fun reset() { + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + @Test fun noDisplayDriverChoiceIsAuto() { + SessionPrefs.setAndroidDriver(context, TurnipDriver.AUTO) + for (mode in listOf(SessionPrefs.GPU_DRIVERS_AUTO, SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.GPU_DRIVERS_MIX)) { + SessionPrefs.setGpuDriverMode(context, mode) + assertTrue(mode, SessionPrefs.displayDriverFromAuto(context)) + } + } + + @Test fun aPairDisplayHalfInstalledByAutoIsAuto() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0", "DD-Turnip_v0.8.0-linux")) + SessionPrefs.setAndroidDriver(context, "DD-Turnip_v0.8.0") + assertTrue(SessionPrefs.displayDriverFromAuto(context)) + } + + @Test fun aDriverTheUserImportedStaysTheirChoiceUnderAuto() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0")) + SessionPrefs.setAndroidDriver(context, "user-import") + assertFalse(SessionPrefs.displayDriverFromAuto(context)) + } + + @Test fun anAutoInstalledDriverPickedByHandStaysTheUsersChoice() { + SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0")) + SessionPrefs.setAndroidDriver(context, "DD-Turnip_v0.8.0") + for (mode in listOf(SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.GPU_DRIVERS_MIX)) { + SessionPrefs.setGpuDriverMode(context, mode) + assertFalse(mode, SessionPrefs.displayDriverFromAuto(context)) + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt b/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt index 05ef3bdd33..ea6bd6238d 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt @@ -403,6 +403,23 @@ class EnhancedSessionLogShareTest { SessionLogShare.clear(app) } + @Test fun rpcs3LogIsSharedByNameWithTheGameLogs() { + val session = tmp.newFolder("2026-11-24-05-rpcs3") + session.resolve("session.log").writeText("session\n") + session.resolve("rpcs3").mkdirs() + session.resolve("rpcs3/RPCS3.log").writeText("PPU: compiling\n") + + val zips = EnhancedSessionLogShare.create(app, session) + fun entries(suffix: String) = ZipFile(zips.single { it.name.endsWith("-$suffix.zip") }).use { archive -> + archive.entries().toList().map { it.name } + } + + assertTrue(entries("games").contains("${session.name}/rpcs3/RPCS3.log")) + assertTrue(entries("session").contains("${session.name}/session.log")) + assertFalse(entries("games").contains("${session.name}/session.log")) + SessionLogShare.clear(app) + } + @Test fun unreadableDiscoverySubtreeKeepsOtherLogsAndMarksTheManifestPartial() { assumeFilePermissionsEnforced() assumeFalse(System.getProperty("os.name").startsWith("Windows")) diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt index b5060392a5..a6b50eb1cc 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/GameStorageTest.kt @@ -113,4 +113,18 @@ class GameStorageTest { SessionPrefs.setGameStorage(app, tmp.newFolder("plugged").path, "USB drive") assertFalse(GameStorage.disconnected(app)) } + + @Test fun onlyAVfatMountCountsAsFat32() { + val mounts = """ + /dev/fuse /storage/emulated fuse rw 0 0 + /dev/block/vold/public:179,65 /mnt/media_rw/8C5A-1F23 vfat rw 0 0 + /dev/block/vold/public:8,1 /mnt/media_rw/1111-2222 exfat rw 0 0 + /dev/fuse /storage/8C5A-1F23 fuse rw 0 0 + """.trimIndent() + assertTrue(GameStorage.isFat32("/storage/8C5A-1F23/Android/data/com.droiddeck.launcher/files/steam", mounts)) + assertTrue(GameStorage.isFat32("/mnt/media_rw/8C5A-1F23/Games", mounts)) + assertFalse(GameStorage.isFat32("/storage/1111-2222/Android/data/com.droiddeck.launcher/files/steam", mounts)) + assertFalse(GameStorage.isFat32("/storage/emulated/0/Android/data/com.droiddeck.launcher/files/steam", mounts)) + assertFalse(GameStorage.isFat32("/storage/8C5A-1F230/Games", mounts)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameThreadHintsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameThreadHintsTest.kt index ff5867d4c2..6482177c0a 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/GameThreadHintsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/GameThreadHintsTest.kt @@ -10,6 +10,7 @@ class GameThreadHintsTest { assertTrue(GameThreadHints.supported("CQ8725S")) assertTrue(GameThreadHints.supported("SM8750")) assertTrue(GameThreadHints.supported("QTI SM8750")) + assertTrue(GameThreadHints.supported("QTI SM8750P")) assertFalse(GameThreadHints.supported("SM8650")) assertFalse(GameThreadHints.supported("SM8850")) assertFalse(GameThreadHints.supported("")) diff --git a/app/src/test/java/com/droiddeck/launcher/session/LaunchCoordinatorTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LaunchCoordinatorTest.kt new file mode 100644 index 0000000000..0a2feeed36 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/LaunchCoordinatorTest.kt @@ -0,0 +1,121 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class LaunchCoordinatorTest { + @Test + fun aNewLaunchSupersedesAnOlderLaunch() { + val coordinator = LaunchCoordinator<String, String>() + val first = coordinator.beginLaunch() + val second = coordinator.beginLaunch() + assertFalse(coordinator.isCurrent(first)) + assertTrue(coordinator.isCurrent(second)) + } + + @Test + fun anAllowedLaunchDropsThePendingLink() { + val coordinator = LaunchCoordinator<String, String>() + coordinator.beginLink("link") + coordinator.beginLaunch() + assertFalse(coordinator.hasPending()) + } + + @Test + fun aLinkReadResolvesAndIsConsumed() { + val coordinator = LaunchCoordinator<String, String>() + val ticket = coordinator.beginLink("link") + assertTrue(coordinator.resolve(ticket, "game")) + assertEquals("game", coordinator.pendingLink()?.request) + assertTrue(coordinator.consume(ticket)) + assertFalse(coordinator.hasPending()) + } + + @Test + fun aStaleLinkReadCannotReplaceTheNewLink() { + val coordinator = LaunchCoordinator<String, String>() + val first = coordinator.beginLink("first") + val second = coordinator.beginLink("second") + assertFalse(coordinator.resolve(first, "old")) + assertTrue(coordinator.resolve(second, "new")) + assertEquals("new", coordinator.pendingLink()?.request) + } + + @Test + fun handlingNeedsAResolvedLink() { + val coordinator = LaunchCoordinator<String, String>() + val ticket = coordinator.beginLink("link") + assertFalse(coordinator.beginHandling(ticket)) + coordinator.resolve(ticket, "game") + assertTrue(coordinator.beginHandling(ticket)) + assertTrue(coordinator.isHandling(ticket)) + } + + @Test + fun aStaleCompletionCannotConsumeTheNewLink() { + val coordinator = LaunchCoordinator<String, String>() + val first = coordinator.beginLink("first") + val second = coordinator.beginLink("second") + coordinator.resolve(second, "new") + assertFalse(coordinator.consume(first)) + assertTrue(coordinator.hasPending()) + } + + @Test + fun aUiLaunchDropsThePendingLinkBeforeItLaunches() { + val coordinator = LaunchCoordinator<String, String>() + coordinator.beginLink("link") + val launch = coordinator.beginLaunch() + assertNull(coordinator.pendingLink()) + assertTrue(coordinator.isCurrent(launch)) + } + + @Test + fun aSecondLinkReplacesTheFirst() { + val coordinator = LaunchCoordinator<String, String>() + val first = coordinator.beginLink("first") + val second = coordinator.beginLink("second") + assertFalse(coordinator.isCurrent(first)) + assertTrue(coordinator.isCurrent(second)) + assertEquals("second", coordinator.pendingLink()?.owner) + } + + @Test + fun aLinkKeepsItsOwnerForIntentCleanup() { + val coordinator = LaunchCoordinator<String, String>() + val ticket = coordinator.beginLink("intent-a") + coordinator.resolve(ticket, "game") + assertSame("intent-a", coordinator.pendingLink()?.owner) + } + + @Test + fun aLinkIsOwnedOnlyByItsIntent() { + val coordinator = LaunchCoordinator<String, String>() + val ticket = coordinator.beginLink("intent-a") + coordinator.resolve(ticket, "game") + val link = requireNotNull(coordinator.pendingLink()) + assertTrue(link.ownedBy("intent-a")) + assertFalse(link.ownedBy("intent-b")) + assertFalse(link.ownedBy(null)) + assertTrue(coordinator.consume(ticket)) + assertNull(coordinator.pendingLink()) + } + + @Test + fun cancelAllInvalidatesEveryOutstandingTicket() { + val coordinator = LaunchCoordinator<String, String>() + coordinator.beginLaunch() + val link = coordinator.beginLink("link") + assertTrue(coordinator.isCurrent(link)) + coordinator.cancelAll() + assertFalse(coordinator.isCurrent(link)) + assertFalse(coordinator.hasPending()) + assertNull(coordinator.pendingLink()) + assertFalse(coordinator.resolve(link, "late")) + assertFalse(coordinator.consume(link)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt deleted file mode 100644 index 8e14b74147..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt +++ /dev/null @@ -1,56 +0,0 @@ -package com.droiddeck.launcher.session - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class LightPauseTest { - @Test - fun theBounceAloneResumesLight() { - val pause = LightPause() - pause.paused(bounces = 3) - assertEquals(LightPause.Resume.LIGHT, pause.resumed(bounces = 4)) - assertFalse(pause.timedOut()) - } - - @Test - fun anUnrelatedPauseWithoutABounceCleansUpAtTheTimeout() { - val pause = LightPause() - pause.paused(bounces = 3) - assertTrue(pause.timedOut()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 3)) - } - - @Test - fun aBounceWhileAnotherActivityHoldsThePauseStillCleansUpAtTheTimeout() { - val pause = LightPause() - pause.paused(bounces = 3) - assertTrue(pause.timedOut()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4)) - } - - @Test - fun aResumeBeforeTheTimeoutWithoutABounceCleansUpFirst() { - val pause = LightPause() - pause.paused(bounces = 3) - assertEquals(LightPause.Resume.CLEANUP_FIRST, pause.resumed(bounces = 3)) - assertFalse(pause.timedOut()) - } - - @Test - fun aStopAfterALightPauseCleansUpOnce() { - val pause = LightPause() - pause.paused(bounces = 3) - assertTrue(pause.stopped()) - assertFalse(pause.timedOut()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4)) - } - - @Test - fun aNormalPauseIsUntouched() { - val pause = LightPause() - assertFalse(pause.stopped()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 0)) - } -} diff --git a/app/src/test/java/com/droiddeck/launcher/session/LoadingStateUpdateTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LoadingStateUpdateTest.kt index 0ef4ebaeeb..30c273969c 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/LoadingStateUpdateTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/LoadingStateUpdateTest.kt @@ -76,6 +76,80 @@ class LoadingStateUpdateTest { assertEquals(LoadingState.Topic.DESKTOP, state.topic) } + @Test fun bootstrapperProgressWithThousandsSeparatorsIsRead() { + val state = read("[2026-11-15 11:58:51] Downloading update (184,557 of 573,070 KB)...") + assertEquals(32, state.percent) + assertEquals("Downloading the Steam client update · 32%", state.step) + } + + @Test fun translatedBootstrapperProgressUsesItsPercentLine() { + val state = read( + "[2026-11-15 11:58:51] 正在下载更新 (已下载 184,557,共 573,070 KB)...", + "[2026-11-15 11:58:51] Set status message: 正在下载更新 (已下载 184,557,共 573,070 KB)...", + "[2026-11-15 11:58:51] Set percent complete: 32", + ) + assertEquals(32, state.percent) + assertEquals(LoadingState.Topic.STEAM, state.topic) + assertTrue(state.readable) + } + + @Test fun anUnknownPercentDoesNotLookLikeProgress() { + val state = read("[2026-11-15 11:53:37] Set percent complete: -1") + assertEquals(-1, state.percent) + } + + @Test fun aVerificationOnlyPassKeepsTheScriptStep() { + val state = read( + "[2026-11-15 11:53:36] Set percent complete: 0", + "[2026-11-15 11:53:37] Set percent complete: -1", + "[2026-11-15 11:53:37] Verifying installation...", + ) + assertEquals("starting the Steam client", state.step) + assertEquals(-1, state.percent) + } + + @Test fun aPercentLineDoesNotReplaceApplyingInTheSameStep() { + assertApplying(read("Extracting package...", "[2026-11-15 11:58:52] Set percent complete: 100")) + } + + @Test fun anUnknownPercentEndsAnEarlierPercent() { + val state = read( + "[2026-11-15 11:58:51] Set percent complete: 40", + "[2026-11-15 11:58:52] Set percent complete: -1", + ) + assertEquals("starting the Steam client", state.step) + assertEquals(-1, state.percent) + } + + @Test fun aPercentLineCountsAgainAfterANewStep() { + val state = read( + "Installing update...", + "== STEP 12:00:03 starting the Steam client", + "[2026-11-15 11:58:51] Set percent complete: 40", + ) + assertEquals(40, state.percent) + } + + @Test fun aPercentOutsideTheIntRangeIsIgnored() { + val state = read( + "[2026-11-15 11:58:51] Set percent complete: 40", + "[2026-11-15 11:58:52] Set percent complete: 2147483648", + ) + assertEquals(40, state.percent) + } + + @Test fun anUnknownPercentClearsTheDisplayedPercentAfterTheStepLeavesTheTail() { + val context = RuntimeEnvironment.getApplication() + val log = log("[2026-11-15 11:58:51] Set percent complete: 40") + val state = LoadingState(context) + state.update(context, log) + assertEquals(40, state.percent) + log.appendText("\n" + "Loading cached metrics\n".repeat(4096) + "[2026-11-15 11:58:52] Set percent complete: -1") + state.update(context, log) + assertEquals(-1, state.percent) + assertEquals("starting the Steam client", state.step) + } + @Test fun anExistingLoadingStateFollowsUpdatesAcrossPolls() { val context = RuntimeEnvironment.getApplication() val log = log("Downloading update (100 of 100 KB)") diff --git a/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt b/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt new file mode 100644 index 0000000000..748b0a96e6 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/OnboardingTest.kt @@ -0,0 +1,73 @@ +package com.droiddeck.launcher.session + +import com.droiddeck.launcher.session.Onboarding.Facts +import com.droiddeck.launcher.session.Onboarding.Progress +import com.droiddeck.launcher.session.Onboarding.State +import com.droiddeck.launcher.session.Onboarding.Step +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class OnboardingTest { + private val none = Facts(runtime = false, proton = false, steam = false) + + @Before fun fresh() = Onboarding.resetProgress() + + @Test fun everythingReadyShowsNothing() { + val rows = Onboarding.rows(emptyMap(), emptyMap(), Facts()) + assertFalse(Onboarding.pending(rows)) + assertEquals(100, Onboarding.overall(rows)) + } + + @Test fun stepsAreActiveFailedOrWaiting() { + val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), mapOf(Step.PROTON to "no"), none) + assertEquals(listOf(State.ACTIVE, State.FAILED, State.WAITING), rows.map { it.state }) + assertTrue(Onboarding.pending(rows)) + } + + @Test fun anActiveStepStaysActiveWhenItsFactIsAlreadyTrue() { + val rows = Onboarding.rows(mapOf(Step.STEAM to Progress("x", -1)), emptyMap(), Facts()) + assertEquals(State.ACTIVE, rows.first { it.step == Step.STEAM }.state) + } + + @Test fun overallWeighsDownloadsBySize() { + val rows = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 50)), emptyMap(), Facts(runtime = false)) + assertEquals(10 + 30 + 50, Onboarding.overall(rows)) + } + + @Test fun overallNeverGoesBackwardsWhileStepsHandOver() { + val prefetched = Onboarding.rows(mapOf(Step.PROTON to Progress("x", 100)), emptyMap(), Facts(runtime = true, proton = false, steam = false)) + val before = Onboarding.overall(prefetched) + val handover = Onboarding.rows(mapOf(Step.STEAM to Progress("y", 4)), emptyMap(), Facts(runtime = true, proton = false, steam = false)) + assertTrue(Onboarding.overall(handover) >= before) + val installing = Onboarding.rows(mapOf(Step.PROTON to Progress("z", 0), Step.STEAM to Progress("y", 4)), emptyMap(), Facts(runtime = true, proton = false, steam = false)) + assertTrue(Onboarding.overall(installing) >= before) + } + + @Test fun overallStartsOverOnceEverythingIsReady() { + Onboarding.overall(Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 90)), emptyMap(), Facts(runtime = false))) + assertEquals(100, Onboarding.overall(Onboarding.rows(emptyMap(), emptyMap(), Facts()))) + val again = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 10)), emptyMap(), Facts(runtime = false)) + assertEquals(2 + 30 + 50, Onboarding.overall(again)) + } + + @Test fun settlingWithEverythingReadyStartsTheNextAttemptFromZero() { + Onboarding.overall(Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 90)), emptyMap(), Facts(runtime = false))) + Onboarding.active.value = emptyMap() + Onboarding.failed.value = emptyMap() + Onboarding.facts.value = Facts() + Onboarding.settle() + val again = Onboarding.rows(mapOf(Step.RUNTIME to Progress("x", 10)), emptyMap(), Facts(runtime = false)) + assertEquals(2 + 30 + 50, Onboarding.overall(again)) + } + + @Test fun reportingClearsAPriorFailure() { + Onboarding.fail(Step.STEAM, "boom") + Onboarding.report(Step.STEAM, "again", 3) + assertTrue(Onboarding.failed.value[Step.STEAM] == null) + Onboarding.finish(Step.STEAM) + assertTrue(Onboarding.active.value[Step.STEAM] == null) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/PerfModeTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PerfModeTest.kt index 3a7dff017f..1bd7ed3444 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PerfModeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PerfModeTest.kt @@ -56,4 +56,64 @@ class PerfModeTest { assertTrue(PerfMode.needsChange(modes, 0, oneTwenty)) assertTrue(PerfMode.needsChange(modes, 99, oneTwenty)) } + + @Test fun aGuestFrameRateChoosesTheHighestPanelRateItDividesEvenly() { + val modes = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f), mode(4, 144f)) + val current = modes[3] + assertEquals(modes[2], PerfMode.selectMode(modes, current, 60, Float.POSITIVE_INFINITY, 120)) + assertEquals(modes[2], PerfMode.selectMode(modes, current, 40, Float.POSITIVE_INFINITY, 120)) + assertEquals(modes[1], PerfMode.selectMode(modes, current, 45, Float.POSITIVE_INFINITY, 90)) + assertEquals(modes[3], PerfMode.selectMode(modes, current, 72, Float.POSITIVE_INFINITY, 144)) + assertEquals(modes[3], PerfMode.selectMode(modes, current, 50, Float.POSITIVE_INFINITY, 144)) + } + + @Test fun frameGenerationRaisesThePanelRateToItsOutputRate() { + val modes = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f), mode(4, 144f)) + val current = modes[0] + assertEquals(120, PerfMode.contentRate(60, 2, 0)) + assertEquals(60, PerfMode.contentRate(60, 1, 0)) + assertEquals(90, PerfMode.contentRate(40, 3, 90)) + assertEquals(0, PerfMode.contentRate(0, 2, 0)) + assertEquals(modes[2], PerfMode.selectMode(modes, current, PerfMode.contentRate(60, 2, 0), Float.POSITIVE_INFINITY)) + assertEquals(modes[1], PerfMode.selectMode(modes, current, PerfMode.contentRate(45, 2, 0), Float.POSITIVE_INFINITY)) + assertEquals(modes[3], PerfMode.selectMode(modes, current, PerfMode.contentRate(72, 2, 0), Float.POSITIVE_INFINITY)) + assertEquals(modes[3], PerfMode.selectMode(modes, current, PerfMode.contentRate(60, 3, 0), Float.POSITIVE_INFINITY)) + assertEquals(modes[2], PerfMode.selectMode(modes, current, PerfMode.contentRate(60, 4, 0), 120f)) + } + + @Test fun aGuestRefreshRequestWithoutAFrameRatePicksThatPanelRate() { + val modes = arrayOf(mode(1, 60f), mode(2, 90f), mode(3, 120f)) + val current = modes[2] + assertEquals(modes[0], PerfMode.selectMode(modes, current, 0, Float.POSITIVE_INFINITY, 60)) + assertEquals(modes[1], PerfMode.selectMode(modes, current, 0, Float.POSITIVE_INFINITY, 75)) + assertEquals(modes[1], PerfMode.selectMode(modes, current, 0, 90f, 120)) + assertEquals(modes[2], PerfMode.selectMode(modes, current, 0, Float.POSITIVE_INFINITY, 0)) + } + + @Test fun panelRatesListOnlyTheCurrentSizeWithinTheCap() { + val modes = arrayOf(mode(1, 60f), mode(2, 120f), mode(3, 144f), mode(4, 90f, 720), mode(5, 59.94f)) + assertEquals(listOf(60, 120, 144), PerfMode.panelRates(modes, modes[1], Float.POSITIVE_INFINITY).toList()) + assertEquals(listOf(60, 120), PerfMode.panelRates(modes, modes[1], 120f).toList()) + } + + @Test fun aPanelTheSystemHoldsOffersOnlyItsCurrentRate() { + val modes = arrayOf(mode(1, 60f), mode(2, 120f), mode(3, 185f)) + assertTrue(PerfMode.panelHeld(185f, 120f)) + assertTrue(PerfMode.panelHeld(60f, 120f)) + assertFalse(PerfMode.panelHeld(120f, 119.88f)) + assertFalse(PerfMode.panelHeld(0f, 120f)) + assertEquals(listOf(120), PerfMode.panelRates(modes, modes[1], Float.POSITIVE_INFINITY, true).toList()) + assertEquals(listOf(60, 120, 185), PerfMode.panelRates(modes, modes[1], Float.POSITIVE_INFINITY, false).toList()) + } + + @Test + fun aSteadyRateBelowAnUnconstrainingLimiterSetsThePace() { + assertEquals(30, PerfMode.pacedRate(30, 120, 120, 45)) + assertEquals(45, PerfMode.pacedRate(0, 0, 0, 45)) + assertEquals(40, PerfMode.pacedRate(0, 40, 120, 45)) + assertEquals(45, PerfMode.pacedRate(0, 120, 120, 45)) + assertEquals(120, PerfMode.pacedRate(0, 120, 120, 60)) + assertEquals(120, PerfMode.pacedRate(0, 120, 120, 0)) + assertEquals(60, PerfMode.pacedRate(0, 60, 0, 45)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt new file mode 100644 index 0000000000..f010e97a65 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt @@ -0,0 +1,127 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.content.pm.ActivityInfo +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class PortraitResolutionTest { + private val app get() = RuntimeEnvironment.getApplication() + private val panel = 2400 to 1080 + + @Before fun clear() { + app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + @Test fun portraitFollowsLandscapeUntilItIsSet() { + assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "steam", panel, true)) + SessionPrefs.setResolutionChoice(app, "steam", "900p") + assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, false)) + assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, true)) + } + + @Test fun eachOrientationKeepsItsOwnResolution() { + SessionPrefs.setResolutionChoice(app, "steam", "1600x720") + SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true) + assertEquals("1600x720", SessionPrefs.resolutionChoice(app, "steam", panel, false)) + assertEquals("1080p", SessionPrefs.resolutionChoice(app, "steam", panel, true)) + assertEquals("1080p", SessionPrefs.resolutionStored(app, "steam", panel, true)) + } + + @Test fun landscapeCanFollowPortrait() { + SessionPrefs.setResolutionChoice(app, "steam", "720x1280", portrait = true) + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) + assertEquals(SessionDisplay.LINK_PORTRAIT, SessionPrefs.resolutionStored(app, "steam", panel, false)) + assertEquals("1280x720", SessionPrefs.resolutionChoice(app, "steam", panel, false)) + assertEquals("720x1280", SessionPrefs.resolutionChoice(app, "steam", panel, true)) + } + + @Test fun followingEachOtherNeverLoops() { + SessionPrefs.setResolutionChoice(app, "steam", "900p") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) + assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, false)) + assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, true)) + assertFalse(SessionDisplay.isLink(SessionPrefs.resolutionStored(app, "steam", panel, true))) + } + + @Test fun aGeneratedPortraitSizeSurvivesAReload() { + SessionPrefs.setResolutionChoice(app, "steam", "2560x1440") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) + assertEquals("1440x2560", SessionPrefs.resolutionStored(app, "steam", panel, true)) + assertEquals("2560x1440", SessionPrefs.resolutionChoice(app, "steam", panel, false)) + assertEquals("1440x2560", SessionPrefs.resolutionChoice(app, "steam", panel, true)) + } + + @Test fun aSavedDesktopResolutionInEitherOrientationCountsAsChosen() { + SessionPrefs.setResolutionChoice(app, SessionService.MODE_DESKTOP, "1080p", portrait = true) + assertTrue(SessionPrefs.resolutionChosen(app, SessionService.MODE_DESKTOP, true)) + assertEquals(SessionService.MODE_DESKTOP, + SessionPrefs.displayMode(app, SessionService.MODE_RUN, com.droiddeck.launcher.runtime.UserApps.SCRIPT_LAUNCHER)) + } + + @Test fun portraitInputAcceptsTallSizesLandscapeInputDoesNot() { + assertNull(SessionPrefs.parseResolution("1440x2560")) + assertEquals(1440 to 2560, SessionPrefs.parseOrientedResolution("1440x2560")) + assertEquals(1280 to 720, SessionPrefs.parseOrientedResolution("1280x720")) + assertNull(SessionPrefs.parseOrientedResolution("100x100")) + SessionPrefs.setResolutionChoice(app, "steam", "1440x2560", portrait = true) + assertEquals("1440x2560", SessionPrefs.resolutionStored(app, "steam", panel, true)) + } + + @Test fun followScreenInLandscapeLeavesAFixedPortraitSizeFixed() { + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.FOLLOW_SCREEN) + SessionPrefs.setResolutionChoice(app, "steam", "1024x768", portrait = true) + assertEquals(1f to null, SessionPrefs.followScales(app, "steam", panel)) + } + + @Test fun followScreenInPortraitLeavesAFixedLandscapeSizeFixed() { + SessionPrefs.setResolutionChoice(app, "steam", "1080p") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.followScaled(2f), portrait = true) + assertEquals(null to 2f, SessionPrefs.followScales(app, "steam", panel)) + } + + @Test fun followScalesKeepLinkedAndFixedChoices() { + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.followScaled(1.5f)) + assertEquals(1.5f to 1.5f, SessionPrefs.followScales(app, "steam", panel)) + SessionPrefs.setResolutionChoice(app, "steam", "1024x768", portrait = true) + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) + assertEquals(null to null, SessionPrefs.followScales(app, "steam", panel)) + app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + assertEquals(null to null, SessionPrefs.followScales(app, "steam", panel)) + } + + @Test fun anAutoOrientationIsNotChangedByFollowScreen() { + assertFalse(SessionPrefs.portrait(app)) + SessionPrefs.setOrientation(app, ActivityInfo.SCREEN_ORIENTATION_USER) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(app, true, 700)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(app, false, 700)) + } + + @Test fun modesKeepSeparateChoices() { + SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true) + assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "lxqt", panel, true)) + } + + @Test fun resettingSettingsClearsThePortraitChoice() { + SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true) + assertTrue(SettingsReset.isSessionSetting("displayResolution.portrait.steam")) + } + + @Test fun effectiveChoiceFollowsTheOtherOrientation() { + val d = SessionDisplay + assertEquals("900p", d.effectiveChoice("900p", d.LINK_LANDSCAPE, true)) + assertEquals("1600x720", d.effectiveChoice("1600x720", "1080p", false)) + assertEquals("720x1600", d.effectiveChoice("1600x720", d.LINK_LANDSCAPE, true)) + assertEquals("1600x720", d.effectiveChoice(d.LINK_PORTRAIT, "720x1600", false)) + assertEquals(d.DEFAULT_RESOLUTION, d.effectiveChoice(d.LINK_PORTRAIT, d.LINK_LANDSCAPE, true)) + assertEquals("follow/2", d.effectiveChoice("follow/2", d.LINK_LANDSCAPE, true)) + assertEquals(d.MATCH_SCREEN, d.effectiveChoice(d.LINK_PORTRAIT, d.MATCH_SCREEN, false)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchRunnerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchRunnerTest.kt new file mode 100644 index 0000000000..d5f851a7f4 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchRunnerTest.kt @@ -0,0 +1,116 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class QueuedLaunchRunnerTest { + private class Clock { + var now = 0L + private class Task(val at: Long, val run: Runnable) + private val tasks = mutableListOf<Task>() + fun schedule(delay: Long, run: Runnable) { tasks += Task(now + delay, run) } + fun cancel(run: Runnable) { tasks.removeAll { it.run === run } } + /** Moves time forward and runs what is due, as the main thread would. */ + fun advance(ms: Long) { + val end = now + ms + while (true) { + val next = tasks.filter { it.at <= end }.minByOrNull { it.at } ?: break + tasks.remove(next) + now = maxOf(now, next.at) + next.run.run() + } + now = end + } + } + + private class Owner(clock: Clock, queue: QueuedLaunch<String>, val state: State) { + class State { var blocked = true; var busy = false } + val started = mutableListOf<String>() + val runner = QueuedLaunchRunner( + queue = queue, now = { clock.now }, blocked = { state.blocked }, busy = { state.busy }, + schedule = clock::schedule, unschedule = clock::cancel, start = { started += it }, retryMs = 2_000, + ) + } + + private val minute = 60_000L + + @Test fun aLaunchWaitsWhileTheSettingBlocksItAndStartsOnceItDoesNot() { + val clock = Clock() + val owner = Owner(clock, QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) }, Owner.State()) + owner.runner.poke() + clock.advance(5_000) + assertEquals(emptyList<String>(), owner.started) + owner.state.blocked = false + owner.runner.poke() + clock.advance(1) + assertEquals(listOf("steam"), owner.started) + } + + @Test fun aBusyRuntimeIsRetriedEveryTwoSecondsUntilItIsFree() { + val clock = Clock() + val state = Owner.State().apply { blocked = false; busy = true } + val owner = Owner(clock, QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + clock.advance(7_000) + assertEquals(emptyList<String>(), owner.started) + state.busy = false + clock.advance(2_001) + assertEquals(listOf("steam"), owner.started) + clock.advance(10_000) + assertEquals(listOf("steam"), owner.started) + } + + @Test fun aLaunchThatWaitsPastItsLifetimeIsNeverStarted() { + val clock = Clock() + val state = Owner.State().apply { blocked = false; busy = true } + val owner = Owner(clock, QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + clock.advance(16 * minute) + state.busy = false + clock.advance(10_000) + assertEquals(emptyList<String>(), owner.started) + } + + @Test fun onlyTheRestoredOwnerStartsAfterTheFirstOneIsDestroyedMidRetry() { + val clock = Clock() + val state = Owner.State().apply { blocked = false; busy = true } + val firstQueue = QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) } + val first = Owner(clock, firstQueue, state) + first.runner.poke() + clock.advance(3_000) + + val saved = firstQueue.launch + val savedAt = firstQueue.queuedAt + first.runner.destroy() + val secondQueue = QueuedLaunch<String>(15 * minute).also { it.restore(saved, savedAt, clock.now) } + val second = Owner(clock, secondQueue, state) + second.runner.poke() + + state.busy = false + clock.advance(10_000) + assertEquals(emptyList<String>(), first.started) + assertEquals(listOf("steam"), second.started) + assertNull(firstQueue.launch) + } + + @Test fun aDestroyedOwnerNeverStartsEvenIfItsRetryWasAlreadyDue() { + val clock = Clock() + val state = Owner.State().apply { blocked = false } + val owner = Owner(clock, QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + owner.runner.destroy() + clock.advance(10_000) + assertEquals(emptyList<String>(), owner.started) + } + + @Test fun pokingTwiceBeforeTheFirstAttemptStartsTheLaunchOnce() { + val clock = Clock() + val state = Owner.State().apply { blocked = false } + val owner = Owner(clock, QueuedLaunch<String>(15 * minute).also { it.queue("steam", 0) }, state) + owner.runner.poke() + owner.runner.poke() + clock.advance(1) + assertEquals(listOf("steam"), owner.started) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchTest.kt b/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchTest.kt new file mode 100644 index 0000000000..60fbb430eb --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/QueuedLaunchTest.kt @@ -0,0 +1,49 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Test + +class QueuedLaunchTest { + private val minute = 60_000L + + @Test fun aQueuedLaunchIsWantedUntilItsLifetimeEnds() { + val queue = QueuedLaunch<String>(15 * minute) + queue.queue("steam", now = 100) + assertEquals("steam", queue.current(100 + 14 * minute)) + assertNull(queue.current(100 + 16 * minute)) + assertNull(queue.launch) + } + + @Test fun aRestoredLaunchKeepsTheTimeItWasQueued() { + val queue = QueuedLaunch<String>(15 * minute) + queue.restore("steam", queuedAt = 0, now = 14 * minute) + assertEquals("steam", queue.current(14 * minute)) + assertEquals(0L, queue.queuedAt) + assertNull(queue.current(16 * minute)) + } + + @Test fun aLaunchRestoredAfterItsLifetimeIsDropped() { + val queue = QueuedLaunch<String>(15 * minute) + queue.restore("steam", queuedAt = 0, now = 20 * minute) + assertNull(queue.launch) + } + + @Test fun aLaunchRestoredWithoutAValidTimeIsDropped() { + val queue = QueuedLaunch<String>(15 * minute) + queue.restore("steam", queuedAt = 0, now = -1) + assertNull(queue.launch) + queue.restore(null, queuedAt = 5, now = 10) + assertNull(queue.launch) + } + + @Test fun clearingForgetsTheLaunchSoAnOldCallbackDoesNotMatchIt() { + val queue = QueuedLaunch<Any>(15 * minute) + val launch = Any() + queue.queue(launch, now = 0) + assertSame(launch, queue.current(1)) + queue.clear() + assertNull(queue.current(1)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionBackgroundPrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionBackgroundPrefsTest.kt index f7ba39b65f..b1dcbc4e4a 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionBackgroundPrefsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionBackgroundPrefsTest.kt @@ -29,6 +29,16 @@ class SessionBackgroundPrefsTest { } } + @Test fun steamAndQuickAccessFallsBackToAutoOutsideSteam() { + SessionPrefs.setOscMode(context, SessionPrefs.OSC_STEAM_QAM) + assertEquals(SessionPrefs.OSC_AUTO, SessionPrefs.oscMode(context, steamSession = false)) + assertEquals(SessionPrefs.OSC_STEAM_QAM, SessionPrefs.oscMode(context)) + assertEquals(SessionPrefs.OSC_STEAM_QAM, SessionPrefs.oscMode(context, steamSession = true)) + + SessionPrefs.setOscMode(context, SessionPrefs.OSC_ALWAYS) + assertEquals(SessionPrefs.OSC_ALWAYS, SessionPrefs.oscMode(context, steamSession = false)) + } + @Test fun automaticPipDefaultsOnAndHonorsSavedChoices() { assertEquals(true, SessionPrefs.pipAutoEnter(context)) SessionPrefs.setPipAutoEnter(context, false) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt index 1835b6b85d..f8dd6e34e2 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt @@ -55,6 +55,11 @@ class SessionDisplayTest { @Test fun unfoldedControlsKeepTheGameSixteenByNineAcrossTheWidth() { assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920)) + assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920, 0, 16f / 9f)) + assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920, 0, 2.2f)) + assertEquals(1080, SessionDisplay.unfoldedGameHeight(1440, 3039, 192, 4f / 3f)) + assertEquals(1080, SessionDisplay.unfoldedGameHeight(1440, 3039, 0, 4f / 3f)) + assertEquals(2430, SessionDisplay.unfoldedGameHeight(1440, 3039, 0, 0.5f)) assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848)) assertEquals(1038, SessionDisplay.unfoldedGameHeight(1848, 2448)) assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt index 3b996ae3d2..89baf52834 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt @@ -63,6 +63,70 @@ class SessionSteamLogsTest { assertFalse(File(out, "web.txt").readText().contains("abcdef123456")) } + private fun rpcs3Root(): Pair<File, File> { + val root = tmp.newFolder("rootfs") + return root to File(root, "root/.cache/rpcs3").apply { mkdirs() } + } + + @Test fun rpcs3LogRewrittenThisSessionIsCollectedAloneAndRedacted() { + val (root, logs) = rpcs3Root() + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + File(logs, "RPCS3.log").writeText("earlier run\n") + File(logs, "RPCS3.log.gz").writeBytes(byteArrayOf(0x1f, 0x8b.toByte(), 8, 0)) + File(logs, "RPCS3.buf").writeText("lock\n") + SessionArtifacts.markRpcs3Log(session, root) + + File(logs, "RPCS3.log").writeText("PPU: compiling\nGET /x?sessionid=abcdef123456 200\n") + File(logs, "RPCS3.log.gz").appendBytes(byteArrayOf(1, 2, 3)) + File(logs, "RPCS3.buf").appendText("more\n") + + val copied = SessionArtifacts.copyRpcs3Log(logs, session, out) + assertEquals(listOf("RPCS3.log"), names(copied)) + val text = File(out, "RPCS3.log").readText() + assertTrue(text.startsWith("PPU: compiling\n")) + assertFalse(text.contains("abcdef123456")) + assertEquals(listOf("RPCS3.log"), out.list()!!.sorted()) + } + + @Test fun rpcs3LogFirstWrittenThisSessionIsCollected() { + val (root, logs) = rpcs3Root() + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + SessionArtifacts.markRpcs3Log(session, root) + + File(logs, "RPCS3.log").writeText("first boot\n") + + assertEquals(listOf("RPCS3.log"), names(SessionArtifacts.copyRpcs3Log(logs, session, out))) + assertEquals("first boot\n", File(out, "RPCS3.log").readText()) + } + + @Test fun anRpcs3LogFromAnEarlierSessionIsNotCollected() { + val (root, logs) = rpcs3Root() + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + File(logs, "RPCS3.log").writeText("earlier run\n") + SessionArtifacts.markRpcs3Log(session, root) + + assertTrue(SessionArtifacts.copyRpcs3Log(logs, session, out).isEmpty()) + assertFalse(out.exists()) + } + + @Test fun anUnmarkedSessionCollectsNoRpcs3LogEvenWithSteamMarks() { + val (_, logs) = rpcs3Root() + val steam = tmp.newFolder("steam-logs") + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + File(steam, "console_log.txt").writeText("steam\n") + SessionArtifacts.markSteamLogs(session, steam) + File(logs, "RPCS3.log").writeText("another session's run\n") + + assertTrue(SessionArtifacts.copyRpcs3Log(logs, session, out).isEmpty()) + assertFalse(out.exists()) + File(steam, "console_log.txt").appendText("new\n") + assertEquals(listOf("console_log.txt"), names(SessionArtifacts.copySessionLogs(steam, session, tmp.newFolder("out")))) + } + @Test fun aCopyFailurePreservesThePreviousSnapshotAndRemovesPartialStaging() { val logs = tmp.newFolder("logs") val session = tmp.newFolder("session") diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt new file mode 100644 index 0000000000..7b73b81e91 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamClientPrefetchTest.kt @@ -0,0 +1,22 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class SteamClientPrefetchTest { + @Test fun readsPercentAndTotalFromTheInstallersStepLine() { + val line = "== STEP 14:21:07 downloading Steam: bins_linuxarm64.zip (2/5), 120 of 480 MB" + assertEquals(25 to 480, SteamClientPrefetch.parse(line)) + } + + @Test fun aRetryNoteDoesNotChangeTheReading() { + val line = "== STEP 14:21:07 downloading Steam: x.zip (1/3), 10 of 40 MB - retrying in 5s" + assertEquals(25 to 40, SteamClientPrefetch.parse(line)) + } + + @Test fun otherLinesAreIgnored() { + assertNull(SteamClientPrefetch.parse("== STEP 14:21:07 the Steam client now follows steamdeck_stable")) + assertNull(SteamClientPrefetch.parse("downloading Steam: x (1/1), 5 of 0 MB")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt index ae9b31d80c..5e68b5fee9 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt @@ -88,4 +88,17 @@ class SteamGameProcessTest { process("301", "reaper", "SteamLaunch", "AppId=351710", "--", "proton", "waitforexitandrun", "game.exe") assertTrue(SteamGameProcess.running("351710", proc)) } + + @Test fun onlyTheRunningCurrentGameCountsAsAlreadyRunning() { + val proc = tmp.newFolder("proc-relaunch") + File(proc, "200").apply { mkdirs() }.resolve("cmdline") + .writeBytes(cmdline("reaper", "SteamLaunch", "AppId=584400", "--", "proton", "waitforexitandrun", "SonicMania.exe")) + assertTrue(SteamGameProcess.alreadyRunning("584400", "584400", proc)) + assertFalse(SteamGameProcess.alreadyRunning("584400", "311340", proc)) + assertFalse(SteamGameProcess.alreadyRunning("311340", "311340", proc)) + assertFalse(SteamGameProcess.alreadyRunning("584400", null, proc)) + val shortcutId = ((584400uL shl 32) or 0x02000000uL).toString() + assertTrue(SteamGameProcess.alreadyRunning(shortcutId, "584400", proc)) + assertTrue(SteamGameProcess.alreadyRunning("584400", shortcutId, proc)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt index 468b5728f8..9d5d76fa92 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamUserDefaultsTest.kt @@ -59,6 +59,27 @@ class SteamUserDefaultsTest { assertFalse(File(home, "userdata/123/config/droiddeck-user-defaults-initialized").exists()) } + @Test fun libraryHomeUsesBigArtUnlessChosenOtherwise() { + val fresh = home("") + SessionFiles.seedUserDefaults(fresh) + assertTrue(text(fresh).contains("\"LibraryHomeBigArt\"\t\t\"1\"")) + val chosen = home("\t\"LibraryHomeBigArt\"\t\t\"0\"\n") + SessionFiles.seedUserDefaults(chosen) + assertTrue(text(chosen).contains("\"LibraryHomeBigArt\"\t\t\"0\"")) + assertEquals(1, Regex("LibraryHomeBigArt").findAll(text(chosen)).count()) + } + + @Test fun bigArtLandsInTheRootWhenNestedStoresCloseOnItsLastLine() { + val home = home("") + File(home, "userdata/123/config/localconfig.vdf").writeText( + "\"UserLocalConfigStore\"\n{\n\t\"WebStorage\"\n\t{\n\t\t\"Other\"\t\t\"x\"\n\t}}\n") + SessionFiles.seedUserDefaults(home) + val t = text(home) + val beforeBigArt = t.substring(0, t.indexOf("\"LibraryHomeBigArt\"")) + assertEquals(beforeBigArt.count { it == '{' }, beforeBigArt.count { it == '}' } + 1) + assertTrue(t.indexOf("\"CachedBatteryPreferences\"") < t.indexOf("\"LibraryHomeBigArt\"")) + } + @Test fun librarySortsByRecentlyPlayed() { val fresh = home("") SessionFiles.seedUserDefaults(fresh) diff --git a/app/src/test/java/com/droiddeck/launcher/session/TestJvmUncaughtHandler.kt b/app/src/test/java/com/droiddeck/launcher/session/TestJvmUncaughtHandler.kt new file mode 100644 index 0000000000..c95873aa2d --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/TestJvmUncaughtHandler.kt @@ -0,0 +1,16 @@ +package com.droiddeck.launcher.session + +import org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin + +/** + * A plain JVM has no default uncaught-exception handler, so CrashHandler's fallback halts the test JVM (exit 2) + * on any background-thread error. Each test starts from a handler that only prints, like the JVM's own. + */ +class TestJvmUncaughtHandler : TestEnvironmentLifecyclePlugin { + override fun onSetupApplicationState() { + Thread.setDefaultUncaughtExceptionHandler { thread, error -> + System.err.print("Exception in thread \"${thread.name}\" ") + error.printStackTrace(System.err) + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt b/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt deleted file mode 100644 index ac0ec06843..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.ComponentCallbacks2 -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class TopUnderPressureTest { - @Test - fun onlyRunningLevelsCountAsPressure() { - assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL)) - assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW)) - assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE)) - assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN)) - } - - @Test - fun reclaimsOnlyDuringASessionShortlyAfterPressure() { - assertTrue(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(20_000, 9_500, sessionRunning = true, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(10_000, 0, sessionRunning = true, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = false, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = true)) - } -} diff --git a/app/src/test/java/com/droiddeck/launcher/session/UncaughtBackgroundErrorTest.kt b/app/src/test/java/com/droiddeck/launcher/session/UncaughtBackgroundErrorTest.kt new file mode 100644 index 0000000000..d1409cce25 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/UncaughtBackgroundErrorTest.kt @@ -0,0 +1,21 @@ +package com.droiddeck.launcher.session + +import com.droiddeck.launcher.App +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class UncaughtBackgroundErrorTest { + @Test fun anUncaughtErrorOnABackgroundThreadDoesNotEndTheTestRun() { + assertTrue(RuntimeEnvironment.getApplication() is App) + Thread({ throw IllegalStateException("expected by the test") }, "uncaught-background-error").apply { + start() + join() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/CloudPlanTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/CloudPlanTest.kt index 1979bece2b..c2ef81ac04 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/CloudPlanTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/CloudPlanTest.kt @@ -48,6 +48,15 @@ class CloudPlanTest { assertEquals(listOf("s"), CloudPlan.up(mapOf("s" to Local("c")), mapOf("s" to Remote("c", 9000)), base).same) } + @Test fun aSaveDeletedInTheCloudGoesUpOnlyOnceItChangesLocally() { + val base = mapOf("s" to Entry("a", "a", 1000), "t" to Entry("x", "x", 1000)) + val gone = setOf("s") + val idle = CloudPlan.up(mapOf("s" to Local("a"), "t" to Local("y"), "n" to Local("new")), mapOf("t" to Remote("x", 1000)), base, gone) + assertEquals(setOf("t", "n"), idle.transfer.toSet()) + assertEquals(listOf("s"), CloudPlan.up(mapOf("s" to Local("b")), emptyMap(), base, gone).transfer) + assertEquals(listOf("s"), CloudPlan.up(mapOf("s" to Local("a")), emptyMap(), base).transfer) + } + @Test fun timesAloneDecideWhenTheServiceGivesNoHash() { val base = mapOf("s" to Entry("a", null, 1000)) assertEquals(listOf("s"), CloudPlan.down(mapOf("s" to Local("a")), mapOf("s" to Remote(null, 60_000)), base).transfer) diff --git a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt index f3944a8034..c2decf0879 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt @@ -25,7 +25,9 @@ class CloudSavesTest { val puts = ArrayList<String>() var onGet: (CloudFile) -> Unit = {} var raceAfter = Int.MAX_VALUE - override fun list() = files.map { (k, v) -> CloudFile(k, v.second, CloudSaves.md5(v.first)) } + val gone = HashSet<String>() + override fun deleted(file: CloudFile) = file.md5 == GOG_DELETED_MD5 + override fun list() = files.map { (k, v) -> CloudFile(k, v.second, CloudSaves.md5(v.first)) } + gone.map { CloudFile(it, 5000L, GOG_DELETED_MD5) } override fun get(file: CloudFile) = files.getValue(file.name).also { onGet(file) } override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> { val sent = LinkedHashMap<String, Long>() @@ -40,6 +42,40 @@ class CloudSavesTest { private fun dir() = File(app.filesDir, "saves-${System.nanoTime()}").apply { mkdirs() } private val id get() = "g${System.nanoTime()}" + @Test fun savesTheCloudMarksDeletedAreNotDownloaded() { + val dir = dir() + val cloud = Memory().apply { + files["save1.ess"] = "kept".toByteArray() to 1000L + gone += listOf("save2.ess", "save3.ess", "save3.skse") + } + val r = CloudSaves.downWith(app, Store.GOG, id, dir, cloud, force = true) + assertEquals("ok", r.result); assertEquals(1, r.files) + assertEquals(listOf("save1.ess"), dir.list()!!.sorted()) + } + + @Test fun aLocalSaveTheCloudMarksDeletedIsLeftAlone() { + val dir = dir(); File(dir, "save2.ess").writeText("mine") + val cloud = Memory().apply { files["save1.ess"] = "kept".toByteArray() to 1000L; gone += "save2.ess" } + assertEquals("ok", CloudSaves.downWith(app, Store.GOG, id, dir, cloud, force = false).result) + assertEquals("mine", File(dir, "save2.ess").readText()) + assertEquals("kept", File(dir, "save1.ess").readText()) + } + + @Test fun anUnchangedSaveDeletedInTheCloudIsNotSentBackButANewerOneIs() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["save1.ess"] = "a".toByteArray() to 1000L; files["save2.ess"] = "b".toByteArray() to 1000L } + assertEquals("ok", CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false).result) + cloud.files.remove("save2.ess"); cloud.gone += "save2.ess" + val idle = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals("up-to-date", idle.reason) + assertTrue(cloud.puts.isEmpty()) + File(dir, "save2.ess").writeText("b played again") + val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals(listOf("save2.ess"), cloud.puts) + assertEquals("b played again", String(cloud.files.getValue("save2.ess").first)) + assertEquals(1, r.files) + } + @Test fun anUploadBeforeAnyDownloadIsRefused() { val dir = dir(); File(dir, "slot0.sav").writeText("fresh profile") val cloud = Memory().apply { files["slot0.sav"] = "real save".toByteArray() to 1000L } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt index d6667e2a12..554948f49e 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/GogCloudKeysTest.kt @@ -8,7 +8,12 @@ import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) class GogCloudKeysTest { @Test fun defaultLocationIsStrippedLikeAnyNamedLocation() { val files = listOf(CloudFile("__default/savegame0.sav", 1L), CloudFile("saves/slot0.sav", 2L)) @@ -183,6 +188,24 @@ class GogCloudKeysTest { requests.forEach { assertEquals("Bearer token", it.headers["authorization"]) } } + @Test fun listAsksForJsonAndCarriesGalaxyDeletionMarks() { + val body = "[{\"name\":\"saves/save1.ess\",\"hash\":\"0123456789abcdef0123456789abcdef\",\"last_modified\":\"2026-11-17T22:58:55.038000+00:00\"}," + + "{\"name\":\"saves/save2.ess\",\"hash\":\"$GOG_DELETED_MD5\",\"last_modified\":\"2026-11-17T22:59:00+00:00\"}]" + lateinit var files: List<CloudFile> + lateinit var cloud: GogCloud + val requests = serve(1, { "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${body.length}\r\nConnection: close\r\n\r\n$body" }) { url -> + cloud = GogCloud("user", "client", "token", "saves", url) + files = cloud.list() + } + assertEquals("application/json", requests.single().headers["accept"]) + assertEquals(listOf("save1.ess", "save2.ess"), files.map { it.name }) + assertEquals("0123456789abcdef0123456789abcdef", files[0].md5) + assertEquals(1_794_956_335_038L, files[0].modifiedMs) + assertFalse(cloud.deleted(files[0])) + assertTrue(cloud.deleted(files[1])) + assertFalse(cloud.deleted(CloudFile("save3.ess", 1L))) + } + @Test fun rejectedListKeepsTheServerErrorInTheDetail() { val body = "{\"error\":\"invalid_version\",\"error_description\":\"not supported with this version\"}" val failure = runCatching { diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt index b4217895c2..cfde73c1d2 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt @@ -117,9 +117,9 @@ class StoreGameSidecarTest { val text = StoreLaunch.launcherText(sample.copy(exe = "Binaries/Win64/Celeste.exe")) assertTrue(text.contains("cd /d \"%~dp0Binaries\\Win64\"\r\n")) assertTrue(text.contains("set \"FOO=bar\"\r\n")) - assertTrue(text.contains("\r\n\"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\"\r\n")) + assertTrue(text.contains("\r\n%DD_P% \"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\" %*\r\n")) assertTrue(text.contains("set /p DD_X=<\"%~dp0.droiddeck-epic-code\"")) - assertTrue(text.contains("set \"DD_X=\" & \"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\" -AUTH_LOGIN=unused -AUTH_PASSWORD=%DD_X% -AUTH_TYPE=exchangecode\r\n")) + assertTrue(text.contains("set \"DD_X=\" & %DD_P% \"%~dp0Binaries\\Win64\\Celeste.exe\" -EpicPortal -epicusername=\"Some One\" -AUTH_LOGIN=unused -AUTH_PASSWORD=%DD_X% -AUTH_TYPE=exchangecode %*\r\n")) assertFalse(text.contains("AUTH=")) assertFalse(text.contains("DD_AUTH")) } @@ -157,11 +157,38 @@ class StoreGameSidecarTest { "set /p DD_A=<\"%~dp0.droiddeck-epic-args\"", "del \"%~dp0.droiddeck-epic-args\"", "if exist \"%~dp0.droiddeck-epic-code\" del \"%~dp0.droiddeck-epic-code\"", - "set \"DD_A=\" & \"%~dp0Binaries\\Win64\\Celeste.exe\" %DD_A%", + "set \"DD_A=\" & %DD_P% \"%~dp0Binaries\\Win64\\Celeste.exe\" %DD_A% %*", ), lines.subList(client + 1, client + 6), ) - assertTrue(text.endsWith("%DD_A%\r\n")) + assertTrue(text.endsWith("%DD_A% %*\r\n")) + } + + private val parentLines = listOf( + "if \"%DD_EPIC_PARENT%\"==\"1\" set \"DD_P=1\"", + "if \"%DD_EPIC_PARENT%\"==\"0\" set \"DD_P=\"", + "if defined DD_P set \"SteamAppId=\"", + "if defined DD_P if not exist \"Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\" set \"DD_P=\"", + "if defined DD_P set DD_P=\"Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\"", + ) + + @Test fun epicTitlesThatCheckTheirParentStartUnderTheStandIn() { + for (id in listOf("9d2d0eb64d5c44529cece33fe2a46482", "8769e24080ea413b8ebca3f1b8c50951", "Heather")) { + val lines = StoreLaunch.launcherText(StoreGameSidecar(Store.EPIC, id, "Rockstar title", "PlayGTAV.exe")).split("\r\n") + val on = lines.indexOf("set \"DD_P=1\"") + assertTrue(id, on > lines.indexOf("cd /d \"%~dp0\"")) + assertEquals(parentLines, lines.subList(on + 1, on + 6)) + assertEquals("if exist \"%~dp0.droiddeck-epic-args\" goto client", lines[on + 6]) + assertEquals(3, lines.count { it.contains("%DD_P% \"%~dp0PlayGTAV.exe\"") }) + } + } + + @Test fun otherEpicGamesUseTheStandInOnlyWhenTheirEnvironmentAsksForIt() { + val lines = StoreLaunch.launcherText(sample).split("\r\n") + val off = lines.indexOf("set \"DD_P=\"") + assertTrue(off > 0) + assertFalse(lines.contains("set \"DD_P=1\"")) + assertEquals(parentLines, lines.subList(off + 1, off + 6)) } @Test fun gogLauncherHasNoEpicBlockAndIsOnlyWrittenWhenNeeded() { diff --git a/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt index f1141a8715..2da34d3db4 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/battlenet/BattleNetRequestTest.kt @@ -31,8 +31,7 @@ class BattleNetRequestTest { BattleNetClient.request(root, listOf("launch", "WTCG")) java.io.File(root, "battlenet-request").writeText("launch\nPro\n") java.io.File(root, "battlenet-request.1.tmp").writeText("launch\nPro\n") - java.io.File(root, "battlenet-fex.request").writeText("x") BattleNetClient.clearRequests(root) - assertEquals(listOf("battlenet-fex.request"), root.list()!!.toList()) + assertEquals(0, root.list()!!.size) } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicLoginTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicLoginTest.kt new file mode 100644 index 0000000000..c5e9ab63fc --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicLoginTest.kt @@ -0,0 +1,51 @@ +package com.droiddeck.launcher.stores.epic + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class EpicLoginTest { + private fun innerText(body: String): String = JSONObject.quote(body) + + private fun corrective(action: String) = + """{"errorCode":"errors.com.epicgames.oauth.corrective_action_required","metadata":{"correctiveAction":"$action"}}""" + + private fun epicLogin() = EpicLogin("https://www.epicgames.com/id/authorize", "test-agent", "http://127.0.0.1/launcher/authorized") + + @Test fun aRedirectPageAskingForTermsIsACorrectiveAction() { + assertEquals("PRIVACY_POLICY_ACCEPTANCE", EpicLogin.correctiveAction(innerText(corrective("PRIVACY_POLICY_ACCEPTANCE")))) + assertEquals("EULA_ACCEPTANCE", EpicLogin.correctiveAction(innerText(corrective("EULA_ACCEPTANCE")))) + assertEquals("EULA_ACCEPTANCE", EpicLogin.correctiveAction(corrective("EULA_ACCEPTANCE"))) + assertEquals(EpicLogin.ACCOUNT_SIGN_IN_URL, epicLogin().browserStep(innerText(corrective("EULA_ACCEPTANCE")))) + } + + @Test fun aCorrectiveActionWithoutItsNameStillSelectsTheBrowserStep() { + val body = """{"errorCode":"errors.com.epicgames.oauth.corrective_action_required"}""" + assertEquals("unknown", EpicLogin.correctiveAction(innerText(body))) + assertEquals(EpicLogin.ACCOUNT_SIGN_IN_URL, epicLogin().browserStep(innerText(body))) + } + + @Test fun anAuthorizationCodeOrAnotherErrorStaysInTheSignInPage() { + val pages = listOf( + innerText("""{"warning":"Do not share this code with any 3rd party service.","redirectUrl":"https://localhost/launcher/authorized?code=c1","authorizationCode":"c1","sid":null}"""), + innerText("""{"errorCode":"errors.com.epicgames.common.authentication.authentication_failed","message":"Sorry"}"""), + innerText("Sign in"), + "null", + "", + ) + for (page in pages) { + assertNull(page, EpicLogin.correctiveAction(page)) + assertNull(page, epicLogin().browserStep(page)) + } + } + + @Test fun otherSignInFlowsHaveNoBrowserStep() { + val url = "https://www.epicgames.com/id/authorize?client_id=c85f4c6238b04d3399bc0080e83b83fd&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A41234%2Flauncher%2Fauthorized&state=x" + val flow = EpicClient.loginFlow(url, "test-browser")!! + assertNull(flow.browserStep(innerText(corrective("EULA_ACCEPTANCE")))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt index c98c1da30e..bad390d94e 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogMaintenanceTest.kt @@ -291,6 +291,58 @@ class GogMaintenanceTest { assertEquals("patch_(52404)+special.exe", GogContent.downloadFilename("https://example.invalid/patch_%2852404%29+special.exe?token=temporary")) } + private fun overlaySnapshot(base: JSONArray, dlc: JSONArray, owned: Set<String> = setOf("2")): GogInstallRecord { + val manifest = JSONObject().put("depots", JSONArray().put(JSONObject().put("productId", "1") + .put("languages", JSONArray().put("*")).put("files", base).put("items", base)).put(JSONObject().put("productId", "2") + .put("languages", JSONArray().put("*")).put("files", dlc).put("items", dlc))) + return GogContent.snapshot(GogInstallRecord("1", "depot"), GogBuild("build", "", 2, "", "https://example.invalid/manifest"), + "unused", ownership = { owned }, metadata = { _, _ -> manifest }) + } + + @Test fun generationTwoOwnedDepotOverlaysReplaceExactPathsBeforeValidation() { + val fixture = JSONObject(javaClass.classLoader!!.getResource("gog/gen2-overlay-excerpt.json")!!.readText()) + val base = fixture.getJSONArray("base") + val dlc = fixture.getJSONArray("dlc") + base.put(JSONObject().put("path", "unique.bin").put("type", "DepotFile").put("chunks", JSONArray())) + val snapshot = overlaySnapshot(base, dlc) + assertEquals(3, snapshot.files.length()) + assertEquals(listOf("gog.dat", "gog.idx", "unique.bin"), snapshot.files.objects().map { it.getString("path") }) + for (i in 0..1) { + val file = snapshot.files.getJSONObject(i) + assertEquals("2", file.getString("product")) + assertEquals(dlc.getJSONObject(i).getJSONArray("chunks").toString(), file.getJSONArray("chunks").toString()) + assertEquals(dlc.getJSONObject(i).getJSONArray("chunks").getJSONObject(0).getLong("size"), file.getLong("size")) + } + assertEquals("1", snapshot.files.getJSONObject(2).getString("product")) + GogFiles.validate(snapshot.files, temporary.newFolder()) + val baseOnly = overlaySnapshot(base, dlc, emptySet()) + assertEquals(base.getJSONObject(0).getJSONArray("chunks").toString(), baseOnly.files.getJSONObject(0).getJSONArray("chunks").toString()) + assertTrue(baseOnly.files.objects().all { it.getString("product") == "1" }) + GogFiles.validate(baseOnly.files, temporary.newFolder()) + } + + @Test fun overlaysDoNotHideCaseAliasesTraversalLinksOrPathTypeChanges() { + fun entry(path: String, type: String = "DepotFile") = JSONObject().put("path", path).put("type", type) + for (path in listOf("game.bin", "../Game.bin", "Data/../Game.bin", ".droiddeck-store.json")) { + val snapshot = overlaySnapshot(JSONArray().put(entry("Game.bin")), JSONArray().put(entry(path))) + assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(snapshot.files, temporary.newFolder()) } + } + assertThrows(IllegalArgumentException::class.java) { + overlaySnapshot(JSONArray().put(entry("Game.bin")), JSONArray().put(entry("Game.bin", "DepotDirectory"))) + } + assertThrows(IllegalStateException::class.java) { + overlaySnapshot(JSONArray().put(entry("Game.bin")), JSONArray().put(entry("Game.bin", "DepotLink"))) + } + val identical = JSONArray().put(entry("Game.bin")) + assertEquals(1, overlaySnapshot(identical, identical).files.length()) + val directories = JSONArray().put(entry("Data", "DepotDirectory")) + val merged = overlaySnapshot(directories, JSONArray().put(entry("Data", "DepotDirectory")).put(entry("Data/game.bin"))) + assertEquals(2, merged.files.length()) + GogFiles.validate(merged.files, temporary.newFolder()) + val aliases = overlaySnapshot(JSONArray().put(entry("Data/a")), JSONArray().put(entry("data/b"))) + assertThrows(IllegalArgumentException::class.java) { GogFiles.validate(aliases.files, temporary.newFolder()) } + } + @Test fun pathsRejectTraversalSymlinksCaseCollisionsAndMetadataOverlap() { val folder = temporary.newFolder() for (path in listOf("../escape", "/absolute", "C:/file", "a/./file", "a//file")) { diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt index d23072471a..cb0a7bf0cc 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt @@ -87,6 +87,34 @@ class XboxManifestTest { assertEquals(listOf("Retail.exe"), info.executables) assertEquals("Retail.exe", XboxManifest.executable(root)) } + @Test fun aGameCorePackageIsReadFromItsConfigBesideTheGeneratedAppxManifest() { + val root = temporary.newFolder() + java.io.File(root, "Game.exe").writeText("encrypted") + java.io.File(root, "Other.exe").writeText("encrypted") + java.io.File(root, "MicrosoftGame.config").writeText("""<Game configVersion="1"><Identity Name="Test.Game" Publisher="CN=Test" Version="1.2.3.0"/> + <ExecutableList><Executable Name="Game.exe" TargetDeviceFamily="PC"/></ExecutableList><StoreId>9AAAAAAAAAAA</StoreId></Game>""") + java.io.File(root, "appxmanifest.xml").writeText("""<?xml version="1.0" encoding="utf-8"?> + <Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"> + <Identity Name="Generated.Game" Publisher="CN=Generated" Version="9.9.9.0"/> + <Applications><Application Id="Game" Executable="Other.exe" EntryPoint="Game.App"/></Applications></Package>""") + val info = XboxManifest.read(root) + assertEquals("Test.Game", info.name) + assertEquals("1.2.3.0", info.version) + assertEquals("9AAAAAAAAAAA", info.storeId) + assertEquals("Game.exe", XboxInstaller.executable(root)) + assertFalse(XboxManifest.needsAppModel(root)) + } + @Test fun aFolderWithoutOneManifestIsStillRefused() { + val empty = temporary.newFolder() + java.io.File(empty, "Game.exe").writeText("encrypted") + assertThrows(IllegalArgumentException::class.java) { XboxManifest.read(empty) } + val twice = temporary.newFolder() + java.io.File(twice, "Game.exe").writeText("encrypted") + java.io.File(twice, "MicrosoftGame.config").writeText("<Game><Executable Name=\"Game.exe\"/></Game>") + java.io.File(twice, "microsoftgame.CONFIG").writeText("<Game><Executable Name=\"Game.exe\"/></Game>") + org.junit.Assume.assumeTrue(twice.list().orEmpty().size == 3) + assertThrows(IllegalArgumentException::class.java) { XboxManifest.read(twice) } + } @Test fun legacyPackageManifestNamesItsExecutableTheSameWay() { // A legacy EAppx package carries AppxManifest.xml and has no config; the // launcher must still find the identity and the launch path, or an install diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt new file mode 100644 index 0000000000..20ccd9c069 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt @@ -0,0 +1,94 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.WowAddonCatalog +import com.droiddeck.launcher.runtime.WowAddons +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class) +class AddonRowTest { + @get:Rule val compose = createRobolectricComposeRule() + + private val addon = WowAddonCatalog.Addon("298842", "Leatrix Maps", "Leatrix", "", 0, 0, null) + private fun text(id: Int) = RuntimeEnvironment.getApplication().getString(id) + + private fun show(status: AddonStatus, uninstalls: MutableList<String> = mutableListOf(), installs: MutableList<String> = mutableListOf()) { + val state = mutableStateOf(status) + compose.setContent { + DroidDeckTheme { + AddonRow(addon, state.value, null, Modifier, { uninstalls += addon.id }) { installs += addon.id } + } + } + } + + @Test fun aMissingAddonOffersOnlyInstall() { + val installs = mutableListOf<String>() + show(AddonStatus.INSTALL, installs = installs) + compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(0) + compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0) + compose.onNodeWithText(text(R.string.store_install)).performClick() + assertEquals(listOf("298842"), installs) + } + + @Test fun aCurrentAddonOffersOnlyUninstallAfterAConfirm() { + val uninstalls = mutableListOf<String>() + show(AddonStatus.INSTALLED, uninstalls) + compose.onAllNodesWithText(text(R.string.store_install)).assertCountEquals(0) + compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0) + compose.onAllNodesWithText(text(R.string.stores_installed_chip)).assertCountEquals(0) + compose.onNodeWithText(text(R.string.common_uninstall)).performClick() + assertEquals(emptyList<String>(), uninstalls) + compose.onAllNodesWithText(text(R.string.common_uninstall))[1].performClick() + assertEquals(listOf("298842"), uninstalls) + } + + @Test fun anOutdatedAddonOffersUpdateAndUninstall() { + val installs = mutableListOf<String>() + show(AddonStatus.UPDATE, installs = installs) + compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(1) + compose.onNodeWithText(text(R.string.common_update)).performClick() + assertEquals(listOf("298842"), installs) + } + + private fun disk(vararg addons: WowAddons.Installed) = addons.associateBy { it.name.lowercase() } + + @Test fun anotherSourcesAddonOnDiskIsUpdatableOnlyToANewerVersion() { + val onDisk = disk(WowAddons.Installed("Questie", "11.2.0", null), WowAddons.Installed("QuestieDB", null, null)) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "6.2.5", "1")) + assertEquals(AddonStatus.UPDATE, diskStatus(listOf("Questie"), onDisk, "11.3.0", "1")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "v11.2.0", "1")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("QuestieDB"), onDisk, "1.0", "1")) + } + + @Test fun anIncomparableVersionIsAnUpdateOnlyFromTheSameSource() { + val onDisk = disk(WowAddons.Installed("TomTom", "v4.0.1-release", "12")) + assertEquals(AddonStatus.UPDATE, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "12")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "99")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "4.0.0", "12")) + } + + @Test fun foldersOnDiskMatchWhateverTheirCase() { + val onDisk = disk(WowAddons.Installed("questie", "11.2.0", null)) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "11.2.0", "1")) + } + + @Test fun anAddonCountsAsInstalledOnlyWhenEveryFolderIsOnDisk() { + val onDisk = disk(WowAddons.Installed("Bartender4", "4.19.2", null)) + assertEquals(AddonStatus.INSTALL, diskStatus(listOf("Bartender4", "Bartender4_Options"), onDisk, "4.19.2", "1")) + assertEquals(AddonStatus.INSTALL, diskStatus(emptyList(), onDisk, "4.19.2", "1")) + assertEquals(AddonStatus.INSTALL, diskStatus(listOf("TomTom"), onDisk, "4.4.1", "1")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt new file mode 100644 index 0000000000..7fee7a4f87 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt @@ -0,0 +1,68 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.runtime.CurseForgeApp +import com.droiddeck.launcher.runtime.WowAddons +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class CurseLinkReportTest { + @get:Rule val temp = TemporaryFolder() + + private fun target(vararg folders: String): WowAddons.Target { + val addOns = temp.newFolder("AddOns") + folders.forEach { java.io.File(addOns, it).mkdirs() } + return WowAddons.Target("_retail_", addOns) + } + + private fun project(id: String, vararg folders: String, update: Boolean = false) = CurseForgeApp.Project(id, "m$id", folders.toList(), update) + + @Test fun beforeAnyReportNothingIsKnown() { + assertEquals(emptyMap<String, String?>(), CurseLink.lastReported(target("Questie"))) + } + + @Test fun beforeCurseForgeReportsAddonsWhoseFoldersAreAllOnDiskShowAsInstalled() { + val target = target("questie", "QuestieDB", "Auctionator") + CurseLink.report(target, listOf( + project("334372", "Questie", "QuestieDB", update = true), + project("1", "Auctionator"), + project("2", "Details", "Details_Streamer"), + project("3", "Auctionator", "Auctionator_Extra"), + )) + assertEquals(mapOf<String, String?>("334372" to null, "1" to null), CurseLink.lastReported(target)) + } + + @Test fun anAddonRemovedFromDiskSinceTheLastReportIsNotInstalled() { + val target = target("Questie") + CurseLink.report(target, listOf(project("334372", "Questie"))) + java.io.File(target.addOns, "Questie").delete() + assertEquals(emptyMap<String, String?>(), CurseLink.lastReported(target)) + } + + private fun toc(target: WowAddons.Target, folder: String, curseId: String) { + val dir = java.io.File(target.addOns, folder).apply { mkdirs() } + java.io.File(dir, "$folder.toc").writeText("## Interface: 110207\n## Title: $folder\n## X-Curse-Project-ID: $curseId\n$folder.lua\n") + } + + @Test fun beforeAnyReportAnAddonWhoseTocNamesTheProjectShowsAsInstalled() { + val target = target() + toc(target, "Questie", "334372") + toc(target, "Auctionator", "@project-id@") + assertEquals(mapOf<String, String?>("334372" to null), CurseLink.lastReported(target)) + } + + @Test fun aPlaceholderProjectIdIsIgnored() { + val target = target() + toc(target, "Auctionator", "@project-id@") + assertEquals(emptyMap<String, String?>(), CurseLink.lastReported(target)) + } + + @Test fun curseForgesReportOverridesTheTocProjectId() { + val target = target() + toc(target, "Questie", "334372") + toc(target, "Auctionator", "1") + CurseLink.report(target, listOf(project("1", "Auctionator", update = true))) + assertEquals(mapOf<String, String?>("1" to null), CurseLink.lastReported(target)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt new file mode 100644 index 0000000000..a64e56383f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -0,0 +1,335 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.onAllNodesWithContentDescription +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.AppImageManager +import com.droiddeck.launcher.runtime.CurseForgeApp +import com.droiddeck.launcher.runtime.UserApps +import com.droiddeck.launcher.runtime.WowAddonCatalog +import com.droiddeck.launcher.runtime.WowAddons +import com.droiddeck.launcher.session.SessionPrefs +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withContext +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.nio.file.LinkOption +import java.util.Collections + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class) +class CurseLinkTabTest { + @get:Rule val compose = createRobolectricComposeRule() + @get:Rule val temp = TemporaryFolder() + + private val original = CurseForgeApp.guest + private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED) + private val helper = Collections.synchronizedList(mutableListOf<String>()) + private val methods = Collections.synchronizedList(mutableListOf<String>()) + private val context get() = RuntimeEnvironment.getApplication() + + @After + fun restore() { + CurseForgeApp.guest = original + } + + private fun text(id: Int) = context.getString(id) + + private fun wow(): WowAddons.Target { + val games = temp.newFolder("Games") + val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() } + File(addOns, "Leatrix_Maps").mkdirs() + SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games")) + CurseForgeApp.guest = { _, argv, cancelled, onLine -> + if (argv[0] == CurseForgeApp.HELPER) { + helper += argv[1] + if (argv[1] == "start") { + onLine(url) + while (cancelled?.get() != true) Thread.sleep(10) + } + 0 + } else { + val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(argv[4])?.groupValues?.get(1) + method?.let { methods += it } + val answer: Any = when (method) { + "detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g") + "getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", "/root/Games/World of Warcraft/_retail_")) + "getProjects" -> JSONArray().put(JSONObject().put("id", "298842").put("installedModId", "m").put("status", 1).put("locked", false).put("folders", JSONArray().put("Leatrix_Maps"))) + else -> true + } + onLine(JSONObject().put("ok", true).put("value", JSONObject().put("value", answer).toString()).toString()) + 0 + } + } + return WowAddons.Target("_retail_", addOns) + } + + @Test + fun theTabAndItsDialogShareOneCurseForgeThatStopsWhenTheTabLeaves() { + val target = wow() + val shown = mutableStateOf(true) + val seen = Collections.synchronizedList(mutableListOf<List<String>>()) + var opened: CurseLink? = null + compose.setContent { + if (shown.value) { + val link = rememberCurseLink(app, sessionRunning = false) + opened = link + LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } } + LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } } + } + } + compose.waitUntil(20_000) { seen.size == 2 } + assertEquals(listOf(listOf("298842"), listOf("298842")), seen.toList()) + assertEquals(listOf("start"), helper.toList()) + assertEquals(1, methods.count { it == "scanGameInstance" }) + assertTrue(CurseLink.live() != null) + compose.runOnIdle { shown.value = false } + compose.waitForIdle() + compose.waitUntil(20_000) { "stop" in helper } + assertNull(CurseLink.live()) + assertTrue("shutdown" in methods) + assertEquals(1, helper.count { it == "start" }) + runBlocking { withTimeout(20_000) { opened!!.stopped.join() } } + compose.waitUntil(5_000) { Thread.getAllStackTraces().keys.none { it.isAlive && it.name.startsWith("curseforge") } } + val calls = helper.size + methods.size + Thread.sleep(1_500) + assertEquals(calls, helper.size + methods.size) + } + + @Test + fun aNewGenerationRescansButReusesTheRunningCurseForge() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + link.installed(context, target, 0) + link.refresh() + link.installed(context, target, link.generation) + assertEquals(2, methods.count { it == "scanGameInstance" }) + assertEquals(1, helper.count { it == "start" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun anInstallHandsCurseForgesSettledListToTheNextReadWithoutARescan() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") }) + assertEquals(listOf("298842"), link.installed(context, target, 1).map { it.id }) + assertEquals(1, methods.count { it == "scanGameInstance" }) + link.installed(context, target, 2) + assertEquals(2, methods.count { it == "scanGameInstance" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun aFailedInstallLeavesTheNextReadToRescan() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + assertFalse(link.change(context, target) { null }) + link.installed(context, target, 1) + assertEquals(2, methods.count { it == "scanGameInstance" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun aRefreshAfterAnInstallStillRescans() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") }) + link.refresh() + link.installed(context, target, 1) + assertEquals(2, methods.count { it == "scanGameInstance" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun aFailedChangeDropsAnEarlierSettledList() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") }) + assertFalse(link.change(context, target) { null }) + link.installed(context, target, 1) + assertEquals(2, methods.count { it == "scanGameInstance" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun anOlderChangeFinishingLastDoesNotReplaceTheNewerList() { + val target = wow() + tocFolder(target.addOns, "Older", "1") + tocFolder(target.addOns, "Newer", "2") + val older = CurseForgeApp.Project("1", "11", listOf("Older"), false) + val newer = CurseForgeApp.Project("2", "22", listOf("Newer"), false) + val link = CurseLink(app) + try { + link.installed(context, target, 0) + assertTrue(link.change(context, target) { + assertTrue(link.change(context, target) { listOf(older, newer) }) + listOf(older) + }) + assertEquals(setOf("1", "2"), CurseLink.lastReported(target).keys) + assertEquals(listOf("1", "2"), link.installed(context, target, 1).map { it.id }) + assertEquals(1, methods.count { it == "scanGameInstance" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun aFailedScanKeepsTheLastReportInsteadOfClearingIt() { + val target = wow() + val link = CurseLink(app) + try { + val reported = link.marks(context, target, 0) + assertTrue(reported.isNotEmpty()) + runBlocking { link.close(context).join() } + assertEquals(reported.mapValues { null }, link.marks(context, target, 1)) + } finally { + runBlocking { link.close(context).join() } + } + } + + private fun tocFolder(addOns: File, name: String, curseId: String) = + File(addOns, name).apply { mkdirs(); File(this, "$name.toc").writeText("## X-Curse-Project-ID: $curseId\n") } + + @Test + fun anAddonTheManagerDoesNotListIsFoundByItsTocProjectId() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + tocFolder(target.addOns, "Questie", "334372") + tocFolder(target.addOns, "Other", "1") + assertEquals(listOf("Questie"), curseFolders(target, "334372", emptyList())) + assertEquals(listOf("Listed"), curseFolders(target, "334372", listOf("Listed"))) + } + + @Test + fun uninstallingByTocProjectIdDeletesOnlyTheMatchedFolders() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + tocFolder(target.addOns, "Questie", "334372") + tocFolder(target.addOns, "Other", "1") + deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) + assertEquals(listOf("Other"), WowAddons.installed(target)) + } + + @Test + fun uninstallingALinkedAddonLeavesTheLinkTargetAlone() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + val outside = tocFolder(temp.newFolder("outside"), "Questie", "334372") + File(outside, "keep.lua").writeText("keep") + Files.createSymbolicLink(File(target.addOns, "Questie").toPath(), outside.toPath()) + deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) + assertFalse(Files.exists(File(target.addOns, "Questie").toPath(), LinkOption.NOFOLLOW_LINKS)) + assertEquals("keep", File(outside, "keep.lua").readText()) + assertTrue(File(outside, "Questie.toc").isFile) + } + + @Test + fun uninstallingWithNothingToDeleteFails() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + tocFolder(target.addOns, "Other", "1") + assertThrows(IOException::class.java) { deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) } + assertEquals(listOf("Other"), WowAddons.installed(target)) + } + + @Test + fun noCurseForgeStartsWhileASessionRuns() { + wow() + var link: CurseLink? = CurseLink(app) + compose.setContent { link = rememberCurseLink(app, sessionRunning = true) } + compose.waitForIdle() + assertNull(link) + assertTrue(helper.isEmpty()) + } + + @Test + fun aStaleEntryWhoseFolderIsGoneIsNotManaged() { + val target = wow() + assertTrue(File(target.addOns, "Leatrix_Maps").deleteRecursively()) + val link = CurseLink(app) + try { + assertTrue(link.installed(context, target, 0).isEmpty()) + } finally { + runBlocking { link.close(context).join() } + } + } + + private val actions = FrontEndActions( + onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, + onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, + onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, + onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, + + onSetPhantomProcessLimit = { _, _ -> }, + ) + + private fun row(update: Boolean?, wowi: Boolean) { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + val item = WowAddons.Installed("Leatrix_Maps", "1.60.35", null) + val newer = WowAddonCatalog.Addon("1", "Leatrix Maps", "Leatrix", "1.60.36", 0, 0, null).takeIf { wowi } + val curse = update?.let { CurseForgeApp.Project("298842", "m", listOf("Leatrix_Maps"), it) to CurseLink(app) } + compose.setContent { DroidDeckTheme { AddonRow(item, newer, target, actions, curse) } } + } + + @Test + fun aManagedRowWithAnUpdateOffersUpdateAndUninstall() { + row(update = true, wowi = false) + compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(0) + } + + @Test + fun aCurrentManagedRowIgnoresOtherSourcesAndOffersOnlyUninstall() { + row(update = false, wowi = true) + compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(0) + compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1) + } + + @Test + fun anUnmanagedRowKeepsTheLocalUpdateAndDelete() { + row(update = null, wowi = true) + compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(0) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt index 3f76cac3ba..641de899ac 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt @@ -87,7 +87,7 @@ class DesktopUninstallTest { onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = { removals++ }, ), Modifier.fillMaxSize(), onSelect = {}) StepsLayer(Offset.Zero) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt index a268c46a80..b685aac7ec 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt @@ -67,7 +67,7 @@ class FlathubFocusTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, )) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt index a86bf350f8..97d1d95094 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt @@ -58,7 +58,7 @@ class GamesClientTagTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ), selected = "games", onSelect = {}, modifier = Modifier.fillMaxSize()) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt index 62c90ce94a..aadb56e753 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt @@ -142,7 +142,7 @@ class GlobalGlassesSettingsTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}, onPairWirelessDebugging = {}) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt index 8def5601a4..ac643381a5 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt @@ -258,6 +258,18 @@ class InputSettingsTest { compose.onNodeWithTag("input-layout-canvas").assertExists() } + @Test fun everyScreenOpensWithItsEditorFirst() { + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() + val tops = listOf("primary", "secondary").map { screen -> + compose.onNodeWithTag("input-part-$screen").performScrollTo().performClick() + val top = compose.onNodeWithTag("input-surface-$screen").assertIsDisplayed().fetchSemanticsNode().boundsInRoot.top + compose.onNodeWithText(context.getString(R.string.mode_back)).performClick() + top + } + assertEquals(tops[1], tops[0]) + } + @Test fun deviceSettingsAreInlineBelowProfiles() { compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } compose.onNodeWithTag("input-more").assertDoesNotExist() @@ -522,6 +534,127 @@ class InputSettingsTest { } } + @Test fun buttonSizeResizesOnlyTheSelectedControlAndEverythingWithoutASelection() { + val library = InputLibraries.read(context) + val layout = library.layout("game", InputRole.PRIMARY)!! + compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } + fun editor() = generateSequence(listOf<android.view.View>(ShadowDialog.getLatestDialog().window!!.decorView)) { views -> + views.filterIsInstance<android.view.ViewGroup>().flatMap { g -> (0 until g.childCount).map(g::getChildAt) }.ifEmpty { null } + }.flatten().filterIsInstance<InputSurfaceEditorView>().first() + val stock = compose.runOnIdle { editor().rendered().associateBy { it.id } } + compose.onNodeWithTag("input-editor-tools").performClick() + compose.runOnIdle { editor().onSelect("legacy:a") } + val slider = compose.onNodeWithTag("input-editor-scale").performScrollTo() + slider.assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%")) + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(150f) } + val one = compose.runOnIdle { editor().rendered().associateBy { it.id } } + assertEquals(stock.getValue("legacy:a").width * 1.5f, one.getValue("legacy:a").width, .002f) + for (id in listOf("legacy:b", "legacy:x", "legacy:ls")) stock.getValue(id).let { e -> one.getValue(id).let { o -> + assertEquals(id, e.x, o.x, .0001f); assertEquals(id, e.y, o.y, .0001f); assertEquals(id, e.width, o.width, .0001f) } } + compose.runOnIdle { editor().onSelect("legacy:up") } + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(150f) } + val pad = compose.runOnIdle { editor().rendered().associateBy { it.id } } + for (id in listOf("legacy:up", "legacy:down", "legacy:left", "legacy:right")) assertEquals(id, stock.getValue(id).height * 1.5f, pad.getValue(id).height, .002f) + compose.runOnIdle { assertEquals(4, editor().artworkDpad().size) } + compose.runOnIdle { editor().onSelect(null) } + slider.assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%")) + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(110f) } + val all = compose.runOnIdle { editor().rendered().associateBy { it.id } } + assertEquals(stock.getValue("legacy:ls").width * 1.1f, all.getValue("legacy:ls").width, .003f) + assertEquals(stock.getValue("legacy:a").width * 1.65f, all.getValue("legacy:a").width, .004f) + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() + compose.runOnIdle { assertEquals(1.1f, InputLibraries.read(context).layouts.first { it.id == layout.id }.scale) } + } + + @Test fun undoAfterResizingAControlAgainKeepsAnotherControlsMove() { + val library = InputLibraries.read(context) + val layout = library.layout("game", InputRole.PRIMARY)!! + compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } + fun editor() = generateSequence(listOf<android.view.View>(ShadowDialog.getLatestDialog().window!!.decorView)) { views -> + views.filterIsInstance<android.view.ViewGroup>().flatMap { g -> (0 until g.childCount).map(g::getChildAt) }.ifEmpty { null } + }.flatten().filterIsInstance<InputSurfaceEditorView>().first() + compose.onNodeWithTag("input-editor-tools").performClick() + compose.runOnIdle { editor().onSelect("legacy:a") } + fun slider() = compose.onNodeWithTag("input-editor-scale").performScrollTo() + slider().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(150f) } + val resized = compose.runOnIdle { editor().rendered().associateBy { it.id } } + compose.runOnIdle { + val view = editor() + view.onBeginEdit(view.rendered(), view.width, view.height) + view.onChange(listOf(view.rendered().first { it.id == "legacy:b" }.let { it.copy(x = it.x - .1f) })) + } + val moved = compose.runOnIdle { editor().rendered().associateBy { it.id } } + assertEquals(resized.getValue("legacy:b").x - .1f, moved.getValue("legacy:b").x, .002f) + compose.onNodeWithTag("input-editor-tools").performClick() + compose.runOnIdle { editor().onSelect("legacy:a") } + slider().assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%")) + slider().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(120f) } + compose.onNodeWithText(context.getString(R.string.input_editor_undo)).performScrollTo().performClick() + val undone = compose.runOnIdle { editor().rendered().associateBy { it.id } } + assertEquals(moved.getValue("legacy:b").x, undone.getValue("legacy:b").x, .0001f) + assertEquals(resized.getValue("legacy:a").width, undone.getValue("legacy:a").width, .0001f) + } + + @Test fun buttonSizeShowsTheGamepadWhereItWillBeSaved() { + val library = InputLibraries.read(context) + val layout = library.layout("game", InputRole.PRIMARY)!! + assertEquals(InputLibraries.OVERLAY, layout.id) + val round = mutableStateOf(0) + compose.setContent { DroidDeckTheme { androidx.compose.runtime.key(round.value) { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } } + fun editor() = generateSequence(listOf<android.view.View>(ShadowDialog.getLatestDialog().window!!.decorView)) { views -> + views.filterIsInstance<android.view.ViewGroup>().flatMap { g -> (0 until g.childCount).map(g::getChildAt) }.ifEmpty { null } + }.flatten().filterIsInstance<InputSurfaceEditorView>().first() + val stock = compose.runOnIdle { editor().rendered() } + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(95f) } + val scaled = compose.runOnIdle { editor().rendered() } + assertNotEquals(stock, scaled) + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() + compose.runOnIdle { assertEquals(.95f, InputLibraries.read(context).layouts.first { it.id == layout.id }.scale) } + compose.runOnIdle { round.value = 1 } + compose.runOnIdle { assertEquals(scaled, editor().rendered()) } + } + + @Test @Config(qualifiers = "w468dp-h833dp-port-369dpi") + fun buttonSizeInPortraitKeepsLandscapeEditsWithoutARotatedFrame() { + val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y") + val gamepad = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!! + val landscape = gamepad.copy(elements = gamepad.elements.map { if (it.id in face) it.copy(x = it.x + .012f, y = it.y + .017f) else it }, + aspect = 1600f / 900f, rotated = emptyList(), rotatedAspect = 0f) + InputLibraries.update(context) { it.withLayout(landscape) } + val library = InputLibraries.read(context) + val round = mutableStateOf(0) + compose.setContent { DroidDeckTheme { androidx.compose.runtime.key(round.value) { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = landscape.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } } + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(90f) } + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() + compose.runOnIdle { + val saved = InputLibraries.read(context).layouts.first { it.id == landscape.id } + assertEquals(landscape.aspect, saved.aspect) + for (id in face) assertEquals(landscape.elements.first { it.id == id }.let { it.x to it.y }, saved.elements.first { it.id == id }.let { it.x to it.y }) + assertTrue(saved.rotated.isNotEmpty() && saved.rotatedAspect < 1f) + assertEquals(landscape.scale, saved.scale) + assertEquals(.9f, saved.rotatedScale) + assertEquals(.9f, OnScreenLayout.oriented(saved, 900, 1600).scale) + assertEquals(landscape.scale, OnScreenLayout.oriented(saved, 1600, 900).scale) + } + compose.runOnIdle { round.value = 1 } + compose.onNodeWithTag("input-editor-tools").performClick() + val slider = compose.onNodeWithTag("input-editor-scale").performScrollTo() + assertEquals(90f, slider.fetchSemanticsNode().config[androidx.compose.ui.semantics.SemanticsProperties.ProgressBarRangeInfo].current, .5f) + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(80f) } + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() + compose.runOnIdle { + val saved = InputLibraries.read(context).layouts.first { it.id == landscape.id } + assertEquals(landscape.scale, saved.scale) + assertEquals(.8f, saved.rotatedScale) + } + } + @Test @Config(qualifiers = "w833dp-h468dp-land-369dpi") fun buttonSizeKeepsMovedGamepadGroupsInShape() { val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y") diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt index 192e70d5e1..d322a387df 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt @@ -1,15 +1,29 @@ package com.droiddeck.launcher.ui +import android.content.Context +import android.view.InputDevice import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup import com.droiddeck.launcher.input.InputControl +import com.droiddeck.launcher.input.InputLibraries import com.droiddeck.launcher.input.InputSurfaceElement import com.droiddeck.launcher.input.OnScreenLayout +import com.droiddeck.launcher.input.PadKit import com.droiddeck.launcher.input.SavedInputLayout +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState +import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @@ -18,8 +32,17 @@ class InputSurfaceEditorViewTest { private val context get() = RuntimeEnvironment.getApplication() private val layout = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .1f, .2f, .2f, .2f)), aspect = 2f) + @Before fun reset() { + for (name in listOf("input-profiles", "input-surfaces", "controller", "session")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit() + } + + @After fun restoreSession() { + SessionState.deckPad = false + SessionState.mode = SessionService.MODE_STEAM + } + private fun view() = InputSurfaceEditorView(context).apply { - layout(0, 0, 1000, 1000) + place(1000, 1000) sourceLayout = layout aspect = layout.aspect elements = layout.elements @@ -27,13 +50,46 @@ class InputSurfaceEditorViewTest { } private fun center() = OnScreenLayout.editorElements(context, layout, 1000, 1000).first().let { (it.x + it.width / 2) * 1000 to (it.y + it.height / 2) * 1000 } - @Suppress("UNCHECKED_CAST") - private fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List<InputSurfaceElement> + private fun overlay() = InputLibraries.read(context).layouts.first { it.id == InputLibraries.OVERLAY } + + private fun editor(layout: SavedInputLayout, w: Int, h: Int) = InputSurfaceEditorView(context).apply { + sourceLayout = layout + aspect = layout.aspect + elements = layout.elements + snap = false + place(w, h) + } + + private fun field(target: Any, name: String) = target.javaClass.getDeclaredField(name).also { it.isAccessible = true }.get(target) + private fun InputSurfaceEditorView.controls() = (field(field(this, "preview")!!, "customCanvas") as ViewGroup).let { canvas -> (0 until canvas.childCount).map(canvas::getChildAt) } + private fun InputSurfaceEditorView.rects() = controls().map { listOf(it.left, it.top, it.width, it.height) } + + private fun InputSurfaceEditorView.assertControlsDrawnWhereDisplayed() { + val shown = rendered() + val views = controls() + assertEquals(shown.size, views.size) + for ((e, v) in shown.zip(views)) { + assertEquals(e.id, e.x * width, v.left.toFloat(), 1f) + assertEquals(e.id, e.y * height, v.top.toFloat(), 1f) + assertEquals(e.id, e.width * width, v.width.toFloat(), 1f) + assertEquals(e.id, e.height * height, v.height.toFloat(), 1f) + } + } private fun InputSurfaceEditorView.touch(action: Int, x: Float, y: Float) { MotionEvent.obtain(0, 10, action, x, y, 0).also { onTouchEvent(it); it.recycle() } } + private fun InputSurfaceEditorView.mouse(action: Int, x: Float, y: Float) { + val properties = MotionEvent.PointerProperties().apply { id = 0; toolType = MotionEvent.TOOL_TYPE_MOUSE } + val coords = MotionEvent.PointerCoords().apply { this.x = x; this.y = y; pressure = 1f } + val buttons = if (action == MotionEvent.ACTION_UP) 0 else MotionEvent.BUTTON_PRIMARY + MotionEvent.obtain(0, 10, action, 1, arrayOf(properties), arrayOf(coords), 0, buttons, 1f, 1f, 0, 0, InputDevice.SOURCE_MOUSE, 0) + .also { dispatchTouchEvent(it); it.recycle() } + } + + private fun InputSurfaceEditorView.centre(id: String) = rendered().first { it.id == id }.let { (it.x + it.width / 2) * width to (it.y + it.height / 2) * height } + @Test fun editingStartsInTheDisplayedFrame() { val view = view() var started: Pair<List<InputSurfaceElement>, Float>? = null @@ -70,7 +126,185 @@ class InputSurfaceEditorViewTest { view.elements = renamed view.aspect = 2f assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 1000, 1000), view.rendered()) - view.layout(0, 0, 800, 1000) + view.place(800, 1000) assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 800, 1000), view.rendered()) } + + @Test fun theOverlayEditorDrawsTheKitArtworkWhereTheSessionPlacesIt() { + val layout = overlay() + assertNotNull(PadKit.forOverlay(context, layout)) + val view = editor(layout, 2400, 1504) + assertEquals(OnScreenLayout.editorElements(context, layout, 2400, 1504), view.rendered()) + view.assertControlsDrawnWhereDisplayed() + assertEquals(4, view.artworkDpad().size) + } + + @Test fun copiesOfTheOverlayDrawTheSameKitArtworkInTheSamePlaces() { + val source = overlay() + val copy = source.derived("copy", "Copy") + val again = copy.derived("again", "Again") + for (layout in listOf(copy, again)) { + assertEquals(PadKit.forOverlay(context, source), PadKit.forOverlay(context, layout)) + for ((w, h) in listOf(2400 to 1504, 1504 to 2400)) { + assertEquals(OnScreenLayout.editorElements(context, source, w, h), + OnScreenLayout.editorElements(context, layout, w, h)) + } + assertEquals(4, editor(layout, 2400, 1504).artworkDpad().size) + } + assertNotNull(PadKit.forOverlay(context, source.copy(id = "migrated.layout.2400x1504"))) + assertEquals(null, PadKit.forOverlay(context, this.layout)) + assertEquals(null, PadKit.forOverlay(context, this.layout.derived("custom-copy", "Copy"))) + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE) + assertEquals(null, PadKit.forOverlay(context, copy)) + } + + @Config(qualifiers = "xhdpi") + @Test fun controlsAddedForTheScreenAreDrawnOnTheFirstFrameInBothOrientations() { + SessionState.mode = SessionService.MODE_STEAM + SessionState.deckPad = true + SessionPrefs.setOscRearButtons(context, true) + SessionPrefs.setOscTrackpads(context, true) + val layout = overlay() + for ((w, h) in listOf(2400 to 1504, 1504 to 2400)) { + val view = editor(layout, w, h) + assertTrue(view.rendered().size > layout.elements.size) + view.assertControlsDrawnWhereDisplayed() + assertEquals(4, view.artworkDpad().size) + } + } + + @Test fun displayedControlsStayPutAcrossRepeatedRefreshesAndResizes() { + val view = editor(overlay(), 2400, 1504) + val first = view.rendered() + val drawn = view.rects() + repeat(3) { + view.elements = view.elements + view.aspect = view.aspect + view.sourceLayout = view.sourceLayout + view.place(1504, 2400) + view.assertControlsDrawnWhereDisplayed() + view.place(2400, 1504) + assertEquals(first, view.rendered()) + assertEquals(drawn, view.rects()) + assertEquals(4, view.artworkDpad().size) + } + } + + @Test fun dpadPiecesRedrawWhenTheyLeaveOrRejoinTheKitCross() { + val view = editor(overlay(), 2400, 1504) + val stock = view.rendered() + view.aspect = 2400f / 1504 + val pieces = view.controls().filter { (it.tag as InputSurfaceElement).id in setOf("legacy:up", "legacy:right", "legacy:down", "legacy:left") } + assertEquals(4, pieces.size) + for ((moved, expected) in listOf(stock.map { if (it.id == "legacy:up") it.copy(y = it.y - .2f) else it } to 0, stock to 4)) { + pieces.forEach { shadowOf(it).clearWasInvalidated() } + view.elements = moved + view.place(2400, 1504) + assertEquals(expected, view.artworkDpad().size) + pieces.forEach { assertTrue((it.tag as InputSurfaceElement).id, shadowOf(it).wasInvalidated()) } + } + } + + @Test fun draggingMovesTheTouchedControlByTheDragDistance() { + val view = editor(overlay(), 2400, 1504) + val a = view.rendered().first { it.id == "legacy:a" } + val changes = mutableListOf<InputSurfaceElement>() + view.onChange = { changes += it } + val (x, y) = view.centre(a.id) + view.touch(MotionEvent.ACTION_DOWN, x, y) + view.touch(MotionEvent.ACTION_MOVE, x - 240f, y - 150f) + view.touch(MotionEvent.ACTION_UP, x - 240f, y - 150f) + val moved = changes.last() + assertEquals(a.id, moved.id) + assertEquals(a.x - 240f / 2400, moved.x, .0001f) + assertEquals(a.y - 150f / 1504, moved.y, .0001f) + assertEquals(a.width, moved.width, .0001f) + } + + @Test fun theDpadMovesAndResizesAsOneControlFromAnyArrowOrItsCentre() { + val view = editor(overlay(), 2400, 1504) + val arrows = listOf("legacy:up", "legacy:right", "legacy:down", "legacy:left") + fun pad() = view.rendered().filter { it.id in arrows }.associateBy { it.id } + val before = pad() + assertEquals(4, view.artworkDpad().size) + val changes = mutableListOf<InputSurfaceElement>() + view.onBeginEdit = { shown, w, h -> view.aspect = w.toFloat() / h; view.elements = shown } + view.onChange = { changes += it; view.elements = view.elements.map { e -> it.firstOrNull { c -> c.id == e.id } ?: e } } + val left = before.getValue("legacy:left"); val right = before.getValue("legacy:right") + val x = (left.x + left.width + right.x) / 2 * 2400; val y = (left.y + left.height / 2) * 1504 + view.touch(MotionEvent.ACTION_DOWN, x, y) + view.touch(MotionEvent.ACTION_MOVE, x + 240f, y - 150f) + view.touch(MotionEvent.ACTION_UP, x + 240f, y - 150f) + val moved = changes.takeLast(4).associateBy { it.id } + assertEquals(arrows.toSet(), moved.keys) + for (id in arrows) { + assertEquals(id, before.getValue(id).x + 240f / 2400, moved.getValue(id).x, .0001f) + assertEquals(id, before.getValue(id).y - 150f / 1504, moved.getValue(id).y, .0001f) + } + assertEquals(4, view.artworkDpad().size) + val down = moved.getValue("legacy:down"); val r = moved.getValue("legacy:right") + val cx = (r.x + r.width) * 2400; val cy = (down.y + down.height) * 1504 + view.touch(MotionEvent.ACTION_DOWN, cx, cy) + view.touch(MotionEvent.ACTION_MOVE, cx + 80f, cy + 80f) + view.touch(MotionEvent.ACTION_UP, cx + 80f, cy + 80f) + val resized = changes.takeLast(4).associateBy { it.id } + assertEquals(arrows.toSet(), resized.keys) + assertTrue(resized.getValue("legacy:up").width > moved.getValue("legacy:up").width) + assertEquals(4, view.artworkDpad().size) + } + + @Test fun shrinkingTheDpadStopsBeforeAnyArrowIsSmallerThanASingleControlCanBe() { + val view = editor(overlay(), 2400, 1504) + val arrows = listOf("legacy:up", "legacy:right", "legacy:down", "legacy:left") + val pad = view.rendered().filter { it.id in arrows } + val changes = mutableListOf<InputSurfaceElement>() + view.onBeginEdit = { shown, w, h -> view.aspect = w.toFloat() / h; view.elements = shown } + view.onChange = { changes += it; view.elements = view.elements.map { e -> it.firstOrNull { c -> c.id == e.id } ?: e } } + val right = pad.maxOf { it.x + it.width } * 2400; val bottom = pad.maxOf { it.y + it.height } * 1504 + val (ux, uy) = view.centre("legacy:up") + view.touch(MotionEvent.ACTION_DOWN, ux, uy) + view.touch(MotionEvent.ACTION_UP, ux, uy) + view.touch(MotionEvent.ACTION_DOWN, right, bottom) + view.touch(MotionEvent.ACTION_MOVE, 0f, 0f) + view.touch(MotionEvent.ACTION_UP, 0f, 0f) + val shrunk = changes.takeLast(4) + assertEquals(arrows.toSet(), shrunk.map { it.id }.toSet()) + shrunk.forEach { assertTrue(it.id, it.width >= .0299f && it.height >= .0299f) } + } + + @Test fun aMouseSelectsDragsAndResizesLikeATouch() { + val view = editor(overlay(), 2400, 1504) + val a = view.rendered().first { it.id == "legacy:a" } + val changes = mutableListOf<InputSurfaceElement>() + var selection: String? = null + view.onSelect = { selection = it } + view.onChange = { changes += it } + val (x, y) = view.centre(a.id) + view.mouse(MotionEvent.ACTION_DOWN, x, y) + view.mouse(MotionEvent.ACTION_UP, x, y) + assertEquals(a.id, selection) + view.mouse(MotionEvent.ACTION_DOWN, x, y) + view.mouse(MotionEvent.ACTION_MOVE, x - 240f, y) + view.mouse(MotionEvent.ACTION_UP, x - 240f, y) + assertEquals(a.x - 240f / 2400, changes.last().x, .0001f) + val right = (a.x + a.width) * 2400; val bottom = (a.y + a.height) * 1504 + view.mouse(MotionEvent.ACTION_DOWN, right, bottom) + view.mouse(MotionEvent.ACTION_MOVE, right + 60f, bottom + 60f) + view.mouse(MotionEvent.ACTION_UP, right + 60f, bottom + 60f) + val resized = changes.last() + assertEquals(a.id, resized.id) + assertEquals(a.width + 60f / 2400, resized.width, .0001f) + assertEquals(a.height + 60f / 1504, resized.height, .0001f) + } } + +internal fun InputSurfaceEditorView.place(w: Int, h: Int) { + measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY)) + layout(0, 0, w, h) +} + +@Suppress("UNCHECKED_CAST") +internal fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List<InputSurfaceElement> + +internal fun InputSurfaceEditorView.artworkDpad() = javaClass.getDeclaredField("preview").also { it.isAccessible = true }.get(this)!!.let { preview -> + preview.javaClass.getDeclaredField("artworkDpad").also { it.isAccessible = true }.get(preview) as List<*> } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt index 3df8d65e0f..cd92665cc2 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt @@ -77,6 +77,25 @@ class InputSurfaceTouchTest { assertFalse(state().isDown(PadState.A)) } + @Test fun steamDeckStylingKeepsTheHeldButtonAndItsHitArea() { + val button = a.copy(buttonShape = InputButtonShape.CIRCLE) + show(button) + val surface = view.inputSurface + val shown = surface.shownElements + + touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f)) + assertTrue(state().isDown(PadState.A)) + for (artwork in PadKit.entries) { + surface.updateStyle(InputSurfaceStyle(), artwork) + assertEquals(shown, surface.shownElements) + assertTrue(surface.takesTouchAt(800f, 240f)) + assertTrue(state().isDown(PadState.A)) + } + + touch(MotionEvent.ACTION_UP, 1 to (800f to 240f)) + assertFalse(state().isDown(PadState.A)) + } + @Test fun aStickKeepsItsFingerWhenItCrossesAButton() { touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f)) touch(MotionEvent.ACTION_MOVE, 1 to (800f to 240f)) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt index 9f28c9ccc1..508e2ed4b6 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt @@ -100,7 +100,7 @@ class InputUiLayoutTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, controller = ControllerActions({}), ), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}, onPairWirelessDebugging = {}) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt index 37544588f3..65eef5d38f 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt @@ -66,7 +66,7 @@ class LaunchSettingsComponentsTest { onImportLossless = {}, onProtons = {}, onComponents = { defaultOpens++ }, onGameComponents = { openedGame = it }, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ), rememberMenuHost(), diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt index 772578ea37..b168587e09 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryEntriesTest.kt @@ -96,9 +96,9 @@ class LibraryEntriesTest { } @Test fun placesRoundTripThroughTheirOrder() { - val order = listOf("epic", "steam", "favorites", "gog", "xbox", "added") + val order = listOf("epic", "steam", "favorites", LIBRARY_HIDDEN, "gog", "xbox", "added") assertEquals(order, placeLibraryTabs(listOf("epic", "gog", "xbox"), libraryPlacesOf(order))) - assertEquals(listOf("favorites", "steam", "epic", "gog", "added"), placeLibraryTabs(listOf("epic", "gog"), emptyList())) + assertEquals(listOf("favorites", "steam", "epic", "gog", "added", LIBRARY_HIDDEN), placeLibraryTabs(listOf("epic", "gog"), emptyList())) } @Test fun librarySourcesIgnoreUnknownAndDuplicateOrderEntriesAndAppendNewStores() { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt index c2ce77dbf7..8a8cf59736 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryFavoritesTest.kt @@ -53,6 +53,6 @@ class LibraryFavoritesTest { @Test fun aHiddenFavoritesTabStaysHiddenWithHeartedGames() { val entries = listOf(steam(440, "Team Fortress 2"), owned("123", "Witcher")) - assertEquals(listOf("steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:123"), offTabs = setOf(LIBRARY_FAVORITES))) + assertEquals(listOf("steam", "gog"), librarySources(entries, listOf("gog"), favorites = setOf("gog:123"), offTabs = setOf(LIBRARY_FAVORITES, LIBRARY_HIDDEN))) } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt index 2630a3314d..4123ac826c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt @@ -230,7 +230,7 @@ class LibraryVisibilityTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt index 1736382512..b919b8688a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt @@ -40,8 +40,8 @@ class NavTabsTest { } @Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() { - assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state())) - assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync"), NavTabs.more(state())) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps")) assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent")) assertFalse(com.droiddeck.launcher.agent.AgentTab.shown) @@ -51,13 +51,13 @@ class NavTabsTest { @Test fun showingMusicOnceKeepsItShownAfterReload() { place("soundtracks", TabPlace.BAR) NavTabs.load(ctx) - assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "soundtracks", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", NavTabs.MORE), navigationKeys(state())) } @Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() { place("desktop", TabPlace.MORE) val s = state() - assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync"), NavTabs.more(s)) + assertEquals(listOf("desktop", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s)) assertEquals(NavTabs.MORE, navigationKeys(s).last()) assertFalse("desktop" in navigationKeys(s)) } @@ -70,14 +70,14 @@ class NavTabsTest { } @Test fun resettingPutsBackTheDefaultLayout() { - place("stores", TabPlace.BAR) + place("stores", TabPlace.MORE) place("updates", TabPlace.HIDDEN) moveTab("downloads", -1) assertFalse(NavTabs.isDefault()) NavTabs.reset(ctx) NavTabs.load(ctx) assertTrue(NavTabs.isDefault()) - assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", NavTabs.MORE), navigationKeys(state())) } @Test fun anOldLayoutKeepsWhatItsSwitchesShowed() { @@ -86,7 +86,7 @@ class NavTabsTest { NavTabs.load(ctx) val s = state() assertEquals(listOf("steam", "games", "desktop", "components", "setup", "updates", NavTabs.MORE), navigationKeys(s)) - assertEquals(listOf("storage", "sync"), NavTabs.more(s)) + assertEquals(listOf("storage", "sync", "decky", "boot-movies"), NavTabs.more(s)) listOf("stores", "downloads", "soundtracks", "android-apps", "agent").forEach { assertEquals(it, TabPlace.HIDDEN, NavTabs.place(s, it)) } val prefs = ctx.getSharedPreferences("session", Context.MODE_PRIVATE) assertFalse(prefs.contains("gameStoresEnabled")) @@ -108,7 +108,7 @@ class NavTabsTest { assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "stores")) assertEquals(TabPlace.MORE, NavTabs.place(state(), "components")) assertEquals(TabPlace.BAR, NavTabs.place(state(), "downloads")) - assertEquals(listOf("components", "storage", "sync"), NavTabs.more(state())) + assertEquals(listOf("components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) } @Test fun movingSwapsWithTheNextVisibleTabAndPersists() { @@ -119,9 +119,9 @@ class NavTabsTest { } @Test fun tabsMissingFromASavedOrderSlotInAfterTheirDefaultNeighbour() { - assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"), + assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"), NavTabs.arrange(listOf("updates", "steam"))) - assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "android-apps", "agent", "updates"), + assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "updates"), NavTabs.arrange(listOf("games", "steam", "setup", "stores", "desktop", "components", "android-apps", "updates", "bogus"))) } @@ -130,7 +130,7 @@ class NavTabsTest { .putString("navTabOrder", "steam,games,soundtracks,stores,desktop,agent,components,android-apps,setup,updates") .putString("navTabShelved", "soundtracks").commit() NavTabs.load(ctx) - assertEquals(listOf("soundtracks", "storage", "sync"), NavTabs.more(state())) + assertEquals(listOf("soundtracks", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) place("sync", TabPlace.BAR) NavTabs.load(ctx) assertTrue("sync" in navigationKeys(state())) @@ -262,7 +262,7 @@ class NavTabsTest { onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = {}, ) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt index 5332c83ab0..004fe8cd64 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt @@ -94,7 +94,7 @@ class NavigationSelectionTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PickVolumesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PickVolumesTest.kt new file mode 100644 index 0000000000..0ab95caf7f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/PickVolumesTest.kt @@ -0,0 +1,88 @@ +package com.droiddeck.launcher.ui + +import android.os.Environment +import android.os.Process +import android.os.storage.StorageManager +import com.droiddeck.launcher.files.StorageRoot +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.StorageVolumeBuilder +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class PickVolumesTest { + @get:Rule val temporary = TemporaryFolder() + + private val internal = File("/storage/emulated/0") + + private fun root(label: String, path: String, removable: Boolean = true, readable: Boolean = true) = + StorageRoot(label, File(path), removable, readable) + + @Test fun aCardOnlyReachableThroughMediaRwIsListed() { + val volumes = pickVolumes(internal, "Internal storage", listOf( + root("Internal", "/storage/emulated/0", removable = false), + root("4A1C-830B", "/mnt/media_rw/4A1C-830B"), + )) + + assertEquals(listOf("/storage/emulated/0", "/mnt/media_rw/4A1C-830B"), volumes.map { it.root.path }) + assertEquals("Internal storage", volumes.first().label) + assertFalse(volumes.first().removable) + assertEquals("4A1C-830B", volumes[1].label) + assertTrue(volumes[1].removable) + } + + @Test fun aVisibleCardKeepsItsStoragePathAndLabel() { + val volumes = pickVolumes(internal, "Internal storage", listOf( + root("Internal", "/storage/emulated/0", removable = false), + root("SanDisk SD card", "/storage/1234-ABCD"), + root("USB drive", "/storage/5678-EF01"), + )) + + assertEquals(listOf("Internal storage", "SanDisk SD card", "USB drive"), volumes.map { it.label }) + assertEquals(File("/storage/1234-ABCD"), volumes[1].root) + } + + @Test fun unreadableVolumesAndInternalStorageAreNotListedTwice() { + val volumes = pickVolumes(internal, "Internal storage", listOf( + root("Internal", "/storage/emulated", removable = false), + root("Internal", "/storage/emulated/0/Android/data/com.droiddeck.launcher/files", removable = false), + root("SD card", "/storage/1234-ABCD", readable = false), + root("USB drive", "/mnt/media_rw/5678-EF01"), + root("USB drive", "/mnt/media_rw/5678-EF01"), + )) + + assertEquals(listOf("/storage/emulated/0", "/mnt/media_rw/5678-EF01"), volumes.map { it.root.path }) + } + + @Test fun withNoExternalVolumesOnlyInternalStorageIsListed() { + val volumes = pickVolumes(internal, "Internal storage", listOf(root("Internal", "/storage/emulated/0", removable = false))) + + assertEquals(listOf(internal), volumes.map { it.root }) + } + + @Test fun aMountedVolumeWithoutAnAppFolderReachesThePicker() { + val mount = temporary.newFolder("4A1C-830B") + val context = RuntimeEnvironment.getApplication() + val volume = StorageVolumeBuilder("public:179,1", mount, "SD card", Process.myUserHandle(), Environment.MEDIA_MOUNTED) + .setIsPrimary(false) + .setIsEmulated(false) + .setIsRemovable(true) + .build() + shadowOf(context.getSystemService(StorageManager::class.java)).addStorageVolume(volume) + + val card = pickVolumes(context).single { it.root.absoluteFile == mount.absoluteFile } + + assertEquals("SD card", card.label) + assertTrue(card.removable) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt index 1f6a4b7073..f5988c0b80 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt @@ -152,7 +152,7 @@ class PortraitLayoutTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt index a26973f87e..ebe743b644 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt @@ -1,11 +1,15 @@ package com.droiddeck.launcher.ui import android.content.ComponentName +import android.os.Handler +import android.view.Choreographer import androidx.activity.ComponentActivity +import androidx.compose.ui.platform.AndroidUiDispatcher import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.runtime.snapshots.Snapshot import org.robolectric.RuntimeEnvironment import org.robolectric.Shadows.shadowOf +import kotlin.coroutines.ContinuationInterceptor fun createRobolectricComposeRule() = createComposeRule().also { RingVeil.reset() @@ -13,5 +17,46 @@ fun createRobolectricComposeRule() = createComposeRule().also { shadowOf(context.packageManager).addActivityIfNotPresent( ComponentName(context, ComponentActivity::class.java), ) + resumeDroppedUiDispatch() Snapshot.sendApplyNotifications() } + +internal class UiDispatch { + private val type = AndroidUiDispatcher::class.java + private val dispatcher = AndroidUiDispatcher.Main[ContinuationInterceptor] as AndroidUiDispatcher + private fun field(name: String) = type.getDeclaredField(name).apply { isAccessible = true } + val lock: Any = field("lock").get(dispatcher)!! + val handler = field("handler").get(dispatcher) as Handler + val choreographer = field("choreographer").get(dispatcher) as Choreographer + val callback: Any = field("dispatchCallback").get(dispatcher)!! + private val trampolineFlag = field("scheduledTrampolineDispatch") + private val frameFlag = field("scheduledFrameDispatch") + + fun trampolineDropped() = trampolineFlag.getBoolean(dispatcher) && !handler.hasMessages(0) + + fun frameDropped() = frameFlag.getBoolean(dispatcher) && !frameQueued() + + private fun frameQueued(): Boolean { + val queues = Choreographer::class.java.getDeclaredField("mCallbackQueues").apply { isAccessible = true }.get(choreographer) as Array<*> + return queues.any { queue -> + var record = queue?.let { q -> q.javaClass.getDeclaredField("mHead").apply { isAccessible = true }.get(q) } + var found = false + while (record != null && !found) { + val recordType = record.javaClass + found = recordType.getDeclaredField("action").apply { isAccessible = true }.get(record) === callback + record = recordType.getDeclaredField("next").apply { isAccessible = true }.get(record) + } + found + } + } +} + +internal fun uiDispatchDropped(): Boolean = UiDispatch().run { synchronized(lock) { trampolineDropped() || frameDropped() } } + +internal fun resumeDroppedUiDispatch() { + val ui = UiDispatch() + synchronized(ui.lock) { + if (ui.trampolineDropped()) ui.handler.post(ui.callback as Runnable) + if (ui.frameDropped()) ui.choreographer.postFrameCallback(ui.callback as Choreographer.FrameCallback) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt new file mode 100644 index 0000000000..22ee813a5b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt @@ -0,0 +1,90 @@ +package com.droiddeck.launcher.ui + +import android.os.Looper +import android.view.Choreographer +import androidx.compose.runtime.MutableIntState +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.platform.AndroidUiDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.time.Duration + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], application = android.app.Application::class) +class RobolectricComposeRuleTest { + private fun dropPendingUiDispatch() { + val ui = UiDispatch() + ui.handler.removeCallbacksAndMessages(null) + dropPendingFrame() + } + + private fun dropPendingFrame() { + val ui = UiDispatch() + ui.choreographer.removeFrameCallback(ui.callback as Choreographer.FrameCallback) + } + + private fun awaitFrameAfterTrampoline(ran: MutableIntState) { + CoroutineScope(AndroidUiDispatcher.Main).launch { withFrameNanos { ran.intValue++ } } + shadowOf(Looper.getMainLooper()).runOneTask() + } + + @Test + fun uiWorkDroppedByAnEarlierTestsLooperResetRunsAgainForTheNextComposeTest() { + val ran = mutableIntStateOf(0) + CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ } + dropPendingUiDispatch() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(0, ran.intValue) + assertTrue(uiDispatchDropped()) + createRobolectricComposeRule() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } + + @Test + fun aDispatchStillQueuedIsLeftAlone() { + val ran = mutableIntStateOf(0) + CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ } + assertFalse(uiDispatchDropped()) + resumeDroppedUiDispatch() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } + + @Test + fun aFrameDroppedAfterTheTrampolineDrainedRunsAgainForTheNextComposeTest() { + val ran = mutableIntStateOf(0) + awaitFrameAfterTrampoline(ran) + dropPendingFrame() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(0, ran.intValue) + assertTrue(uiDispatchDropped()) + createRobolectricComposeRule() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } + + @Test + fun aFrameStillQueuedIsLeftAlone() { + val ran = mutableIntStateOf(0) + awaitFrameAfterTrampoline(ran) + assertEquals(0, ran.intValue) + assertFalse(uiDispatchDropped()) + resumeDroppedUiDispatch() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt index adbbbe248a..18911a3521 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -8,15 +8,45 @@ class SessionDrawerPageTest { val pages = sessionDrawerPages(hasAgent = false) assertEquals(SessionDrawerPage.CONTROLLER, pages.first()) assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1)) - assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.CONTROLLER, -1)) - assertEquals(SessionDrawerPage.CONTROLLER, pages.step(SessionDrawerPage.SESSION, 1)) + assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.CONTROLLER, -1)) assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1)) assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1)) - assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1)) - assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.VR, 1)) + assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.EFFECTS, 1)) assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1)) } + @Test fun moreKeepsSteamVrByDefaultAndStandsInForThePagesInsideIt() { + val pages = sessionDrawerPages(hasAgent = false) + assertEquals(listOf(SessionDrawerPage.VR), pages.inMore()) + assertEquals(SessionDrawerPage.MORE, pages.strip().last()) + assertFalse(SessionDrawerPage.VR in pages.strip()) + assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.VR)) + assertEquals(SessionDrawerPage.GAMES, pages.tabFor(SessionDrawerPage.GAMES)) + val strip = pages.strip() + assertEquals(SessionDrawerPage.MORE, strip.step(SessionDrawerPage.SESSION, 1)) + assertEquals(SessionDrawerPage.CONTROLLER, strip.step(SessionDrawerPage.MORE, 1)) + assertEquals(SessionDrawerPage.SESSION, strip.step(pages.tabFor(SessionDrawerPage.VR), -1)) + } + + @Test fun anOlderSavedOrderKeepsItsPagesAndGetsAMoreTabAfterSession() { + val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION") + val out = DrawerPages.arrange(saved) + assertEquals(SessionDrawerPage.MORE, out[out.indexOf(SessionDrawerPage.SESSION) + 1]) + assertTrue(out.indexOf(SessionDrawerPage.VR) < out.indexOf(SessionDrawerPage.EFFECTS) + 2) + assertTrue(out.inMore().isEmpty()) + } + + @Test fun sessionCanBeKeptInsideMore() { + val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "GAMES", "AGENT", "MORE", "SESSION", "VR") + val out = DrawerPages.arrange(saved) + assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore()) + assertFalse(SessionDrawerPage.SESSION in out.strip()) + } + + @Test fun moreAndSessionCannotBeHidden() { + assertFalse(DrawerPages.hideable(SessionDrawerPage.MORE)) + } + @Test fun glassesAddTheirPageAfterController() { val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false) assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1)) @@ -29,4 +59,17 @@ class SessionDrawerPageTest { assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1)) assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false)) } + + @Test fun arrangeKeepsSavedOrderAndSlotsNewPagesAfterTheirNeighbour() { + val saved = listOf("SESSION", "HUD", "CONTROLLER") + val out = DrawerPages.arrange(saved) + assertEquals(SessionDrawerPage.entries.toSet(), out.toSet()) + assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD), out.filter { it in setOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD) }) + assertTrue(out.indexOf(SessionDrawerPage.HUD) < out.indexOf(SessionDrawerPage.CONTROLLER)) + } + + @Test fun sessionPageCannotBeHidden() { + assertFalse(DrawerPages.hideable(SessionDrawerPage.SESSION)) + assertTrue(DrawerPages.hideable(SessionDrawerPage.HUD)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt index 14aed407ea..f4c4688f4a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt @@ -101,7 +101,7 @@ class SteamHomeHeadsetTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ), Modifier.fillMaxSize()) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt index 807b729f6d..76be29b5da 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SteamIntegrationGroupTest.kt @@ -41,7 +41,8 @@ class SteamIntegrationGroupTest { compose.onNodeWithTag("integration-action-brightness").performClick() compose.onNodeWithTag("integration-action-home").performClick() compose.onNodeWithTag("integration-action-shortcuts").performClick() - assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS), requests) + compose.onNodeWithTag("integration-action-bluetooth").performClick() + assertEquals(listOf(Feature.BRIGHTNESS, Feature.HOME, Feature.SHORTCUTS, Feature.BLUETOOTH), requests) } @Test fun switchesReflectAndroidGrants() { @@ -50,7 +51,8 @@ class SteamIntegrationGroupTest { compose.onNodeWithTag("integration-action-brightness").assert(stateIs("On")) compose.onNodeWithTag("integration-action-shortcuts").assert(stateIs("On")) compose.onNodeWithTag("integration-action-wifi").assert(stateIs("Off")) - compose.onNodeWithText("3 of 4 on").assertExists() + compose.onNodeWithTag("integration-action-bluetooth").assert(stateIs("Off")) + compose.onNodeWithText("3 of 5 on").assertExists() } @Test fun shortcutsDoNotNeedHome() { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt index 1f214aba0c..97f5c16ae9 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt @@ -145,7 +145,7 @@ class StoreRestorationTest { onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, - onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, ) } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt new file mode 100644 index 0000000000..d96dc487b6 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt @@ -0,0 +1,22 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.update.AppUpdates +import com.droiddeck.launcher.update.AppUpdates.Channel +import org.junit.Assert.assertEquals +import org.junit.Test + +class UpdatesRailIconTest { + private fun me(pr: Int = 0, ci: Boolean = true) = AppUpdates.Installed("abc", pr, "1.0", 1, ci, ciBuild = ci) + + @Test + fun releaseBuildsFollowTheirChannel() { + assertEquals(BuildKind.STABLE, RunningBuild.kind(me(), Channel.STABLE)) + assertEquals(BuildKind.PREVIEW, RunningBuild.kind(me(), Channel.NIGHTLY)) + } + + @Test + fun prBuildsAreTestAndNonCiBuildsAreLocal() { + assertEquals(BuildKind.TEST, RunningBuild.kind(me(pr = 12), Channel.TEST)) + assertEquals(BuildKind.LOCAL, RunningBuild.kind(me(ci = false), Channel.STABLE)) + } +} diff --git a/app/src/test/resources/META-INF/services/org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin b/app/src/test/resources/META-INF/services/org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin new file mode 100644 index 0000000000..d6d0a4d676 --- /dev/null +++ b/app/src/test/resources/META-INF/services/org.robolectric.pluginapi.TestEnvironmentLifecyclePlugin @@ -0,0 +1 @@ +com.droiddeck.launcher.session.TestJvmUncaughtHandler diff --git a/app/src/test/resources/gog/gen2-overlay-excerpt.json b/app/src/test/resources/gog/gen2-overlay-excerpt.json new file mode 100644 index 0000000000..87cb615f9b --- /dev/null +++ b/app/src/test/resources/gog/gen2-overlay-excerpt.json @@ -0,0 +1,58 @@ +{ + "base": [ + { + "path": "gog.dat", + "chunks": [ + { + "md5": "63b62221caca352670bec591f0e4ed7a", + "size": 65664, + "compressedMd5": "c5695c2838aa020b028334cda81c89e6", + "compressedSize": 34046 + } + ], + "type": "DepotFile" + }, + { + "path": "gog.idx", + "chunks": [ + { + "md5": "0a1f9d90b61039cb3f4f2952f47aeea7", + "size": 28, + "compressedMd5": "7a7f3c3d18c10a3890426ed3f11f6220", + "compressedSize": 24 + } + ], + "type": "DepotFile", + "sfcRef": { + "offset": 11, + "size": 28 + } + } + ], + "dlc": [ + { + "path": "gog.dat", + "chunks": [ + { + "md5": "dac36aea47f5de743d0e0ca10c79ad58", + "size": 16777344, + "compressedMd5": "a27cd9af6e5183a6392c25c973fc367c", + "compressedSize": 3992002 + } + ], + "type": "DepotFile" + }, + { + "path": "gog.idx", + "chunks": [ + { + "md5": "ae818b813bd3585c47846cf1e288b2e5", + "size": 28, + "compressedMd5": "869fd5dd8c9ad554ca8bccb0317a9757", + "compressedSize": 26 + } + ], + "type": "DepotFile" + } + ] +} \ No newline at end of file diff --git a/docs/agent-control.md b/docs/agent-control.md index 13bf1c232d..ac097234cf 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -135,6 +135,7 @@ tools/droiddeckctl input text 'hello world' tools/droiddeckctl input tap 640 360 tools/droiddeckctl input swipe 100 600 100 100 --duration 400 tools/droiddeckctl input pad a +tools/droiddeckctl input gamepad b rb up --hold 120 --gap 400 tools/droiddeckctl input stick left 0 -1 --hold 500 tools/droiddeckctl input trigger right 1.0 tools/droiddeckctl input pen tap 0.5 0.5 --pressure 0.7 @@ -234,6 +235,18 @@ and returns its exit code with the last 160 KiB of stdout and stderr (`--timeout that side over conflicts. The store id is the one in the game's install record (`library` shows it). Both need Setup > Developer > Debugging tools. +`input pad` writes to the session's virtual pad, the one the guest sees, and never reaches the app's +own key handling. To test how DroidDeck's own screens treat a controller (menu focus and outlines, +page switching with LB and RB, Back and Steam shortcuts), use `input gamepad`. It registers a real +gamepad called "DroidDeck test pad" with `adb shell uinput -`, so Android reports a physical +controller, and presses the buttons in order: `a b x y lb rb select start guide l3 r3` and the +d-pad `up down left right`. `--hold` (120 ms) is how long each stays down and `--gap` (400 ms) the +pause after it; a d-pad press always waits at least 20 ms, so Android sees each release before +the next press. The device exists only while the command runs, takes about a second to appear, and +works without a session or Setup > Developer > Debugging tools. Its name does not start with +`uinput-`, which the app treats as a system virtual device. `UINPUT_UNAVAILABLE` and `UINPUT_FAILED` +mean the same as for `input pen`. + `input pen` does not go through the app. It registers a virtual pen with `adb shell uinput -`, so Android's own input reader makes the stylus events, as for a built-in pen, and it works on whatever is on screen, without a session or Setup > Developer > Debugging tools. Positions are fractions of diff --git a/docs/development/game-environment.md b/docs/development/game-environment.md index ac7be74c62..916fa30dc6 100644 --- a/docs/development/game-environment.md +++ b/docs/development/game-environment.md @@ -212,6 +212,12 @@ more, so its fix removes both variables, also from its launch options, and sets `vk_x11_strict_image_count=true`, the option Mesa's driconf gives the game. A per-game value in the environment editor still wins. +Dragon Quest Monsters 4 does not draw slime bodies at its default monster mesh +detail, leaving only their tips. Before each launch, DroidDeck sets +`r.SkeletalMeshLODBias=-4` and `r.SkeletalMeshLODRadiusScale=0.25` under +`[SystemSettings]` in the game's `Engine.ini`. It does this every time because the +game ignores `-ini:` overrides and deletes a writable `Engine.ini` after reading it. + ## Defaults and available suggestions The initial configuration enables Mesa shader caching with @@ -293,6 +299,12 @@ configuration falls back to the inherited environment without evaluating its contents. Both component and environment selection normalize signed non-Steam prefix IDs to unsigned IDs. +A Dragon's Dogma 2 launch (Steam app 2054970) appends the game's own +`/WineDetectionEnabled:False` switch: the game checks for Wine and its Wine path +does not start. The switch is added only at launch, never to Steam's stored +Launch Options, and a user's own `/WineDetectionEnabled:` value in Launch +Options keeps priority and is not repeated. + The published file also carries generated `dxvkConfig` and `dxvkConfigGames` values the app's own file never has. The session menu's texture filtering (`core/TextureFiltering`) becomes `d3d9/d3d11.samplerAnisotropy` and diff --git a/docs/development/low-memory.md b/docs/development/low-memory.md index 218d1fd8e9..50e78363ef 100644 --- a/docs/development/low-memory.md +++ b/docs/development/low-memory.md @@ -99,10 +99,16 @@ available. ## Threads -Page-out never runs on a thread of the game. The preload's signal handler only wakes its -`zr-worker` thread, which does the `madvise` calls. A forked process -without a worker trims inline in steps of at most 32 MiB per request and looks at no more -than 512 MiB of its address space each time. The page-out for a suspend and the read-back +When a worker can be started, page-out runs outside the game's threads. The preload's signal +handler starts a `zr-worker` thread for the request, which does the `madvise` calls and exits once no request +is left, so a process that is not paging out has no thread the preload added. Programs that +check they are single-threaded before they fork or call `unshare(CLONE_NEWUSER)`, such as +Chromium's zygote, keep working. The worker is a bare `clone` with the flags of a normal +thread, on a stack the preload maps itself, and makes only raw system calls, so starting it +from the signal handler is safe and seccomp filters that only allow thread clones accept it. A +process that has a single thread, or whose signalled thread added a seccomp filter after the +process started, as browser sandboxes do, gets no worker. When there is no worker, the process trims inline in steps of at most 32 MiB per request and +looks at no more than 512 MiB of its address space each time. The page-out for a suspend and the read-back after it are not limited there: they run once, while the process is being stopped or started, and cover all of it. The monitor is a shell loop in the session, outside every game process. diff --git a/docs/development/mali-venus.md b/docs/development/mali-venus.md index caf0d2db70..5cdc4ab39f 100644 --- a/docs/development/mali-venus.md +++ b/docs/development/mali-venus.md @@ -128,10 +128,32 @@ What it does, per feature: - Pipelines and `vkCmdSetColorBlendEquationEXT` both. - Why alpha: output 0's color is the paint, its alpha is the usual coverage. Per-channel coverage collapses to one value; blending stays plain alpha blending, not tinted by the paint. +The SPIR-V version the driver gets: +- The phone's own driver compiles the guest's SPIR-V, and its compiler is old: on the MT6897 + Mali-G615 (r44p1, "Vulkan 1.3.247") it dies with a null read in `cmpbe_v2_compile_multiple_shaders` + while compiling a pipeline, and the render server dies with it, so every guest client that + draws loses its device. +- Zink writes SPIR-V 1.6 for any Vulkan 1.3 device (`zink_screen.c`: `spirv_version` from the + device's version), and SPIR-V 1.4 changed the entry point's interface: it has to list every + global variable, not only the input and output ones. +- The layer therefore lowers every module to SPIR-V 1.3 before the driver sees it: the version + word, the interface list (back to the input and output variables) and `OpTerminateInvocation` + (SPIR-V 1.6's name for `OpKill`). This covers shader modules, and code given inline to + graphics and compute pipelines. +- A module that uses something 1.3 cannot express is left alone and the layer says so in its + log: a `ShaderViewportIndex` capability, the Vulkan memory model, `OpCopyLogical`, an + `OpSelect` of a structure or array, the newer loop controls and image operands, or a + capability, decoration or instruction that became core later without the extension 1.3 + needs for it (`ShaderNonUniform` without `SPV_EXT_descriptor_indexing`). +- The version cap runs on every device the layer is active on; clip and cull distances are + only taken out where the layer emulates them. `DROIDDECK_MALI_COMPAT=0` turns both off. +- This is what Dawn ("Disable SPIR-V 1.4 on Android ARM"), ANGLE (`supportsSPIRV14`) and naga + (`AVOID_SPIRV_COPY_LOGICAL`) do for a proprietary compiler they cannot trust. + Files: - `layer.c`: loader plumbing, feature and limit reporting, device creation, the hook table. - `pipeline.c`: pipelines, shader modules, viewports. -- `spirv.c`: the SPIR-V rewriter for clip and cull distances and the second blend source. +- `spirv.c`: the SPIR-V rewriter for clip and cull distances and the second blend source, and the version cap. - `bc.c`: BC formats, images and uploads. - `VkLayer_droiddeck_mali_compat.json`: implicit layer manifest. @@ -149,6 +171,7 @@ How it ships: Not done yet: - Unit tests for the clip and cull distance rewriter. It is untested beyond DXVK's shaders, and unknown whether Silksong's shaders used clip distances at all. - The dual-source rewrite has them: `tools/tests/test_mali_compat_layer.py`. + - The version cap has them: `tools/tests/test_mali_compat_spirv.py`. - Performance: BC decoding on the CPU makes loads slow. A compute-shader decoder would be the next step. ## Changes on the branch diff --git a/docs/development/memory-guard-ab.md b/docs/development/memory-guard-ab.md index 4ac8d1a214..ded09a59f4 100644 --- a/docs/development/memory-guard-ab.md +++ b/docs/development/memory-guard-ab.md @@ -1,20 +1,24 @@ # Keep-top guard A/B on dual screens -`KeepTopActivity` (#2763) covers every other display while a session is on top, so that -display's home is not its top activity. On the Thor, lmkd kills the bottom home under memory -pressure, Android relaunches it to the front (`wm_task_to_front`), the session loses the top -spot, drops to adj 50 and is killed in lmkd's next pass. +`KeepTopActivity` (#2763, removed in the change that added this section) covered every other +display while a session was on top, so that display's home was not its top activity. The +reasoning: on the Thor, lmkd kills the bottom home under memory pressure, Android relaunches it +to the front, the session loses the top spot, drops to adj 50 and is killed next. -Android gives a translucent activity that is alone in its task an `ActivityRecordInputSink` -that consumes every touch inside the task bounds, whatever the window's flags say -(`ENABLE_TOUCH_OPAQUE_ACTIVITIES`, on for DroidDeck's target SDK; see -`services/core/java/com/android/server/wm/ActivityRecordInputSink.java`). The guard's -`FLAG_NOT_TOUCHABLE` therefore did nothing: with the dual-screen panel closed, the bottom -screen took no touch until the session ended, and the guard also stayed over it after Home. +It had three side effects: -The guard now takes touches itself. A touch removes it from that display. It comes back when -the session is top-resumed again, or after 5 s if the session kept the top spot (one touch on -the bottom screen, then back to the game). Stopping or entering PiP removes the guards. +- Android gives a translucent activity alone in its task an `ActivityRecordInputSink` that + consumes every touch in the task bounds whatever the window's flags say + (`ENABLE_TOUCH_OPAQUE_ACTIVITIES`), so the bottom screen took no touch (#2910 worked around it). +- Cocoon tracks the top activity of each display; with a DroidDeck activity on the bottom it + could not suspend or resume DroidDeck properly. +- The Thor's `com.odin.gameassistant` gives every app with an activity on top of the bottom + display that display's volume (`secondary_screen_volume_level`). With the guard up, all of + DroidDeck's audio played at the bottom screen's volume (AudioFlinger track gain -37, -13 and + -2.6 dB at levels 3, 8 and 13; -7.4 dB, the top level, once the guard was removed). + +The A/B below found no case on either device where the guard kept the session alive, so it was +removed. ## Tool @@ -25,6 +29,7 @@ build that has the debugging tools: python3 tools/memory_guard_ab.py --label main --apk main.apk states python3 tools/memory_guard_ab.py --label fix --apk fix.apk states python3 tools/memory_guard_ab.py --label fix pressure --stop-mb 650 --hold 30 --runs 3 +python3 tools/memory_guard_ab.py --label fix pressure --burst --stop-mb 1500 --hold 20 --runs 3 python3 tools/memory_guard_ab.py --label fix summarize ~/.cache/droiddeck-memory-guard-ab/fix-stop650-1-events.txt ``` @@ -39,6 +44,13 @@ event log of every probe. `--stop-mb`, holds it, and releases it. zram cannot compress that data and no app owns it, so lmkd keeps killing by adj. It records lmkd's `killinfo`, process deaths, focus loss and whether DroidDeck survived. +- `pressure --burst` takes everything above `--stop-mb` at once instead: it copies a 256 MiB + random file into the tmpfs with all copies running in parallel (about 5 GiB in 2 to 3 s on a + Thor), the way a game's GPU allocation burst lands on lmkd. +- `oom_score_adj` is read without `su`. Under pressure lmkd keeps killing the root manager app, + and a `su` call can then open its request screen on top of the game. +- If the bottom display has no home (a killed home is not always restarted), the visible app on + top of it stands in. - `--bottom-tap` must point at an inert spot of the bottom home; `--panel-close` at the panel's close button. Both are fractions of the bottom display. - `am start` of `SessionActivity` needs `--display 0`; without it, it creates a second @@ -88,3 +100,24 @@ moves it to the front, even with no guard. The Thor's focus steal does not happe Duo shows that the guard covers the same states as before, not that it saves the session. That needs a Thor: run `states` and `pressure --stop-mb` near its adj-50 level on `main` and on the fix, and look for `task_to_front` and `session_top_lost` before `droiddeck_died_at_adj` 50. + +## Results: AYN Thor (12 GB), Android 13 + +Builds: `main` (56986b5, guard with the #2910 touch yield) and `no-guard` (`main` with +`guardOtherDisplays` returning at once). The game was focused on the top screen in every run. + +| Pressure | Bottom app | no-guard | main | +| --- | --- | --- | --- | +| Fill to 650 MB free, hold 30 s | stock launcher | survived 1/1 usable run (launcher not reached) | survived 3/3 (launcher killed 80, 25, 0 times) | +| Fill to 550 MB free, hold 30 s | Cocoon as home | survived 3/3, Cocoon killed 387, 400, 84 times | survived 3/3, Cocoon killed 384, 127, 338 times | +| Burst to 400 MB free (about 5 GB in 2.5 to 3.4 s) | stock launcher | killed at adj 0 in 3/3 | killed at adj 0 in 3/3 | +| Burst to 1500 MB free (2.0 to 2.4 s) | stock launcher | survived 1/2, killed at adj 0 in 1/2 | killed at adj 0 in 2/2 | + +No run on either build lost the top spot (`wm_on_top_resumed_lost_called` for +`SessionActivity`), moved a task to the front, or killed DroidDeck at adj 50. A killed bottom +home is either restarted in place or its task disappears and the next app shows on the bottom +screen, without taking focus. A burst big enough to matter makes lmkd kill the foreground +session at adj 0, which no activity on another display can prevent. + +`kill -9` of the bottom app (`states`) is noisy on a Thor with many recent apps: each kill +surfaces the next app on the bottom screen, and every tap the tool sends there moves focus. diff --git a/docs/development/steam-display-scaling.md b/docs/development/steam-display-scaling.md index a5c5a674f0..a0594fb0d7 100644 --- a/docs/development/steam-display-scaling.md +++ b/docs/development/steam-display-scaling.md @@ -215,6 +215,15 @@ Still to check by hand: pasting Android text into a game. Force fullscreen is still unsafe without a matching Game Resolution: with the default (native), a game drawing at another size fights it as in run 4. It stays off by default. +## Stretch 16:9 with two Xwayland servers + +With "Stretch 16:9 to panel" the games' server starts at the 16:9 nested size, but the client sets it +to the output size at every launch (run 7), so games saw a near-square screen and letterboxed +themselves. While stretching, the session script rewrites a `GAMESCOPE_XWAYLAND_MODE_CONTROL` that +sizes the game server (`1`) to exactly the output into the nested size with `allow_super_res` set, +since gamescope otherwise clamps it to the output. A Game Resolution chosen in Steam is a different +size and is kept. + ## Force fullscreen removed (`feat/remove-force-fullscreen`) With games on their own Xwayland server, FlatOut 2 no longer shrinks under the QAM, which was the diff --git a/docs/development/steam-game-imports.md b/docs/development/steam-game-imports.md index 52d69934fc..5ebaf5cdfd 100644 --- a/docs/development/steam-game-imports.md +++ b/docs/development/steam-game-imports.md @@ -60,7 +60,9 @@ missing prefix is removed first, and nothing is copied. The account's `.droiddeck-routes.json` maps shortcut IDs to real Steam app IDs so the Android launcher uses the same title and Proton prefix as Steam. Other accounts do not -inherit those routes. Managed shortcuts are replaced; user-created shortcuts and +inherit those routes. A program chosen in DroidDeck other than the folder's default executable (for example a mod +launcher beside the game's own executable) is never routed: it stays its own shortcut and tile. +A target set in the Steam shortcut's properties keeps the route. Managed shortcuts are replaced; user-created shortcuts and unreadable shortcut files are preserved. Both routes use the existing ARM64 Proton registration. diff --git a/docs/development/stores.md b/docs/development/stores.md index 9776ac8c4c..16fdf66bc5 100644 --- a/docs/development/stores.md +++ b/docs/development/stores.md @@ -197,6 +197,13 @@ The appid Steam derives (CRC32 of the quoted exe plus the name, high bit set) is listing carries, so the live add and the writer never disagree. Uninstall removes the folder and the listing drops the entry; the live client is asked to remove it too. +`droiddeck-steam-shortcuts` merges each entry against the one Steam holds: a Target or Start In +edited in Steam survives the client's restart. A target whose file is gone is not an edit to keep - +it can only fail before the game starts - so the listing's exe replaces it, checked in the guest +where the shortcut's paths live, as long as the folder holding it exists (a missing folder can be an +unmounted card). #694 was a hand-typed Target that outlived the game update that removed its file, +so every launch died with Wine's `Failed to create process ...: 2` before the game ran. + `Library.SteamGame.source` is `steam`, `gog`, `epic`, `amazon` or `added`; the Library shows it as a chip on every tile and in the hero, and filters by it. diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 7679a0a6c8..1a02e3420f 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -131,6 +131,18 @@ The client's web helper draws its whole UI. There are two: blank. `LinuxRuntime` binds an empty folder over `/sys/bus/pci/devices` on such devices; device: 0 GPU process exits, ANGLE on zink and Turnip. +FEX ships per-program AppConfigs, and `/usr/local/share/fex-emu/AppConfig/steamwebhelper.json` turns +the GL thunk off for every program named `steamwebhelper`. A program's AppConfig is read after +`FEX_THUNKCONFIG`, so the x86 helper got the rootfs's x86 Mesa while the client next to it had the +thunk. Steam's browser compositor creates its output window through SDL3 and GLX in the helper's +browser process, and x86 Mesa's `driCreateNewScreen3` (kisak libgallium 26.1.6) faulted there +(SIGSEGV, exit 139) about 11 s after every start; the client restarted it each time (device: 57 +restarts in 11 minutes). `x64_env` therefore writes, for every global AppConfig that turns off a +thunk the session uses, a local AppConfig (`$X64_HOME/.config/fex-emu/AppConfig/<name>.json`, read +after the global one) with the session's thunk set. It never touches a local file with other content, +so a user's own AppConfig wins, and removes its own files when the client runs in software. Device: +helper up for over 10 minutes with no restart, ANGLE on zink and Turnip through the thunk. + The session shim (`preload/net.c`) turns `steamrt64/steamwebhelper.sh`'s exec of `./steamwebhelper` into `DD_X64_ARM_WEBHELPER`. Nothing in the client's folder is edited: the client checksums its files as it starts and reinstalled itself over an edited launcher (2-3 minutes) on every start. @@ -197,13 +209,109 @@ alone would then read as an installed client. restarted from the top forever (found with `perf_event_open` IP sampling, since proot holds ptrace). Such a range is now skipped whole and a second exhausted scan returns `-ENOMEM`, as the kernel does (`fex-2610-r3`). + - `0006-smc-alias-of-code-created-after-translation`: a JIT with a double-mapped memfd (CoreCLR's + W^X allocator) maps its writable alias after the executable alias was translated. Under + `SMCChecks=mtrack` the new alias was not write-protected, so writes through it never faulted and + never invalidated the translated code; x86-64 .NET programs ran stale code (access violations, + NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the + overlapping part of any alias that is already executable, so the first write faults and invalidates. + `FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch. + - `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to + `install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure. + The guest libraries are external projects in the default build, which `install` already follows. + - `0008-signal-return-restores-syscall-state`: a guest `rt_sigreturn` is a system call, so FEX's + syscall stub marks every static register as spilled (`InSyscallInfo = 0xFFFF`). When the handler + left RIP alone, the return resumed the interrupted JIT code without passing the stub's reset, and + the mark stayed. Every asynchronous signal after that (until the next system call ended) skipped the + register spill and handed the guest handler stale registers from the last system call: only RIP was + right. CoreCLR suspends threads for the GC with such signals and reads or redirects the interrupted + context, so x86-64 .NET programs failed at random (`AccessViolationException` in whatever code ran + next, then SIGABRT). `tools/fex/probes/async-signal-context.c` shows it: under FEX-2611.1 one signal in + 2000 carried the interrupted registers, natively all of them. The return now restores the value saved + when the signal arrived, and only when the signal interrupted JIT code, which is the only case that + saves it. Restoring it for a signal that interrupted a system call cleared the mark while that call + was still running, so the next signal in the call's return path spilled clobbered registers: + `setitimer` at 100 Hz around `time()` crashed in 15 of 15 runs, and with the guard as often as the + same build without the patch (about half; a separate crash that FEX-2611.1 also shows). + - `0009-signal-handler-escape-frees-host-stack`: FEX keeps each signal's host context on the host + stack and frees it only on `rt_sigreturn`. A guest that leaves its handler another way (`siglongjmp`, + or CoreCLR resuming a `catch` after a NullReferenceException) left that 2 KB block and one + `SignalHandlerRefCounter` count behind. About 3500 such exceptions on one thread overran the 8 MB + host stack, which has no guard page, and the CurseForge agent died with "Internal CLR error. + (0x80131506)" and "Stack overflow occurred on the same thread again!" at the start of its second + addon scan. FEX now chains each thread's signal frames with the guest frame range and alternate + stack they used. When a signal arrives in JIT code that runs at the host level of the newest frame + and the guest stack pointer shows the guest has left that frame (above its frame, or back off the + alternate stack above where the outermost frame on it interrupted), the left frames are dropped and + the new context is stored where the newest live frame (or the dispatcher entry) left the host stack. + `rt_sigreturn` pops its frame and any newer ones it skips. Signals that arrive inside system calls or + thunk callbacks are left alone. `tools/fex/probes/signal-handler-escape.c` leaves handlers on and + off the alternate stack, mixes them with handlers that return, and leaves nested handlers: FEX-2611.1 + with 0001 to 0008 crashed (SIGSEGV) before 2000 iterations of it, and `siglongjmp` out of a SIGSEGV + handler died after about 3500; with this patch 350000 escapes and 200000 straight `siglongjmp`s + finish, as natively. The approach is the one suggested in FEX-Emu/FEX#2487. + - `0010-syscall-exit-resets-host-stack` (`Fixed-upstream: FEX-2612`): a backport of FEX's + "JIT: Ensure IR ops that jump out of the JIT reset the stack" (FEX-Emu/FEX#6122). A system call or + code-entry removal that ends a block jumps to the dispatcher without dropping the block's spill + slots, and the syscall handler's fast path branches straight into the next block, so every such + exit leaked up to 32 bytes per spill slot of host stack. AVX and MMX code keeps enough values live to + spill, and `tools/fex/probes/syscall-host-stack.c` overran the 8 MB host stack after about 65000 + system calls; with the patch 2000000 finish, as natively. The CPUID hunk of the upstream commit is + left out, since CPUID returns to the JIT in 2611. + - `0011-thunk-calls-mark-spilled-state`: a thunk call (every vDSO `clock_gettime`, `gettimeofday` + and `time`, and the host library thunks) spills the static registers to the guest frame and calls + host code, which clobbers the caller-saved host registers. A signal that arrived in the JIT code + after the host call returned and before the registers were refilled took the interrupted state from + those clobbered host registers: the guest handler got garbage registers, and the interrupted code + resumed with them, or FEX built the signal frame at a garbage stack pointer and crashed. The thunk + call now marks every static register as spilled (`InSyscallInfo = 0xFFFF`, as the system call + handler does) until the refill ends, and a fully spilled mark takes only RIP from the host PC and + leaves the frame's GPRs, vector registers and flags alone (the 16-bit mask could not name the + x16/x17 and v16 to v31 registers the host call clobbers). Every guest signal now saves and clears the + mark, so guest handlers and nested signals never inherit it, and every return puts back the value it + saved; 0008 restored it only for JIT code because the other paths saved none. A handler that changes + RIP restarts at the dispatcher with no mark, and thunk callbacks into guest code run with none. + `tools/fex/probes/vdso-signal-state.c` calls `clock_gettime` under a 1 kHz `SIGALRM` and checks the + values held across each call: FEX-2611 crashed in 3 of 8 runs, with 0001 to 0010 in 7 of 8; with + this patch 0 of 28, as natively. This was the "separate crash" noted under 0008. + - `0012-signal-return-applies-guest-registers`: a signal return that kept RIP threw away every + register change the guest handler made in its `ucontext`; only a changed RIP made FEX reload the + guest state from it. CoreCLR suspends threads for garbage collection with a signal and, in fully + interruptible code, runs the collection from that handler and writes the moved object references + back into the interrupted registers, so under FEX the thread resumed with pointers into the old heap. + The CurseForge agent's crashes during parallel addon scans (an `AccessViolationException` in + `Curse.Hashing.MurmurHash2.ComputeHash` or `RegexInterpreter`, or "Internal CLR error. (0x80131506)" + with a stack overflow) look like this, but they still happen with this patch, so it is not a fix for + them. When RIP is + unchanged, each guest GPR the handler changed is now written where the resumed code reads it: the + guest frame for registers the interrupted code had spilled (all of them inside a system call or + thunk call), otherwise the static host register. Unchanged registers are left alone, signals that + interrupted code outside the JIT (and not inside a system call or thunk call) keep the old + behaviour, and 32-bit frames compare and write only the low 32 bits. `tools/fex/probes/signal-register-update.c` + spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames): + FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all + three see it on the first signal, as natively. + - `0013-path-syscalls-through-libc`: FEX passes most path system calls of the guest (`mkdirat`, + `unlinkat`, `renameat`, `renameat2`, `symlinkat`, `linkat`, `mknodat`, `fchmodat`, `fchmodat2`, + `fchownat`, `utimensat`, `truncate`, `chdir`, `chroot`, `inotify_add_watch`) straight to the kernel + with an inline `svc`, which the native userland's path hook never sees, so an x86-64 program wrote + `/opt/...` or `/root/...` to the Android root instead of the rootfs, and `cd` into a rootfs folder + failed. They now go through libc's `syscall()`, which the hook maps like every other path; without + the hook it is the same system call. `tools/tests/test_native_hook_path_syscalls.py` checks the hook + side, including that an allocator which opens files before the hook has started does not hang. + FEX also mirrors each guest signal handler with `syscall(SYS_rt_sigaction, ...)`; for `SIGSYS` the + hook records the guest handler as it does for `sigaction()` and keeps its own installed, so a + program that sets a crash handler is no longer killed by the next blocked system call + (`tools/tests/test_native_hook_sigsys_mask.py`). - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, checks the digest GitHub stored, and records the build's version, sha256 and size in its `fex.json` (in that order: a device that reads the old `fex.json` meanwhile gets a mismatching archive and keeps its FEX). This repository's `build-fex.yml` only builds `tools/fex` when it changes (and on dispatch, - for diagnostic builds such as `-DDEBUG_STRACE`); nothing is published from it. + for diagnostic builds such as `-DDEBUG_STRACE`); nothing is published from it. It builds FEX's latest + release, point releases (`FEX-2611.1`) included; `build-in-arch.sh` takes the tag from `FEX_VERSION` + and compares only its four-digit release against a patch's `Fixed-upstream`. - Releases so far: `fex-2609-r2` (no thunks), `fex-2609-r3` (thunks), `fex-2610-r1`, `fex-2610-r2`, `fex-2610-r3`, `fex-2610-r4` (in-root resolution when openat2 is missing, exact MAP_32BIT marking), `fex-2610-r5` (current: bundles libxxhash, which the Linux runtime does not ship; the diff --git a/docs/development/xreal-investigation.md b/docs/development/xreal-investigation.md index bcad031461..8e75819b60 100644 --- a/docs/development/xreal-investigation.md +++ b/docs/development/xreal-investigation.md @@ -240,3 +240,65 @@ extended gameplay stability need hardware validation. One successful view/motion check does not establish long-session stability. Users must select Follow mode and disable the glasses' own stabilization. Factory calibration and XREAL Eye/6DoF are not implemented. One Pro is not enabled or claimed as tested. + +## Native 1 Pro+ implementation and hardware validation — 2026-11-13 + +The attached device identifies as USB `3318:0444`, product `XREAL 1 Pro+`. This exact +identity enables the experimental 1 Pro+ profile alongside the existing 1S profile. +The [official specifications](https://tutorials.xreal.com/docs/glasses/pro-plus/specifications/) +give 1920×1080 per eye and a 57° diagonal field of view. The direct Kotlin driver +uses the USB-Ethernet control and IMU services; it requires no XREAL SDK or +ControlGlasses installation and includes no vendor SDK binaries or headers. + +Verified on the connected phone and glasses: + +| Observation | Result | +| --- | --- | +| Control and IMU transport | Individually bound Android Ethernet sockets reach `169.254.2.1:52999` and `:52998` without replacing the default Internet network. | +| Native display | `GET_DISPLAY` (`0x275e`) returns **9**, with Android reporting **1920×1080 at 60 Hz**. This profile preserves mode 9 for native 60 Hz instead of the 1S's mode 29. | +| Legacy 60 Hz command | Setting mode **2** is rejected with status **10001**. A rejected command does not count as a successful display switch. | +| Higher refresh commands | Setting modes **3** and **4** through DroidDeck selects physical **1920×1080 at 90/120 Hz**, confirmed through Android's active display mode. | +| Full SBS | `SET_INPUT` (`0x2822`) with value **1** settles at display mode **5** and Android **3840×1080 at 60 Hz**. Value **0** restores native mode **9**; DroidDeck then restores the saved 90 Hz preference. Tracking resumed after both switches. | +| IMU | Type **11** raw sensor reports arrive at approximately **1,000 Hz**, using the existing 128-byte body layout. | + +Mode 9 is an observed native display configuration, not a general mapping from +EDID number to the physical refresh rate selected by every host. The older +[xr-tools enum](https://github.com/0xcaff/xr-tools/blob/main/packages/xreal_one_driver/src/proto/net/dp_get_current_edid_dsp.rs) +contains only modes 2–5. The independent +[one-xr investigation](https://github.com/Skarian/one-xr/blob/main/docs/UNRESOLVED.md) +also records mode 9 and mode-2 rejection status 10001 on other firmware. This +supports keeping display mappings per model and confirming output through Android. + +The Pro+ profile applies a nominal **+35° rotation around X** to both gyro and +acceleration before fusion, inverting the factory display-to-IMU mounting +direction. Directed wearer captures separately establish the sign: horizontal +turns primarily rotate around corrected Y, and shoulder tilts around corrected Z. +The initial opposite-sign correction mixed these axes; a stationary capture alone +could not distinguish sensor mounting from the physical angle of the glasses. +This is a model mounting correction, not individually calibrated tracking. Device +calibration data and serial numbers are not stored in the repository. After the +corrected build was installed, the wearer confirmed all three rotation directions +and the horizon were correct. The existing 1S mapping stays unchanged. + +The initial APK build and 621 targeted glasses/UI tests completed with zero failures +and one skipped test. After correcting the mounting direction, all 73 focused +XREAL/routing tests passed, including a regression using the measured movement +axes. Native dependency checks passed and the APK contains no vendor +SDK libraries. On this phone, background network restrictions interrupted the +glasses sockets while DroidDeck was away from the foreground; foreground operation +recovered. Sustained background use needs separate validation. + +Brightness remains limited to the known protocol values **0–9**. XREAL's +[display guide](https://tutorials.xreal.com/docs/glasses/pro-plus/display-sound/) +documents 14 physical levels in Follow mode with Stabilizer off and 10 in Anchor +or Spatial Anchor. Those counts do not establish a 0–13 direct-protocol range. +The wearer confirmed that DroidDeck's brightness and dimming controls work on the +Pro+. The wider brightness API mapping remains unverified. + +Use **Follow** with **Stabilizer off** in the glasses' own menu before using +DroidDeck tracking, following the official +[display-mode](https://tutorials.xreal.com/docs/glasses/pro-plus/spatial-screen/display-modes/) +and [Stabilizer](https://tutorials.xreal.com/docs/glasses/pro-plus/spatial-screen/stabilizer-transparency/) +descriptions. The built-in tracking must not be layered over host tracking. +XREAL Eye, camera capture, and 6DoF are not implemented. Long-session stability +remains an outstanding hardware check. diff --git a/docs/progress-log.md b/docs/progress-log.md index 462affde2a..5fcfa60707 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -1449,8 +1449,9 @@ State: **main = `90c7574`** (PR #14 merge), main build run 35895701784. No tag, - A runtime script must be named `bannerlator-*` or CI never packages it. - `gh release create --target` needs the full sha. - A proot bind is invisible to a program's "Computer" list; put what users need under home. -- The compositor decides its driver and its HDR gate once per app process - anything that changes - them applies after the app is fully closed, and the UI must say so. +- The compositor decides its driver once per app process - anything that changes it applies after + the app is fully closed, and the UI must say so. Its HDR gate follows what the device can present, + so the HDR setting itself switches during a session. - Bannerlator's File Manager ports mechanically (`port_fm.py` anchors) once the container hooks are cut; do not hand-edit 2,500 lines. - Deleting a release asset on GitHub can drop a sibling asset - re-list and restore. diff --git a/docs/settings-map.md b/docs/settings-map.md index cfbdf196de..bcef3a25c3 100644 --- a/docs/settings-map.md +++ b/docs/settings-map.md @@ -44,6 +44,8 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc | Launcher orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait | | Session orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait | | Fullscreen | Settings › Launcher (`droiddeck://settings/launcher`) | | +| Swipe between pages | Settings › Launcher (`droiddeck://settings/launcher`) | gesture | +| Controller haptics | Settings › Launcher (`droiddeck://settings/launcher`) | vibration, rumble | | Dual screen launcher | Settings › Launcher (`droiddeck://settings/launcher`) | thor, second screen, bottom screen | | Warn when storage is low | Settings › Launcher (`droiddeck://settings/launcher`) | | | SteamGridDB API key | Settings › Launcher (`droiddeck://settings/launcher`) | artwork, steamgriddb | @@ -63,6 +65,8 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc | --- | --- | --- | | Storage | Tabs › Storage | sd card, space, uninstall, disk | | Syncthing | Tabs › Syncthing | syncthing, saves | +| Decky | Tabs › Decky | plugins, plugin store, homebrew, loader | +| Boot movies | Tabs › Boot movies | startup movie, boot video, animation, steamdeckrepo | | Download speed tier | Tabs › Downloads | download, speed, bandwidth, slow | | Downloads at a time | Tabs › Downloads | download, parallel, queue, at once | | Tabs | Tabs › More | tabs, hide, reorder, agent, stores, edit tabs | @@ -94,7 +98,7 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc | Setting | Where | Also matches | | --- | --- | --- | -| Session display | Steam or Desktop options (swipe up) › Display | resolution, scaling, hdr, refresh | +| Session display | Steam or Desktop options (swipe up) › Display | resolution, scaling, hdr, refresh, zero-copy | | Graphics drivers | Steam or Desktop options (swipe up) › Display | turnip, driver, gpu, adreno, mali | | Offline mode | Steam or Desktop options (swipe up) › Steam | offline, steam | | Microphone | Steam or Desktop options (swipe up) › Audio | microphone, voice | diff --git a/docs/smart-glasses-support.md b/docs/smart-glasses-support.md index 123c1451c7..36137c9aa7 100644 --- a/docs/smart-glasses-support.md +++ b/docs/smart-glasses-support.md @@ -22,7 +22,7 @@ This describes the integrations implemented in DroidDeck as of 2026-10-24. A rec | **VITURE Luma Ultra** | SDK-dependent Carina transport | Yes | **Experimental, opt-in** | **Experimental, opt-in** | | Recognized RayNeo / TCL Air-series devices | Integrated RayNeo USB transport | Yes, with orientation calibration controls | No | No | | RayNeo GT-series devices matching the supported USB identity, including GT Max identification | Integrated GT USB/IMU path | Yes, with orientation calibration controls | No | No | -| **XREAL 1S, One, One Pro, One Pro+, Aura** | **Experimental**; exact USB identity plus the device's USB-Ethernet control/IMU connection. Head tracking and 2D/3D switching are tested on the Aura | Yes, when that connection is ready | No | No | +| **XREAL 1S, One, One Pro, One Pro+, Aura** | **Experimental**; exact USB identity plus the device's USB-Ethernet control/IMU connection. Head tracking and 2D/3D switching are tested on the Aura and One Pro+ | Yes, when that connection is ready | No | No | | Rokid Max / Max 2; Rokid Air under the Max USB identity | Integrated Rokid USB transport (vendor control requests and HID IMU reports) | Yes | No | No | | Other XREAL models (Air family and others); unrecognized glasses; display adapters and docks | Display-only where Android exposes a usable display; automatic glasses routing also requires display recognition | No supported app tracking connection | No | No | @@ -43,7 +43,8 @@ All display modes depend on the phone's video output, the cable/adapter, and And | VITURE Pro 2 | 1080p per eye; 2D and SBS | Brightness and volume; no electrochromic-film control | | RayNeo Air/GT | 2D/SBS switching; resolution and refresh follow available Android modes | Orientation calibration; no app brightness, volume, or dimming commands | | XREAL 1S | Supported 1S display-mode commands, including native 1200p/60 Hz and SBS | Brightness and dimming toggle; no app volume command | -| XREAL One, One Pro, One Pro+, Aura | 2D and SBS only, switched with the glasses' 3D input command; the display-mode set command is never sent (an unexpected index reboots the Aura) | No app brightness, dimming or volume commands | +| XREAL One Pro+ | Verified 1920×1080 at 60/90/120 Hz; 3840×1080 SBS at 60 Hz. Native 60 Hz uses mode 9; 1S-only modes 2/29 are rejected | Brightness 0–9 and dimming toggle verified; no app volume command | +| XREAL One, One Pro, Aura | 2D and SBS only, switched with the glasses' 3D input command; the display-mode set command is never sent (an unexpected index reboots the Aura) | No app brightness, dimming or volume commands | | Rokid Max / Max 2 | 1080p at 60 or 120 Hz in 2D; SBS at 1080p/60, 1200p/60, or 1200p/90 | Brightness; volume follows Android's USB audio volume; no dimming film | | Rokid Air | 1080p/60 in 2D and SBS | Brightness; volume follows Android's USB audio volume | @@ -55,6 +56,8 @@ With **game on glasses** the compositor draws the guest pointer into its own sce The pointer is left out of the picture when it cannot be drawn where the game is: while a game holds the pointer lock (it draws its own), and for a game the compositor cannot import — an AHardwareBuffer-only surface, or HDR frames it has no texture for. Those games stay on their own display layer, because composing the scene would drop the game itself. An importable HDR game that would otherwise stay on its own layer is composed through the screen swapchain, so there the pointer does fit. +The One Pro+ uses a verified sensor mounting correction for both gyro and acceleration. The wearer confirmed all three tracking axes, a level horizon, brightness and dimming on a Fold7. Use Follow mode with Stabilizer off. These checks do not establish long-session stability; see the [hardware validation](development/xreal-investigation.md#native-1-pro-implementation-and-hardware-validation--2026-11-13). + ## Setup and app-wide behavior 1. Connect the glasses through a compatible video/data connection. Accept USB access when requested. For XREAL 1S, One, One Pro, One Pro+ and Aura, Android must also expose the glasses' USB-Ethernet network; the app leaves Steam's Internet connection on its normal network. diff --git a/gradle.properties b/gradle.properties index 3289cc4c5d..16bca3f56d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,6 +4,5 @@ org.gradle.configuration-cache=true org.gradle.parallel=true android.useAndroidX=true android.nonTransitiveRClass=true -ndkVersion=27.3.13750724 org.gradle.tooling.parallel=true diff --git a/tools/build_local.sh b/tools/build_local.sh index 6f8d004ffa..b5d15acea6 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -24,6 +24,7 @@ java_dir="${JAVA_HOME:-/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents [[ -x "$java_dir/bin/java" ]] || java_dir="${HOME}/.local/share/mise/installs/java/temurin-17" [[ "$java_dir" == */homebrew/* ]] && echo "using homebrew java path: $java_dir" [[ "$java_dir" == */mise/* ]] && echo "using mise java path: $java_dir" +requested_image=${DROIDDECK_BUILD_IMAGE:-} . "${repo_root}/tools/docker_platform.sh" image_name=${DROIDDECK_BUILD_IMAGE} build_variant=${DROIDDECK_BUILD_VARIANT:-release} @@ -63,6 +64,11 @@ fi ndk_version=${DROIDDECK_NDK_VERSION:-} if [[ -z "${ndk_version}" ]]; then + . "${repo_root}/tools/ci/toolchains.env" + [[ -d "${sdk_dir}/ndk/${CI_ANDROID_NDK_VERSION}" ]] && ndk_version=${CI_ANDROID_NDK_VERSION} +fi +if [[ -z "${ndk_version}" ]]; then + echo "NDK ${CI_ANDROID_NDK_VERSION} (tools/ci/toolchains.env) is not installed; using the newest NDK instead, so native caches will not match CI." >&2 ndk_path=$(find "${sdk_dir}/ndk" -mindepth 2 -maxdepth 2 -name source.properties -print | xargs -n1 dirname | sort -V | tail -1) ndk_version=${ndk_path##*/} fi @@ -112,93 +118,6 @@ save_step() { python3 "${repo_root}/tools/docker_preflight.py" "${image_name}" image_id=$(docker image inspect --format '{{.Id}}' "${image_name}") -rm -rf -- "${linuxfs_dir}" -mkdir -p "${linuxfs_dir}" - -git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir) -docker run --rm --platform "${docker_platform}" \ - --user "$(id -u):$(id -g)" \ - -v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc ' - set -euo pipefail - d=app/src/main/assets/linuxfs - mkdir -p "$d" - put() { mkdir -p "$(dirname "$2")" && cat "$1" > "$2"; } - aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \ - -pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \ - -o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so" - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so" - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so" - bash tools/nativeguest/build.sh "$d/libddnatv-hook.so" - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \ - -fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c - aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so" - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so" - mkdir -p "$d/usr/local/lib/droiddeck-xclipse" - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \ - -o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" - install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/" - mkdir -p "$d/usr/local/bin" - external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc - aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe" - aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard" - for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do - put "$script" "$d/usr/local/bin/$(basename "$script")" - done - for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do - [ -f "$f" ] && put "$f" "$d/${f#tools/linuxfs/overlay/}" - done - put tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop" - put tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu" - put tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu" - put tools/linuxfs/desktop/kwin_wayland_wrapper "$d/usr/local/bin/kwin_wayland_wrapper" - put tools/linuxfs/desktop/firefox-droiddeck.js \ - "$d/usr/lib/firefox/defaults/pref/droiddeck.js" - - READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d" - ' - -x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \ - app/src/main/cpp/fakeinput_steam.cpp) -x86_stage="${staging_dir}/x86-preloads" -if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else - docker run --rm --platform linux/amd64 \ - -v "${repo_root}:/src" -v "${git_common}:${git_common}" -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 - DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null - tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs - chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs - ' - mkdir -p "${x86_stage}" - cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/" - save_step x86-preloads "${x86_key}" "${x86_stage}" -fi - -vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr" -vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c) -if ! restore_step vr "${vr_key}" "${vr_out}"; then - DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}" - save_step vr "${vr_key}" "${vr_out}" -fi - -gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload" -gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload) -if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then - DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}" - save_step gpuload "${gpuload_key}" "${gpuload_out}" -fi - github_repo=${DROIDDECK_GITHUB_REPOSITORY:-} if [[ -z "${github_repo}" ]]; then origin_url=$(git -C "${repo_root}" remote get-url origin) @@ -215,46 +134,295 @@ if [[ -z "${github_repo}" ]]; then github_repo=${github_repo%.git} fi -cached() { - local sha=$1 name=$2 out - shift 2 - out="${cache_dir}/${sha}-${name}" - if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then - echo "${out}" - return 0 +ci_components=0 +ci_run= +ci_cache="${cache_dir}/ci-components" +reuse_ci_components() { + [[ "${DROIDDECK_CI_COMPONENTS:-1}" == 1 ]] && command -v gh >/dev/null 2>&1 || return 1 + # CI prepares with the pinned NDK, its own build image and PulseAudio source, and the system Vulkan headers. + . "${repo_root}/tools/ci/toolchains.env" + [[ "${ndk_version}" == "${CI_ANDROID_NDK_VERSION}" && -z "${DROIDDECK_PA13_SOURCE_DIR:-}" && -z "${VK_INCLUDE:-}" \ + && -z "${requested_image}" ]] || return 1 + local base candidates run artifact archive part + base=$(git -C "${repo_root}" merge-base HEAD origin/main 2>/dev/null || true) + # Only runs of this repository's own main: a fork's pull request can also name its branch main. + candidates=$(gh api "repos/${github_repo}/actions/artifacts?name=prepared-components&per_page=100" \ + -q "[.artifacts[] | select(.expired | not) | select(.workflow_run.head_branch == \"main\") + | select(.workflow_run.head_repository_id == .workflow_run.repository_id)] + | sort_by(.workflow_run.head_sha != \"${base}\") | .[:3][] | \"\(.workflow_run.id):\(.id)\"" 2>/dev/null) || return 1 + mkdir -p "${ci_cache}" + # CI keeps these artifacts for 14 days. + find "${ci_cache}" -mindepth 1 -maxdepth 1 -mtime +14 -exec rm -rf {} + + for candidate in ${candidates}; do + run=${candidate%%:*} + artifact=${candidate#*:} + archive="${ci_cache}/${artifact}.tar.gz" + if [[ ! -f "${archive}" ]]; then + part=$(mktemp -d "${ci_cache}/${run}.part.XXXXXX") + if gh run download "${run}" -R "${github_repo}" -n prepared-components -D "${part}" >/dev/null 2>&1; then + mv "${part}/prepared-components.tar.gz" "${archive}" + fi + rm -rf "${part}" + [[ -f "${archive}" ]] || continue + fi + if python3 "${repo_root}/tools/components/reuse.py" "${archive}"; then + ci_run=${run} + return 0 + fi + done + return 1 +} +fetch_ci_xbox() { + local stored="${ci_cache}/${ci_run}-xbox" part + if [[ ! -d "${stored}" ]]; then + part=$(mktemp -d "${ci_cache}/${ci_run}-xbox.part.XXXXXX") + gh run download "${ci_run}" -R "${github_repo}" -n xbox-arm64 -D "${part}" >/dev/null 2>&1 || { rm -rf "${part}"; return 1; } + # rename(2) refuses a non-empty destination, so a copy another build published first wins. + python3 -c 'import os, sys; os.rename(sys.argv[1], sys.argv[2])' "${part}" "${stored}" 2>/dev/null || rm -rf "${part}" fi - rm -f "${out}.part" - out="${out}.part" "$@" >&2 - printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2 - mv "${out}.part" "${out}" - echo "${out}" + rm -rf "${xbox_out}" && mkdir -p "${xbox_out}" && cp -R "${stored}/." "${xbox_out}/" } -if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then - . "${repo_root}/tools/gamescope/release.env" - gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \ - bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}") - zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}" - test -f "${linuxfs_dir}/usr/local/bin/gamescope" -fi +git_common=$(git -C "${repo_root}" rev-parse --path-format=absolute --git-common-dir) +proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a" +if reuse_ci_components; then + ci_components=1 + echo "components: every recipe identity matches main CI run ${ci_run}; reusing its prepared components (DROIDDECK_CI_COMPONENTS=0 builds them here)" +else + rm -rf -- "${linuxfs_dir}" + mkdir -p "${linuxfs_dir}" -. "${repo_root}/tools/linuxfs/uruntime.env" -uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \ - bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}") -mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime" -install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime" -install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE" + docker run --rm --platform "${docker_platform}" \ + --user "$(id -u):$(id -g)" \ + -v "${repo_root}:/src" -v "${git_common}:${git_common}" -w /src "${image_name}" bash -lc ' + set -euo pipefail + d=app/src/main/assets/linuxfs + mkdir -p "$d" + put() { mkdir -p "$(dirname "$2")" && cat "$1" > "$2"; } + aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \ + -pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \ + -o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so" + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ + -o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so" + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ + -o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so" + bash tools/nativeguest/build.sh "$d/libddnatv-hook.so" + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \ + -fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c + aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so" + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ + -o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so" + mkdir -p "$d/usr/local/lib/droiddeck-xclipse" + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \ + -o "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" + install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$d/usr/local/lib/droiddeck-xclipse/" + mkdir -p "$d/usr/local/bin" + external/MaliBridge/scripts/build-client-linux.sh "$d" aarch64-linux-gnu-gcc + aarch64-linux-gnu-gcc -O2 -Wall -o "$d/usr/local/bin/droiddeck-glprobe" tools/venus/glprobe.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-glprobe" + aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$d/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/usr/local/bin/droiddeck-clipboard" + for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do + put "$script" "$d/usr/local/bin/$(basename "$script")" + done + for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do + [ -f "$f" ] && put "$f" "$d/${f#tools/linuxfs/overlay/}" + done + put tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop" + put tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu" + put tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu" + put tools/linuxfs/desktop/kwin_wayland_wrapper "$d/usr/local/bin/kwin_wayland_wrapper" + put tools/linuxfs/desktop/firefox-droiddeck.js \ + "$d/usr/lib/firefox/defaults/pref/droiddeck.js" + + READELF=aarch64-linux-gnu-readelf bash tools/linuxfs/check-preloads.sh "$d" + ' + + x86_key=$(inputs_hash bullseye tools/linuxfs/build-x86-preloads.sh tools/linuxfs/preload tools/linuxfs/fex \ + app/src/main/cpp/fakeinput_steam.cpp) + x86_stage="${staging_dir}/x86-preloads" + if restore_step x86-preloads "${x86_key}" "${linuxfs_dir}"; then :; else + x86_platform=linux/amd64 + x86_packages="gcc g++ gcc-multilib g++-multilib binutils" + x86_cross=0 + if [[ "${docker_platform}" == linux/arm64 ]]; then + x86_platform=linux/arm64 + x86_packages="gcc-x86-64-linux-gnu g++-x86-64-linux-gnu gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-amd64-cross libc6-dev-i386-cross binutils-x86-64-linux-gnu binutils-i686-linux-gnu" + x86_cross=1 + fi + docker run --rm --platform "${x86_platform}" -e X86_CROSS="${x86_cross}" -e X86_PACKAGES="${x86_packages}" \ + -v "${repo_root}:/src" -v "${git_common}:${git_common}" -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 + DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends $X86_PACKAGES >/dev/null + tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs + chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs + ' + mkdir -p "${x86_stage}" + cp -R "${linuxfs_dir}/x86_64" "${linuxfs_dir}/i386" "${x86_stage}/" + save_step x86-preloads "${x86_key}" "${x86_stage}" + fi + + vr_out="${linuxfs_dir}/usr/local/lib/droiddeck-vr" + vr_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/vr app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c) + if ! restore_step vr "${vr_key}" "${vr_out}"; then + DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${vr_out}" + save_step vr "${vr_key}" "${vr_out}" + fi + + gpuload_out="${linuxfs_dir}/usr/local/lib/droiddeck-gpuload" + gpuload_key=$(inputs_hash "${image_id} ${ndk_version} ${VK_INCLUDE:-}" tools/gpuload) + if ! restore_step gpuload "${gpuload_key}" "${gpuload_out}"; then + DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/gpuload/build.sh" "${gpuload_out}" + save_step gpuload "${gpuload_key}" "${gpuload_out}" + fi + + cached() { + local sha=$1 name=$2 out + shift 2 + out="${cache_dir}/${sha}-${name}" + if [[ -f "${out}" ]] && printf '%s %s\n' "${sha}" "${out}" | shasum -a 256 -c - >/dev/null 2>&1; then + echo "${out}" + return 0 + fi + rm -f "${out}.part" + out="${out}.part" "$@" >&2 + printf '%s %s\n' "${sha}" "${out}.part" | shasum -a 256 -c - >&2 + mv "${out}.part" "${out}" + echo "${out}" + } + + if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then + . "${repo_root}/tools/gamescope/release.env" + gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \ + bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}") + zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}" + test -f "${linuxfs_dir}/usr/local/bin/gamescope" + fi + + . "${repo_root}/tools/linuxfs/uruntime.env" + uruntime_binary=$(cached "${URUNTIME_SHA256}" "${URUNTIME_ASSET}" \ + bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}") + mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime" + install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime" + install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE" + dwarfs_wrapper=$(cached "${DWARFS_SHA256}" "${DWARFS_ASSET}" \ + bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/mhx/dwarfs/releases/download/${DWARFS_VERSION}/${DWARFS_ASSET}") + mkdir -p "${linuxfs_dir}/usr/local/share/licenses/dwarfs" + bash "${repo_root}/tools/linuxfs/unwrap-dwarfs.sh" "${dwarfs_wrapper}" "${linuxfs_dir}/usr/local/lib/droiddeck/dwarfsextract" + printf '%s %s\n' "${DWARFS_PAYLOAD_SHA256}" "${linuxfs_dir}/usr/local/lib/droiddeck/dwarfsextract" | shasum -a 256 -c - >&2 + install -m644 "${repo_root}/tools/linuxfs/licenses/dwarfs-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/dwarfs/LICENSE" + + sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync" + if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then + . "${repo_root}/tools/droiddeck-esync/release.env" + sync_archive=$(cached "${SYNC_BUNDLE_SHA256}" "${SYNC_BUNDLE_ASSET}" \ + bash -c 'gh release download "$0" -R "$2" -p "$1" -O "$out"' "${SYNC_BUNDLE_TAG}" "${SYNC_BUNDLE_ASSET}" "${SYNC_BUNDLE_REPO}") + rm -rf "${sync_assets}" + mkdir -p "${sync_assets}" + zstd -dc "${sync_archive}" | tar -xf - -C "${sync_assets}" + test -f "${sync_assets}/index.json" + test -f "${sync_assets}/index.json.sig" + elif [[ -d "${sync_assets}" ]]; then + echo "No tools/droiddeck-esync/release.env: the APK bundles the droiddeck-esync packs already in ${sync_assets}." >&2 + fi + + msi_pkgs="${staging_dir}/msi-pkgs" + msi_dir="${linuxfs_dir}/usr/local/lib/droiddeck-msitools" + mkdir -p "${msi_pkgs}" "${msi_dir}" + while read -r package_sha256 package_url; do + [[ -n "${package_url}" ]] || continue + package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ + bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") + tar -xJf "${package_archive}" -C "${msi_pkgs}" + done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt") + for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done + for tool in 7z 7z.so; do install -m644 "${msi_pkgs}/usr/lib/7zip/${tool}" "${msi_dir}/${tool}"; done + for library in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do + cp -L "${msi_pkgs}/usr/lib/${library}" "${msi_dir}/${library}" + done + mkdir -p "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools" + for license in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do + install -m644 "${repo_root}/tools/msitools/licenses/${license}" \ + "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools/${license}" + done + + mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp" + mango_pkgs="${staging_dir}/mango-pkgs" + mkdir -p "${mango_dir}" "${mango_pkgs}" + while read -r package_sha256 package_url; do + [[ -n "${package_url}" ]] || continue + package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ + bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") + zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}" + done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt") + install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp" + for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do + cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}" + done + docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \ + aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \ + -o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c + mkdir -p "${linuxfs_dir}/usr/local/bin" + install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp" + + pw_pkgs="${staging_dir}/pw-pkgs" + mkdir -p "${pw_pkgs}" + while read -r package_sha256 package_url; do + [[ -n "${package_url}" ]] || continue + package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ + bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") + zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}" + done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt") + "${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst" + + pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"} + if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then + pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz" + if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then + curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \ + https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz + mv "${pa_tarball}.part" "${pa_tarball}" + fi + mkdir -p "${pa_source}" + tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1 + fi + if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then + echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2 + exit 1 + fi + + sink_output="${staging_dir}/sink-out" + "${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}" + "${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}" + proot_sources=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1) + proot_inputs=$(printf '%s\n' "${proot_sources}" "${ndk_version}" | shasum -a 256 | cut -d' ' -f1) + if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \ + && "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]] \ + && (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then + echo "proot: sources unchanged, keeping ${proot_out}/libproot.so" + else + proot_stage="${staging_dir}/proot" + if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then + "${repo_root}/tools/proot/build.sh" "${proot_stage}" + save_step proot "${proot_inputs}" "${proot_stage}" + fi + install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/" + echo "${proot_inputs}" > "${proot_out}/.proot-inputs" + (cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs) + fi +fi sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync" if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then + # Packs revoked after a bundle was published are dropped from local and CI-prepared bundles alike. . "${repo_root}/tools/droiddeck-esync/release.env" - sync_archive=$(cached "${SYNC_BUNDLE_SHA256}" "${SYNC_BUNDLE_ASSET}" \ - bash -c 'gh release download "$0" -R "$2" -p "$1" -O "$out"' "${SYNC_BUNDLE_TAG}" "${SYNC_BUNDLE_ASSET}" "${SYNC_BUNDLE_REPO}") - rm -rf "${sync_assets}" - mkdir -p "${sync_assets}" - zstd -dc "${sync_archive}" | tar -xf - -C "${sync_assets}" - test -f "${sync_assets}/index.json" - test -f "${sync_assets}/index.json.sig" sync_index=$(mktemp) gh release download "${SYNC_BUNDLE_TAG}" -R "${SYNC_BUNDLE_REPO}" -p index.json -O "${sync_index}" --clobber revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' "${sync_index}") @@ -265,94 +433,6 @@ if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then fi done rm -f "${sync_index}" -elif [[ -d "${sync_assets}" ]]; then - echo "No tools/droiddeck-esync/release.env: the APK bundles the droiddeck-esync packs already in ${sync_assets}." >&2 -fi - -msi_pkgs="${staging_dir}/msi-pkgs" -msi_dir="${linuxfs_dir}/usr/local/lib/droiddeck-msitools" -mkdir -p "${msi_pkgs}" "${msi_dir}" -while read -r package_sha256 package_url; do - [[ -n "${package_url}" ]] || continue - package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ - bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") - tar -xJf "${package_archive}" -C "${msi_pkgs}" -done < <(grep -v '^#' "${repo_root}/tools/msitools/packages.txt") -for tool in msiinfo cabextract; do install -m644 "${msi_pkgs}/usr/bin/${tool}" "${msi_dir}/${tool}"; done -for tool in 7z 7z.so; do install -m644 "${msi_pkgs}/usr/lib/7zip/${tool}" "${msi_dir}/${tool}"; done -for library in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do - cp -L "${msi_pkgs}/usr/lib/${library}" "${msi_dir}/${library}" -done -mkdir -p "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools" -for license in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do - install -m644 "${repo_root}/tools/msitools/licenses/${license}" \ - "${linuxfs_dir}/usr/local/share/licenses/droiddeck-msitools/${license}" -done - -mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp" -mango_pkgs="${staging_dir}/mango-pkgs" -mkdir -p "${mango_dir}" "${mango_pkgs}" -while read -r package_sha256 package_url; do - [[ -n "${package_url}" ]] || continue - package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ - bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") - zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}" -done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt") -install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp" -for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do - cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}" -done -docker run --rm --platform "${docker_platform}" --user "$(id -u):$(id -g)" -v "${repo_root}:/src" -w /src "${image_name}" \ - aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \ - -o app/src/main/assets/linuxfs/usr/local/lib/mangoapp/libtracefs.so.1 tools/mangoapp/libtracefs-shim.c -mkdir -p "${linuxfs_dir}/usr/local/bin" -install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp" - -pw_pkgs="${staging_dir}/pw-pkgs" -mkdir -p "${pw_pkgs}" -while read -r package_sha256 package_url; do - [[ -n "${package_url}" ]] || continue - package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \ - bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "${package_url}") - zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}" -done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt") -"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst" - -pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"} -if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then - pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz" - if [[ ! -s "${pa_tarball}" ]] || ! tar -tzf "${pa_tarball}" >/dev/null 2>&1; then - curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "${pa_tarball}.part" \ - https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz - mv "${pa_tarball}.part" "${pa_tarball}" - fi - mkdir -p "${pa_source}" - tar -xzf "${pa_tarball}" -C "${pa_source}" --strip-components=1 -fi -if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then - echo "PulseAudio 13.0 source not found at ${pa_source}; set DROIDDECK_PA13_SOURCE_DIR." >&2 - exit 1 -fi - -sink_output="${staging_dir}/sink-out" -"${repo_root}/tools/directaudio/fetch.sh" "${repo_root}" "${sink_output}" -"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}" -proot_out="${repo_root}/app/src/main/jniLibs/arm64-v8a" -proot_sources=$(cd "${repo_root}/tools/proot" && find . -type f ! -name '*.pyc' | LC_ALL=C sort | xargs shasum -a 256 | shasum -a 256 | cut -d' ' -f1) -proot_inputs=$(printf '%s\n' "${proot_sources}" "${ndk_version}" | shasum -a 256 | cut -d' ' -f1) -if [[ -f "${proot_out}/libproot.so" && -f "${proot_out}/libproot-loader.so" \ - && "$(cat "${proot_out}/.proot-inputs" 2>/dev/null)" = "${proot_inputs}" ]] \ - && (cd "${proot_out}" && shasum -a 256 -c .proot-outputs >/dev/null 2>&1); then - echo "proot: sources unchanged, keeping ${proot_out}/libproot.so" -else - proot_stage="${staging_dir}/proot" - if ! restore_step proot "${proot_inputs}" "${proot_stage}"; then - "${repo_root}/tools/proot/build.sh" "${proot_stage}" - save_step proot "${proot_inputs}" "${proot_stage}" - fi - install -m755 "${proot_stage}/libproot.so" "${proot_stage}/libproot-loader.so" "${proot_out}/" - echo "${proot_inputs}" > "${proot_out}/.proot-inputs" - (cd "${proot_out}" && shasum -a 256 libproot.so libproot-loader.so > .proot-outputs) fi syncthing_src="${repo_root}/tools/syncthing/syncthing-android/syncthing/src/github.com/syncthing/syncthing" @@ -376,21 +456,23 @@ else echo "${syncthing_inputs}" > "${proot_out}/.syncthing-inputs" fi -bundle_dir="${staging_dir}/pulseaudio-bundle" -mkdir -p "${bundle_dir}" -zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}" -if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \ - || -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then - echo "The committed audio bundle already contains a built ARM64 sink." >&2 - exit 1 +if [[ "${ci_components}" != 1 ]]; then + bundle_dir="${staging_dir}/pulseaudio-bundle" + mkdir -p "${bundle_dir}" + zstd -dc "${bundle_asset}" | tar -xf - -C "${bundle_dir}" + if [[ -e "${bundle_dir}/modules/arm64/module-aaudio-sink.so" \ + || -e "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" ]]; then + echo "The committed audio bundle already contains a built ARM64 sink." >&2 + exit 1 + fi + install -m755 "${sink_output}/module-aaudio-sink.so" \ + "${bundle_dir}/modules/arm64/module-aaudio-sink.so" + install -m755 "${sink_output}/module-directaudio-native-sink.so" \ + "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" + tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst" + mkdir -p "${repo_root}/app/build/prepared-assets" + mv "${staging_dir}/pulseaudio.tzst" "${repo_root}/app/build/prepared-assets/pulseaudio.tzst" fi -install -m755 "${sink_output}/module-aaudio-sink.so" \ - "${bundle_dir}/modules/arm64/module-aaudio-sink.so" -install -m755 "${sink_output}/module-directaudio-native-sink.so" \ - "${bundle_dir}/modules/arm64/module-directaudio-native-sink.so" -tar -cf - -C "${bundle_dir}" . | zstd -19 -T0 -c > "${staging_dir}/pulseaudio.tzst" -mkdir -p "${repo_root}/app/build/prepared-assets" -mv "${staging_dir}/pulseaudio.tzst" "${repo_root}/app/build/prepared-assets/pulseaudio.tzst" gradle_rust_arg="" if [[ "${DROIDDECK_SKIP_RUST:-0}" == 1 ]]; then @@ -411,19 +493,23 @@ else fi cd "${repo_root}" -python3 tools/quest/build-driver.py "${NDK}" +[[ "${ci_components}" == 1 ]] || python3 tools/quest/build-driver.py "${NDK}" xbox_out="${linuxfs_dir}/usr/local/lib/droiddeck-xbox" xbox_key=$(inputs_hash "native-arm64-ubuntu24.04" tools/xbox) -if ! restore_step xbox "${xbox_key}" "${xbox_out}"; then +if [[ "${ci_components}" == 1 ]] && fetch_ci_xbox; then + echo "xbox: reused main CI run ${ci_run}" +elif ! restore_step xbox "${xbox_key}" "${xbox_out}"; then bash tools/xbox/build-local.sh save_step xbox "${xbox_key}" "${xbox_out}" fi -comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet" -comet_key=$(inputs_hash "${image_id}" tools/comet) -if ! restore_step comet "${comet_key}" "${comet_out}"; then - DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh - save_step comet "${comet_key}" "${comet_out}" +if [[ "${ci_components}" != 1 ]]; then + comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet" + comet_key=$(inputs_hash "${image_id}" tools/comet) + if ! restore_step comet "${comet_key}" "${comet_out}"; then + DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh + save_step comet "${comet_key}" "${comet_out}" + fi fi if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then upc_out="${linuxfs_dir}/usr/local/lib/droiddeck-ubisoft" @@ -436,10 +522,21 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then rockstar_out="${linuxfs_dir}/usr/local/lib/droiddeck-rockstar" rockstar_key=$(inputs_hash "windows-gnu" tools/rockstar-launcher/src tools/rockstar-launcher/Cargo.toml tools/rockstar-launcher/Cargo.lock tools/rockstar-launcher/build.sh) if ! restore_step rockstar "${rockstar_key}" "${rockstar_out}"; then - command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; } - CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}" + if [[ "$(uname -s)" == Darwin ]]; then + bash tools/rockstar-launcher/build-container.sh "${rockstar_out}" + else + command -v i686-w64-mingw32-gcc >/dev/null 2>&1 || { echo "i686-w64-mingw32-gcc is required for the Rockstar launcher service." >&2; exit 1; } + CARGO_TARGET_DIR="${cache_dir}/rockstar-target" bash tools/rockstar-launcher/build.sh "${rockstar_out}" + fi save_step rockstar "${rockstar_key}" "${rockstar_out}" fi + epic_out="${linuxfs_dir}/usr/local/lib/droiddeck-epic" + epic_key=$(inputs_hash "x86_64-pc-windows-gnu" tools/epic-launcher/src tools/epic-launcher/Cargo.toml tools/epic-launcher/Cargo.lock tools/epic-launcher/build.sh) + if ! restore_step epic "${epic_key}" "${epic_out}"; then + command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1 || { echo "x86_64-w64-mingw32-gcc is required for EpicGamesLauncher.exe." >&2; exit 1; } + CARGO_TARGET_DIR="${cache_dir}/epic-target" bash tools/epic-launcher/build.sh "${epic_out}" + save_step epic "${epic_key}" "${epic_out}" + fi fi python3 tools/powervr/fetch.py bash tools/packs/build.sh app/build/packs @@ -466,7 +563,7 @@ readelf_path=$(find "${NDK}/toolchains/llvm/prebuilt" -name llvm-readelf | head [[ -x "${readelf_path}" ]] || { echo "NDK llvm-readelf is missing" >&2; exit 1; } stores_check=() [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]] || stores_check+=(--without-stores) -python3 tools/release/check_android_libraries.py "${apk}" --readelf "${readelf_path}" "${stores_check[@]}" +python3 tools/release/check_android_libraries.py "${apk}" --readelf "${readelf_path}" ${stores_check[@]+"${stores_check[@]}"} git diff --exit-code -- app/src/main/rust/stores/Cargo.lock build_tools=$(find "${sdk_dir}/build-tools" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1) diff --git a/tools/ci/clear-runner-scratch.sh b/tools/ci/clear-runner-scratch.sh new file mode 100755 index 0000000000..aab34a2e92 --- /dev/null +++ b/tools/ci/clear-runner-scratch.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -uo pipefail +workspace="${1:?}" +find /tmp -maxdepth 1 -user "$(id -u)" \( -name 'robolectric-*' -o -name 'junit*' -o -name 'gradle-*' -o -name 'kotlin-*' \) -mmin +180 -print0 | + while IFS= read -r -d '' entry; do + recent=$(find "$entry" -xdev -mmin -180 -print -quit 2>/dev/null) && [ -z "$recent" ] && rm -rf --one-file-system --preserve-root=all -- "$entry" + done +free=$(df --output=avail -k "$workspace" | tail -1) +if [ "$free" -lt 20971520 ]; then + rm -rf --one-file-system --preserve-root=all -- "${HOME:?}/.gradle/caches/build-cache-1" "${HOME:?}/.gradle/.tmp" +fi +df -h /tmp "$workspace" +du -xsh /tmp "${HOME:?}/.gradle" "${HOME:?}/.cargo" "${HOME:?}/.m2" "$(dirname "$workspace")" 2>/dev/null | sort -h +exit 0 diff --git a/tools/components/recipes.json b/tools/components/recipes.json index 5fd8ca4bc2..5cccf80ffa 100644 --- a/tools/components/recipes.json +++ b/tools/components/recipes.json @@ -8,6 +8,7 @@ "tools/linuxfs/desktop", "tools/linuxfs/licenses", "tools/linuxfs/uruntime.env", + "tools/linuxfs/unwrap-dwarfs.sh", "tools/gamescope/release.env", "tools/wlroots/release.env", "tools/mangoapp", diff --git a/tools/components/recipes/runtime.sh b/tools/components/recipes/runtime.sh index aa5273d270..9de7efba18 100644 --- a/tools/components/recipes/runtime.sh +++ b/tools/components/recipes/runtime.sh @@ -26,6 +26,13 @@ echo "${URUNTIME_SHA256} uruntime" | sha256sum -c - install -Dm644 uruntime "$D/usr/local/lib/droiddeck/uruntime" install -Dm644 tools/linuxfs/licenses/uruntime-LICENSE "$D/usr/local/share/licenses/uruntime/LICENSE" rm uruntime +curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o dwarfs-wrapper "https://github.com/mhx/dwarfs/releases/download/${DWARFS_VERSION}/${DWARFS_ASSET}" +echo "${DWARFS_SHA256} dwarfs-wrapper" | sha256sum -c - +bash tools/linuxfs/unwrap-dwarfs.sh dwarfs-wrapper dwarfsextract +echo "${DWARFS_PAYLOAD_SHA256} dwarfsextract" | sha256sum -c - +install -Dm644 dwarfsextract "$D/usr/local/lib/droiddeck/dwarfsextract" +install -Dm644 tools/linuxfs/licenses/dwarfs-LICENSE "$D/usr/local/share/licenses/dwarfs/LICENSE" +rm dwarfs-wrapper dwarfsextract M="$D/usr/local/lib/mangoapp" mkdir -p "$M" mango-pkgs grep -v '^#' tools/mangoapp/packages.txt | while read -r sum url; do diff --git a/tools/components/reuse.py b/tools/components/reuse.py new file mode 100644 index 0000000000..1eb02dca9d --- /dev/null +++ b/tools/components/reuse.py @@ -0,0 +1,150 @@ +"""Install the components a main CI run prepared when they match this tree. + +The run's prepared-components archive is used only when every recipe identity it records equals +the identity of the local tree, the inputs CI builds outside the recipes are unchanged from the +run's source tree, and no recipe submodule has local edits. Files are verified in a staging +directory before any local output is replaced. +""" +import argparse +from contextlib import contextmanager +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import shutil +import subprocess +import sys +import tarfile +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import prepare # noqa: E402 + +# CI records identities under its runner labels and pinned NDK, not this host's. +RUNNER_ARCHITECTURES = ('X64', 'ARM64') +# The components job builds these outside the recipe registry. +UNREGISTERED_INPUTS = ['.github/workflows/build.yml', 'tools/linuxfs/xclipse-layer', 'tools/venus/glprobe.c', + 'tools/quest'] + + +def ci_environment(architecture, root): + ndk = next(line.split('=', 1)[1].strip() + for line in (root / 'tools/ci/toolchains.env').read_text().splitlines() + if line.startswith('CI_ANDROID_NDK_VERSION=')) + return dict(RUNNER_OS='Linux', RUNNER_ARCH=architecture, NDK_VERSION=ndk) + + +@contextmanager +def environ(values): + saved = {key: os.environ.get(key) for key in values} + os.environ.update(values) + try: + yield + finally: + for key, value in saved.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + + +def identities(environment, root): + with environ(environment): + return {name: prepare.identity(name, root) for name in prepare.registry(root)} + + +def git(root, *args): + return subprocess.run(['git', *args], cwd=root, capture_output=True, text=True) + + +def unregistered_changes(source_tree, root): + if git(root, 'cat-file', '-e', source_tree + '^{tree}').returncode: + return ['source tree ' + source_tree + ' (fetch origin main)'] + changed = git(root, 'diff', '--name-only', source_tree, '--', *UNREGISTERED_INPUTS).stdout.split() + changed += git(root, 'ls-files', '--others', '--exclude-standard', '--', *UNREGISTERED_INPUTS).stdout.split() + return sorted(set(changed)) + + +def edited_submodules(root): + inputs = [path for spec in prepare.registry(root).values() + for path in spec.get('inputs', []) + spec.get('source_inputs', [])] + staged = git(root, 'ls-files', '--stage', '--', *inputs).stdout.splitlines() + links = [line.split('\t', 1)[1] for line in staged if line.startswith('160000 ')] + return [link for link in links + if git(root, 'diff', '--quiet', '--ignore-submodules=none', '--', link).returncode] + + +def extract(archive_path, stage): + allowed = set(prepare.LIBRARIES + [prepare.MANIFEST]) + total = 0 + with tarfile.open(archive_path, mode='r:gz') as archive: + for entry in archive: + name = PurePosixPath(entry.name) + total += entry.size + if (not entry.isfile() or name.is_absolute() or '..' in name.parts or '\\' in entry.name + or name.as_posix() != entry.name or total > 2 * 1024**3 + or not (entry.name in allowed or any(entry.name.startswith(t + '/') for t in prepare.TREES))): + raise ValueError('Unsafe prepared component archive: ' + entry.name) + path = stage / entry.name + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('xb') as output: + shutil.copyfileobj(archive.extractfile(entry), output) + path.chmod(entry.mode & 0o777) + + +def digest(path): + with path.open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def install(stage, root): + for name in prepare.TREES: + shutil.rmtree(root / name, ignore_errors=True) + (root / name).parent.mkdir(parents=True, exist_ok=True) + os.replace(stage / name, root / name) + for name in prepare.LIBRARIES + [prepare.MANIFEST]: + (root / name).parent.mkdir(parents=True, exist_ok=True) + os.replace(stage / name, root / name) + + +def reuse(archive_path, root=prepare.ROOT): + with tarfile.open(archive_path, mode='r:gz') as archive: + data = json.load(archive.extractfile(prepare.MANIFEST)) + if data.get('version') != 1: + raise ValueError('Unknown prepared component archive version') + recorded = data.get('recipes') or {} + environment = next((ci_environment(a, root) for a in RUNNER_ARCHITECTURES + if identities(ci_environment(a, root), root) == recorded), None) + if environment is None: + local = identities(ci_environment(RUNNER_ARCHITECTURES[0], root), root) + changed = sorted(name for name in local.keys() | recorded.keys() if local.get(name) != recorded.get(name)) + print('CI run ' + str(data.get('run')) + ' prepared different components: ' + ', '.join(changed)) + return False + differences = unregistered_changes(data['source_tree'], root) + edited_submodules(root) + if differences: + print('CI run ' + str(data.get('run')) + ' built from other sources: ' + ', '.join(differences)) + return False + (root / 'app/build').mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=root / 'app/build', prefix='.reuse-') as stage: + stage = Path(stage) + extract(archive_path, stage) + files = sorted(path.relative_to(stage).as_posix() for path in stage.rglob('*') + if path.is_file() and path.relative_to(stage).as_posix() != prepare.MANIFEST) + if data.get('files') != {name: digest(stage / name) for name in files}: + raise ValueError('Prepared components do not match their recorded file hashes') + missing = [name for name in prepare.TREES if not (stage / name).is_dir()] + missing += [name for name in prepare.LIBRARIES + [prepare.MANIFEST] if not (stage / name).is_file()] + if missing: + raise ValueError('Prepared component archive is missing ' + ', '.join(missing)) + install(stage, root) + return True + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('archive', type=Path) + args = parser.parse_args() + try: + sys.exit(0 if reuse(args.archive) else 3) + except (ValueError, OSError, KeyError, tarfile.TarError) as error: + sys.exit('Cannot reuse CI components: ' + str(error)) diff --git a/tools/droiddeckctl b/tools/droiddeckctl index 50ff42423d..2a4341c514 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -412,10 +412,10 @@ def pacing(adb: str, serial: str, seconds: float) -> dict: try: time.sleep(seconds) dump = run_adb(adb, serial, *timestats, "-dump", timeout=60) + elapsed = time.monotonic() - started except ControlError as exc: raise ControlError(str(exc), "PACING_FAILED") from exc finally: - elapsed = time.monotonic() - started try: disabled = run_adb(adb, serial, *timestats, "-disable").returncode == 0 except ControlError: @@ -792,7 +792,7 @@ def uinput_commands(samples: list[dict], tool: str, viewport: dict) -> list[dict {"id": 1, "command": "sync", "syncToken": UINPUT_SYNC}] -def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict: +def uinput_check(adb: str, serial: str) -> None: probe = run_adb(adb, serial, "shell", "command -v uinput >/dev/null 2>&1 || echo no-uinput; [ -w /dev/uinput ] || echo no-dev-uinput") if probe.returncode != 0: @@ -802,6 +802,10 @@ def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict: raise ControlError("This device's shell has no `uinput` command", "UINPUT_UNAVAILABLE") if "no-dev-uinput" in missing: raise ControlError("The ADB shell cannot write /dev/uinput on this device", "UINPUT_UNAVAILABLE") + + +def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict: + uinput_check(adb, serial) viewport = input_viewport(run_adb(adb, serial, "shell", "dumpsys", "input").stdout.decode(errors="replace")) script = "".join(json.dumps(command) + "\n" for command in uinput_commands(samples, tool, viewport)) started = time.monotonic() @@ -817,6 +821,68 @@ def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict: "viewport": {key: viewport[key] for key in ("display", "rotation", "size")}} +GAMEPAD_NAME = "DroidDeck test pad" +GAMEPAD_SYNC = "droiddeckctl-gamepad-done" +GAMEPAD_BUTTONS = {"a": "BTN_SOUTH", "b": "BTN_EAST", "x": "BTN_NORTH", "y": "BTN_WEST", "lb": "BTN_TL", "rb": "BTN_TR", + "select": "BTN_SELECT", "start": "BTN_START", "guide": "BTN_MODE", "l3": "BTN_THUMBL", "r3": "BTN_THUMBR"} +GAMEPAD_DPAD = {"up": ("ABS_HAT0Y", -1), "down": ("ABS_HAT0Y", 1), "left": ("ABS_HAT0X", -1), "right": ("ABS_HAT0X", 1)} +GAMEPAD_MAX_PRESSES = 200 +GAMEPAD_DPAD_MIN_GAP_MS = 20 + + +def gamepad_commands(buttons: list[str], hold: int, gap: int) -> list[dict]: + def axis(code: str, low: int, high: int) -> dict: + return {"code": code, "info": {"value": 0, "minimum": low, "maximum": high, "fuzz": 0, "flat": 0, "resolution": 0}} + + unknown = [name for name in buttons if name not in GAMEPAD_BUTTONS and name not in GAMEPAD_DPAD] + if unknown: + raise ControlError(f"Unknown gamepad button {unknown[0]!r}; use " + f"{', '.join(list(GAMEPAD_BUTTONS) + list(GAMEPAD_DPAD))}", "INVALID_INPUT") + if not 1 <= len(buttons) <= GAMEPAD_MAX_PRESSES: + raise ControlError(f"Press between 1 and {GAMEPAD_MAX_PRESSES} buttons", "INVALID_INPUT") + if not 10 <= hold <= 5000 or not 0 <= gap <= 5000: + raise ControlError("--hold must be 10..5000 ms and --gap 0..5000 ms", "INVALID_INPUT") + commands: list[dict] = [ + {"id": 1, "command": "register", "name": GAMEPAD_NAME, "bus": "usb", "vid": 0x045E, "pid": 0x028E, + "configuration": [ + {"type": "UI_SET_EVBIT", "data": ["EV_KEY", "EV_ABS"]}, + {"type": "UI_SET_KEYBIT", "data": sorted(GAMEPAD_BUTTONS.values())}, + {"type": "UI_SET_ABSBIT", "data": ["ABS_X", "ABS_Y", "ABS_RX", "ABS_RY", "ABS_HAT0X", "ABS_HAT0Y"]}, + ], + "abs_info": [axis("ABS_X", -32768, 32767), axis("ABS_Y", -32768, 32767), axis("ABS_RX", -32768, 32767), + axis("ABS_RY", -32768, 32767), axis("ABS_HAT0X", -1, 1), axis("ABS_HAT0Y", -1, 1)]}, + {"id": 1, "command": "delay", "duration": UINPUT_REGISTER_MS}, + ] + for name in buttons: + code, down, up = (GAMEPAD_BUTTONS[name], 1, 0) if name in GAMEPAD_BUTTONS else \ + (GAMEPAD_DPAD[name][0], GAMEPAD_DPAD[name][1], 0) + kind = "EV_KEY" if name in GAMEPAD_BUTTONS else "EV_ABS" + commands += [{"id": 1, "command": "inject", "events": [kind, code, down, "EV_SYN", "SYN_REPORT", 0]}, + {"id": 1, "command": "delay", "duration": hold}, + {"id": 1, "command": "inject", "events": [kind, code, up, "EV_SYN", "SYN_REPORT", 0]}] + pause = gap if name in GAMEPAD_BUTTONS else max(gap, GAMEPAD_DPAD_MIN_GAP_MS) + if pause > 0: + commands.append({"id": 1, "command": "delay", "duration": pause}) + return commands + [{"id": 1, "command": "delay", "duration": UINPUT_TAIL_MS}, + {"id": 1, "command": "sync", "syncToken": GAMEPAD_SYNC}] + + +def gamepad_uinput(adb: str, serial: str, buttons: list[str], hold: int, gap: int) -> dict: + commands = gamepad_commands(buttons, hold, gap) + uinput_check(adb, serial) + script = "".join(json.dumps(command) + "\n" for command in commands) + started = time.monotonic() + result = run_adb(adb, serial, "shell", "uinput", "-", stdin=script.encode(), + timeout=(UINPUT_REGISTER_MS + len(buttons) * (hold + gap) + UINPUT_TAIL_MS) / 1000 + 30) + elapsed = round((time.monotonic() - started) * 1000) + if GAMEPAD_SYNC not in result.stdout.decode(errors="replace"): + detail = (result.stderr or result.stdout).decode(errors="replace").strip()[-400:] + raise ControlError(f"uinput stopped before the last button (exit {result.returncode})" + + (f": {detail}" if detail else "") + "; `adb logcat -s UINPUT UinputDevice` tells why", + "UINPUT_FAILED") + return {"ok": True, "command": "input", "type": "gamepad", "buttons": buttons, "ms": elapsed} + + def xr_ppm_to_png(data: bytes, linear: bool = False) -> bytes: header = re.match(rb"P6\n([0-9]+) ([0-9]+)\n255\n", data) if not header: @@ -1081,6 +1147,8 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict: if command == "input": if args.input_type == "pen": return add_serial(pen_uinput(adb, serial, pen_samples(args), args.tool), serial) + if args.input_type == "gamepad": + return add_serial(gamepad_uinput(adb, serial, args.buttons, args.hold, args.gap), serial) return add_serial(checked(provider_call(adb, serial, "input", request=input_request(args), timeout=60), "INPUT_FAILED"), serial) @@ -1359,6 +1427,13 @@ def build_parser() -> argparse.ArgumentParser: pad.add_argument("button") pad.add_argument("--action", choices=["tap", "down", "up"], default="tap") pad.add_argument("--hold", type=int, default=120) + gamepad = kinds.add_parser( + "gamepad", help="press buttons on a real uinput gamepad that Android sees as a physical controller " + "(unlike pad, which only feeds the guest's virtual pad)") + gamepad.add_argument("buttons", nargs="+", metavar="BUTTON", + help="a b x y lb rb select start guide l3 r3 up down left right, pressed in order") + gamepad.add_argument("--hold", type=int, default=120, help="ms each button stays down") + gamepad.add_argument("--gap", type=int, default=400, help="ms between buttons (a d-pad press always waits at least 20 ms)") stick = kinds.add_parser("stick", help="hold a stick at x, y (-1..1)") stick.add_argument("stick", choices=["left", "right"]) stick.add_argument("x", type=float) diff --git a/tools/epic-launcher/.gitignore b/tools/epic-launcher/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/tools/epic-launcher/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/tools/epic-launcher/Cargo.lock b/tools/epic-launcher/Cargo.lock new file mode 100644 index 0000000000..569575bb09 --- /dev/null +++ b/tools/epic-launcher/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "droiddeck-epic-launcher" +version = "0.1.0" diff --git a/tools/epic-launcher/Cargo.toml b/tools/epic-launcher/Cargo.toml new file mode 100644 index 0000000000..fb5974a4b2 --- /dev/null +++ b/tools/epic-launcher/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "droiddeck-epic-launcher" +version = "0.1.0" +edition = "2021" +license = "GPL-3.0-only" +publish = false + +[[bin]] +name = "EpicGamesLauncher" +path = "src/main.rs" + +[profile.release] +opt-level = "s" +lto = true +panic = "abort" +strip = true diff --git a/tools/epic-launcher/README.md b/tools/epic-launcher/README.md new file mode 100644 index 0000000000..97dbce402f --- /dev/null +++ b/tools/epic-launcher/README.md @@ -0,0 +1,13 @@ +# Epic Games Launcher parent stand-in + +`EpicGamesLauncher.exe` starts the game named by its first argument as its own child, passes the rest of its command line to the game unchanged, waits for the game and returns its exit code. + +Some Epic titles only accept a launch whose parent process is named `EpicGamesLauncher.exe`. Rockstar's launcher logs `Epic Games Launcher not detected as parent process.` and then treats the Epic copy as unowned. In DroidDeck the Epic client is a Linux program, so it can never be that parent. The check matches the process name, not its path: Heroic's stand-in works from `C:\windows\command` and from the game folder. + +`StoreLaunch` writes the Epic `.droiddeck-launch.bat` to run the game through this executable for the titles in `EPIC_PARENT_TITLES`, or for any Epic game whose per-game environment sets `DD_EPIC_PARENT=1`. `DD_EPIC_PARENT=0` turns it off. Without the staged executable the game starts directly, as before. + +`build.sh` builds it with the GNU Windows target for the `epic` add-on pack. The app fetches the pack when it starts signed in to Epic, or when a launch that needs it finds it missing, and stages it in the Linux runtime at `/usr/local/lib/droiddeck-epic`. + +```sh +cargo test --locked --manifest-path tools/epic-launcher/Cargo.toml +``` diff --git a/tools/epic-launcher/build.sh b/tools/epic-launcher/build.sh new file mode 100755 index 0000000000..5db23c420d --- /dev/null +++ b/tools/epic-launcher/build.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +out=${1:-"$here/../../app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic"} +target=x86_64-pc-windows-gnu +rustup target add "$target" >/dev/null 2>&1 || true +cargo build --manifest-path "$here/Cargo.toml" --release --locked --target "$target" +mkdir -p "$out" +install -m644 "${CARGO_TARGET_DIR:-$here/target}/$target/release/EpicGamesLauncher.exe" "$out/EpicGamesLauncher.exe" diff --git a/tools/epic-launcher/src/lib.rs b/tools/epic-launcher/src/lib.rs new file mode 100644 index 0000000000..f842dc13c2 --- /dev/null +++ b/tools/epic-launcher/src/lib.rs @@ -0,0 +1,110 @@ +const QUOTE: u16 = b'"' as u16; +const BACKSLASH: u16 = b'\\' as u16; + +fn blank(c: u16) -> bool { + c == b' ' as u16 || c == b'\t' as u16 +} + +fn trim_start(line: &[u16]) -> &[u16] { + let start = line.iter().position(|&c| !blank(c)).unwrap_or(line.len()); + &line[start..] +} + +/// Splits this program's command line into the game executable that follows the program name and +/// the rest of the line, which reaches the game unchanged. +pub fn split(line: &[u16]) -> Option<(Vec<u16>, &[u16])> { + let mut quoted = false; + let mut end = line.len(); + for (i, &c) in line.iter().enumerate() { + if c == QUOTE { + quoted = !quoted; + } else if blank(c) && !quoted { + end = i; + break; + } + } + let rest = trim_start(&line[end..]); + let mut exe = Vec::new(); + let mut quoted = false; + let mut slashes = 0; + let mut end = rest.len(); + for (i, &c) in rest.iter().enumerate() { + if c == BACKSLASH { + slashes += 1; + continue; + } + if c == QUOTE { + exe.extend(std::iter::repeat(BACKSLASH).take(slashes / 2)); + if slashes % 2 == 1 { + exe.push(QUOTE); + } else { + quoted = !quoted; + } + } else if blank(c) && !quoted { + exe.extend(std::iter::repeat(BACKSLASH).take(slashes)); + end = i; + slashes = 0; + break; + } else { + exe.extend(std::iter::repeat(BACKSLASH).take(slashes)); + exe.push(c); + } + slashes = 0; + } + exe.extend(std::iter::repeat(BACKSLASH).take(slashes)); + if exe.is_empty() { + return None; + } + Some((exe, trim_start(&rest[end..]))) +} + +#[cfg(test)] +mod tests { + use super::split; + + fn wide(s: &str) -> Vec<u16> { + s.encode_utf16().collect() + } + + fn parts(line: &str) -> Option<(String, String)> { + let line = wide(line); + split(&line).map(|(exe, rest)| (String::from_utf16(&exe).unwrap(), String::from_utf16(rest).unwrap())) + } + + #[test] + fn the_game_gets_the_rest_of_the_line_exactly_as_written() { + assert_eq!( + parts(r#""Z:\usr\local\lib\droiddeck-epic\EpicGamesLauncher.exe" "Z:\root\Games\Stores\Epic\Grand Theft Auto V\PlayGTAV.exe" -AUTH_LOGIN=unused -epicusername="A B" -nobattleye"#), + Some(( + r"Z:\root\Games\Stores\Epic\Grand Theft Auto V\PlayGTAV.exe".into(), + r#"-AUTH_LOGIN=unused -epicusername="A B" -nobattleye"#.into() + )) + ); + } + + #[test] + fn a_game_without_arguments_gets_none() { + assert_eq!(parts(r#"EpicGamesLauncher.exe "C:\Games\x.exe" "#), Some((r"C:\Games\x.exe".into(), String::new()))); + assert_eq!(parts(r"EpicGamesLauncher.exe C:\Games\x.exe"), Some((r"C:\Games\x.exe".into(), String::new()))); + } + + #[test] + fn the_program_name_follows_its_own_quoting_rules() { + assert_eq!(parts("\"C:\\a b\\\"EpicGamesLauncher.exe\tgame.exe -x"), Some(("game.exe".into(), "-x".into()))); + } + + #[test] + fn the_executable_follows_the_argument_quoting_rules() { + assert_eq!(parts(r#"e "C:\dir with\"part\"s\x.exe" -y"#), Some((r#"C:\dir with"part"s\x.exe"#.into(), "-y".into()))); + assert_eq!(parts(r#"e C:\a"b c"\x.exe -y"#), Some((r"C:\ab c\x.exe".into(), "-y".into()))); + assert_eq!(parts(r"e C:\games\ -y"), Some((r"C:\games\".into(), "-y".into()))); + } + + #[test] + fn a_missing_executable_is_refused() { + assert_eq!(parts("EpicGamesLauncher.exe"), None); + assert_eq!(parts("EpicGamesLauncher.exe "), None); + assert_eq!(parts(r#"EpicGamesLauncher.exe "" -x"#), None); + assert_eq!(parts(""), None); + } +} diff --git a/tools/epic-launcher/src/main.rs b/tools/epic-launcher/src/main.rs new file mode 100644 index 0000000000..0b3ac53837 --- /dev/null +++ b/tools/epic-launcher/src/main.rs @@ -0,0 +1,42 @@ +#[cfg(windows)] +fn main() { + use std::ffi::OsString; + use std::os::windows::ffi::OsStringExt; + use std::os::windows::process::CommandExt; + + #[link(name = "kernel32")] + extern "system" { + fn GetCommandLineW() -> *const u16; + } + + let line = unsafe { + let start = GetCommandLineW(); + let mut len = 0; + while *start.add(len) != 0 { + len += 1; + } + std::slice::from_raw_parts(start, len) + }; + let Some((exe, rest)) = droiddeck_epic_launcher::split(line) else { + eprintln!("usage: EpicGamesLauncher.exe <game.exe> [arguments]"); + std::process::exit(2); + }; + let exe = OsString::from_wide(&exe); + let mut command = std::process::Command::new(&exe); + if !rest.is_empty() { + command.raw_arg(OsString::from_wide(rest)); + } + match command.status() { + Ok(status) => std::process::exit(status.code().unwrap_or(1)), + Err(error) => { + eprintln!("EpicGamesLauncher: could not start {}: {error}", exe.to_string_lossy()); + std::process::exit(1); + } + } +} + +#[cfg(not(windows))] +fn main() { + eprintln!("EpicGamesLauncher.exe runs on Windows or Wine"); + std::process::exit(1); +} diff --git a/tools/fex/build-in-arch.sh b/tools/fex/build-in-arch.sh index 75bf7c22a3..dccb24f882 100755 --- a/tools/fex/build-in-arch.sh +++ b/tools/fex/build-in-arch.sh @@ -1,6 +1,8 @@ #!/usr/bin/bash set -euxo pipefail -VERSION=${FEX_VERSION:-FEX-2610} +VERSION=${FEX_VERSION:?FEX_VERSION must name a FEX release tag, e.g. FEX-2611.1} +RELEASE=${VERSION#FEX-} +RELEASE=${RELEASE%%.*} WORK=/work cd "$WORK" grep -q '^DisableSandbox' /etc/pacman.conf || sed -i 's/^\[options\]/[options]\nDisableSandbox/' /etc/pacman.conf @@ -38,7 +40,7 @@ fi rm -rf fex-src out && git clone -q --depth 1 --branch "$VERSION" --recurse-submodules --shallow-submodules https://github.com/FEX-Emu/FEX.git fex-src for p in tools/fex/patches/*.patch; do upstream=$(sed -n 's/^Fixed-upstream: FEX-\([0-9]\{4\}\)$/\1/p' "$p") - if [ -n "$upstream" ] && [ "${VERSION#FEX-}" -ge "$upstream" ]; then + if [ -n "$upstream" ] && [ "$RELEASE" -ge "$upstream" ]; then echo "$(basename "$p"): already in FEX-$upstream, skipped for $VERSION" continue fi @@ -56,7 +58,8 @@ cmake -S fex-src -B fex-build -G Ninja \ -DTUNE_CPU=none -DTUNE_ARCH=armv8-a \ -DBUILD_TESTING=OFF -DBUILD_FEXCONFIG=OFF -DENABLE_ASSERTIONS=OFF \ $( [ "$THUNKS" = 1 ] && echo "-DBUILD_THUNKS=ON -DX86_DEV_ROOTFS=$X86ROOT" || echo "-DBUILD_THUNKS=OFF" ) \ - -DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF \ + -DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF -DFMT_MODULE=OFF \ + -DCMAKE_CXX_MODULE_STD=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF \ ${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"} ninja -C fex-build DESTDIR="$WORK/out" ninja -C fex-build install diff --git a/tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch b/tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch new file mode 100644 index 0000000000..7311bb7c5d --- /dev/null +++ b/tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch @@ -0,0 +1,81 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +index d720866..f55bce4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +@@ -288,6 +288,7 @@ public: + ///// VMA (Virtual Memory Area) tracking ///// + static bool HandleSegfault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext); + void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; ++ void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length); + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + std::optional<FEXCore::ExecutableFileSectionInfo> + LookupExecutableFileSection(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestAddr) final override; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +index 94bdd37..5d6c850 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +@@ -196,6 +196,44 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + } + } + ++void SyscallHandler::ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length) { ++ if (SMCChecks != FEXCore::Config::CONFIG_SMC_MTRACK) { ++ return; ++ } ++ ++ const auto End = Base + Length; ++ auto Mapping = VMATracking.FindVMAEntry(Base); ++ if (Mapping == VMATracking.VMAs.end()) { ++ Mapping = VMATracking.VMAs.lower_bound(Base); ++ } ++ ++ for (; Mapping != VMATracking.VMAs.end() && Mapping->first < End; ++Mapping) { ++ if (!Mapping->second.Flags.Shared || !Mapping->second.Prot.Writable || !Mapping->second.Resource) { ++ continue; ++ } ++ ++ const auto MapBase = std::max(Base, Mapping->first); ++ const auto MapTop = std::min(End, Mapping->first + Mapping->second.Length); ++ if (MapTop <= MapBase) { ++ continue; ++ } ++ ++ const auto OffsetBase = Mapping->second.Offset + (MapBase - Mapping->first); ++ const auto OffsetTop = OffsetBase + (MapTop - MapBase); ++ ++ for (auto VMA = Mapping->second.Resource->FirstVMA; VMA; VMA = VMA->ResourceNextVMA) { ++ if (!VMA->Prot.Executable || VMA->Offset >= OffsetTop || VMA->Offset + VMA->Length <= OffsetBase) { ++ continue; ++ } ++ ++ const auto OverlapBase = std::max(VMA->Offset, OffsetBase); ++ const auto OverlapTop = std::min(VMA->Offset + VMA->Length, OffsetTop); ++ auto rv = mprotect((void*)(MapBase + (OverlapBase - OffsetBase)), OverlapTop - OverlapBase, PROT_READ); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", OverlapBase, OverlapTop - OverlapBase); ++ } ++ } ++} ++ + void SyscallHandler::InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) { + InvalidateCodeRangeIfNecessary(Thread, Start, Length, false); + } +@@ -334,6 +372,9 @@ void* SyscallHandler::GuestMmap(bool Is64Bit, FEXCore::Core::InternalThreadState + } + + LateMetadata = TrackMmap(Thread, Result, length, prot, flags, fd, offset, CachedSection); ++ if (prot & PROT_WRITE) { ++ ProtectWritableAliasOfCode(Result, Size); ++ } + PendingResourceDeletion = VMATracking.HasPendingResourceDeletions(); + } + +@@ -479,6 +520,9 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + } + + TrackMprotect(Thread, addr, len, prot); ++ if (prot & PROT_WRITE) { ++ ProtectWritableAliasOfCode(reinterpret_cast<uint64_t>(addr), FEXCore::AlignUp(len, FEXCore::Utils::FEX_PAGE_SIZE)); ++ } + } + + InvalidateCodeRangeIfNecessary(Thread, reinterpret_cast<uint64_t>(addr), len, false); diff --git a/tools/fex/patches/0007-cmake-install-code-without-depends.patch b/tools/fex/patches/0007-cmake-install-code-without-depends.patch new file mode 100644 index 0000000000..6752b40280 --- /dev/null +++ b/tools/fex/patches/0007-cmake-install-code-without-depends.patch @@ -0,0 +1,20 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 8976588..3ae54f4 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -776,7 +776,6 @@ if (BUILD_THUNKS) + CODE " + execute_process(COMMAND ${CMAKE_COMMAND} --build . --target install + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Guest)" +- DEPENDS guest-libs + COMPONENT Runtime) + + install( +@@ -784,7 +783,6 @@ if (BUILD_THUNKS) + CODE " + execute_process(COMMAND ${CMAKE_COMMAND} --build . --target install + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Guest_32)" +- DEPENDS guest-libs-32 + COMPONENT Runtime) + + add_custom_target(uninstall_guest-libs diff --git a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch new file mode 100644 index 0000000000..6592a94550 --- /dev/null +++ b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch @@ -0,0 +1,18 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index b4c7b24..643185d 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + auto Frame = Thread->CurrentFrame; + + if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { + // XXX: Unsupported since it needs state reconstruction + // If we are in the JIT then SRA might need to be restored to values from the context + // We can't currently support this since it might result in tearing without real state reconstruction ++ Frame->InSyscallInfo = Context->InSyscallInfo; + } + + if (Is64BitMode) { + RestoreFrame_x64(Thread, Context, Frame, ucontext); + } else { + if (Type == RestoreType::TYPE_NONREALTIME) { diff --git a/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch new file mode 100644 index 0000000000..fbeec5ec96 --- /dev/null +++ b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch @@ -0,0 +1,174 @@ +diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +index 02bb6bf..2e72492 100644 +--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h ++++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +@@ -49,6 +49,11 @@ struct X86ContextBackup { + uint64_t FPStateLocation; + uint64_t UContextLocation; + uint64_t SigInfoLocation; ++ uint64_t PrevGuestFrame; ++ uint64_t GuestFrameEnd; ++ uint64_t GuestInterruptedSP; ++ uint64_t GuestAltBase; ++ uint64_t GuestAltEnd; + FEXCore::Core::CPUState GuestState; + static constexpr int RedZoneSize = 128; + }; +@@ -76,6 +81,11 @@ struct ArmContextBackup { + uint64_t FPStateLocation; + uint64_t UContextLocation; + uint64_t SigInfoLocation; ++ uint64_t PrevGuestFrame; ++ uint64_t GuestFrameEnd; ++ uint64_t GuestInterruptedSP; ++ uint64_t GuestAltBase; ++ uint64_t GuestAltEnd; + FEXCore::Core::CPUState GuestState; + + // Arm64 doesn't have a red zone +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index 643185d..53179c4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* + #endif + } + ++namespace { ++ bool OnGuestAltStack(const ArchHelpers::Context::ContextBackup* Backup, uint64_t SP) { ++ return Backup->GuestAltEnd != 0 && SP >= Backup->GuestAltBase && SP <= Backup->GuestAltEnd; ++ } ++ ++ bool GuestLeftFrame(const ArchHelpers::Context::ContextBackup* Backup, uint64_t GuestSP, uint32_t Limit) { ++ const bool SPOnAlt = OnGuestAltStack(Backup, GuestSP); ++ if (SPOnAlt == OnGuestAltStack(Backup, Backup->GuestFrameEnd)) { ++ return GuestSP >= Backup->GuestFrameEnd; ++ } ++ if (SPOnAlt) { ++ return false; ++ } ++ auto Entry = Backup; ++ while (OnGuestAltStack(Backup, Entry->GuestInterruptedSP)) { ++ if (--Limit == 0 || !Entry->PrevGuestFrame) { ++ return false; ++ } ++ Entry = reinterpret_cast<const ArchHelpers::Context::ContextBackup*>(Entry->PrevGuestFrame); ++ } ++ return OnGuestAltStack(Backup, Entry->GuestFrameEnd) && Entry->GuestAltBase == Backup->GuestAltBase && ++ Entry->GuestAltEnd == Backup->GuestAltEnd && GuestSP >= Entry->GuestInterruptedSP; ++ } ++} ++ + ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) { + // We can end up getting a signal at any point in our host state + // Jump to a handler that saves all state so we can safely return +@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + } + + OldSP = *reinterpret_cast<uint64_t*>(GuestSP); ++ ++ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; ++ uint64_t Entry = SignalInfo.GuestFrames; ++ for (uint32_t Depth = 1; Entry && Depth <= SignalInfo.GuestFrameCount; ++Depth) { ++ auto EntryBackup = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(Entry); ++ if (Entry == OldSP) { ++ SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame; ++ SignalInfo.GuestFrameCount -= Depth; ++ Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1; ++ break; ++ } ++ Entry = EntryBackup->PrevGuestFrame; ++ } + } + + uintptr_t NewSP = OldSP; +@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + auto ContextBackup = StoreThreadState(Thread, Signal, ucontext); + + auto Frame = Thread->CurrentFrame; ++ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; + + // Ref count our faults + // We use this to track if it is safe to clear cache +@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + + uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP]; + uint64_t NewGuestSP = OldGuestSP; ++ uint64_t GuestAltBase = 0; ++ uint64_t GuestAltEnd = 0; + + // altstack is only used if the signal handler was setup with SA_ONSTACK + if (GuestAction->sa_flags & SA_ONSTACK) { +@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + // Then that means we are hitting recursive signals and we need to walk back the stack correctly + uint64_t AltStackBase = reinterpret_cast<uint64_t>(GuestStack->ss_sp); + uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size; ++ GuestAltBase = AltStackBase; ++ GuestAltEnd = AltStackEnd; + if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) { + // We are already in the alt stack, the rest of the code will handle adjusting this + } else { +@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + } + } + ++#ifdef ARCHITECTURE_arm64 ++ auto Newest = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(SignalInfo.GuestFrames); ++ if (WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames && ++ Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1 && GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount)) { ++ uint32_t LeftFrames = 0; ++ while (Newest && LeftFrames < SignalInfo.GuestFrameCount && ++ GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount - LeftFrames)) { ++ Newest = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(Newest->PrevGuestFrame); ++ ++LeftFrames; ++ } ++ ++ const uint64_t HostTop = Newest ? reinterpret_cast<uint64_t>(Newest) : Frame->ReturningStackLocation; ++ const uint64_t MovedBackup = FEXCore::AlignDown( ++ HostTop - ArchHelpers::Context::ContextBackup::RedZoneSize - sizeof(ArchHelpers::Context::ContextBackup), 16); ++ if (MovedBackup > reinterpret_cast<uint64_t>(ContextBackup)) { ++ memmove(reinterpret_cast<void*>(MovedBackup), ContextBackup, sizeof(ArchHelpers::Context::ContextBackup)); ++ ContextBackup = reinterpret_cast<ArchHelpers::Context::ContextBackup*>(MovedBackup); ++ ContextBackup->PrevSP = HostTop; ++ ArchHelpers::Context::SetSp(ucontext, MovedBackup); ++ SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(Newest); ++ SignalInfo.GuestFrameCount -= LeftFrames; ++ Frame->SignalHandlerRefCounter -= LeftFrames; ++ } ++ } ++#endif ++ ++ ContextBackup->GuestFrameEnd = NewGuestSP; ++ ContextBackup->GuestInterruptedSP = OldGuestSP; ++ ContextBackup->GuestAltBase = GuestAltBase; ++ ContextBackup->GuestAltEnd = GuestAltEnd; ++ ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames; ++ SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(ContextBackup); ++ ++SignalInfo.GuestFrameCount; ++ + // siginfo_t + siginfo_t* HostSigInfo = reinterpret_cast<siginfo_t*>(info); + +@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre + + // Our ref counting doesn't matter anymore + Thread->CurrentFrame->SignalHandlerRefCounter = 0; ++ ThreadObject->SignalInfo.GuestFrames = 0; ++ ThreadObject->SignalInfo.GuestFrameCount = 0; + + // Set the new PC + if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index dfcd4b0..e4a86a9 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + // Queue of thread local signal frames that have been deferred. + // Async signals aren't guaranteed to be delivered in any particular order, but FEX treats them as FILO. + fextl::vector<DeferredSignalState> DeferredSignalFrames; ++ ++ uint64_t GuestFrames {}; ++ uint32_t GuestFrameCount {}; + } SignalInfo {}; + + // Seccomp thread specific data. diff --git a/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch b/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch new file mode 100644 index 0000000000..790a5390d8 --- /dev/null +++ b/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch @@ -0,0 +1,23 @@ +Fixed-upstream: FEX-2612 +diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +index c2b1d8e287..fcdf261484 100644 +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -285,6 +285,8 @@ DEF_OP(CondJump) { + DEF_OP(Syscall) { + SpillStaticRegs(TMP1); + ++ ResetStack(); ++ + // Jump to the syscall dispatch handler. We won't return after this. + ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.ThreadDispatchSyscallHandler)); + br(TMP1); +@@ -376,6 +378,8 @@ DEF_OP(ThreadRemoveCodeEntry) { + + SpillStaticRegs(TMP1); + ++ ResetStack(); ++ + // Store the new RIP to go to. + str(GetReg(Op->NewRIP).X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip)); + diff --git a/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch new file mode 100644 index 0000000000..626c726b59 --- /dev/null +++ b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch @@ -0,0 +1,109 @@ +diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp +--- a/FEXCore/Source/Interface/Core/Core.cpp ++++ b/FEXCore/Source/Interface/Core/Core.cpp +@@ -383,7 +383,11 @@ + } + + void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) { +- static_cast<ContextImpl*>(Thread->CTX)->Dispatcher->ExecuteJITCallback(Thread->CurrentFrame, RIP); ++ auto Frame = Thread->CurrentFrame; ++ const auto InSyscallInfo = Frame->InSyscallInfo; ++ Frame->InSyscallInfo = 0; ++ static_cast<ContextImpl*>(Thread->CTX)->Dispatcher->ExecuteJITCallback(Frame, RIP); ++ Frame->InSyscallInfo = InSyscallInfo; + } + + void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) { +diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -305,6 +305,9 @@ + + PushDynamicRegs(TMP1); + ++ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF); ++ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo)); ++ + mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr)); + + InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash); +@@ -320,6 +323,8 @@ + FillStaticRegs({ + .NZCV = false, + }); ++ ++ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo)); + } + + DEF_OP(ValidateCode) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -107,6 +107,10 @@ + #ifdef ARCHITECTURE_arm64 + Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext)); + ++ if ((IgnoreMask & 0xFFFF) == 0xFFFF) { ++ return; ++ } ++ + for (size_t i = 0; i < Config.SRAGPRCount; i++) { + const uint8_t SRAIdxMap = Config.SRAGPRMapping[i]; + if (IgnoreMask & (1U << SRAIdxMap)) { +@@ -301,12 +305,10 @@ + if (Context->UContextLocation) { + auto Frame = Thread->CurrentFrame; + +- if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { +- // XXX: Unsupported since it needs state reconstruction +- // If we are in the JIT then SRA might need to be restored to values from the context +- // We can't currently support this since it might result in tearing without real state reconstruction +- Frame->InSyscallInfo = Context->InSyscallInfo; +- } ++ // XXX: Unsupported since it needs state reconstruction ++ // If we are in the JIT then SRA might need to be restored to values from the context ++ // We can't currently support this since it might result in tearing without real state reconstruction ++ Frame->InSyscallInfo = Context->InSyscallInfo; + + if (Is64BitMode) { + RestoreFrame_x64(Thread, Context, Frame, ucontext); +@@ -361,6 +363,9 @@ + ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo; + Thread->CurrentFrame->InSyscallInfo = 0; + } else { ++ ContextBackup->InSyscallInfo = Frame->InSyscallInfo; ++ Frame->InSyscallInfo = 0; ++ + if (!IsAddressInDispatcher(OldPC)) { + // This is likely to cause issues but in some cases it isn't fatal + // This can also happen if we have put a signal on hold, then we just reenabled the signal +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -131,7 +131,7 @@ + if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) { + + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it +@@ -211,7 +211,7 @@ + // If the guest modified the RIP then we need to take special precautions here + if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) { + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it +@@ -290,7 +290,7 @@ + if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) { + + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it diff --git a/tools/fex/patches/0012-signal-return-applies-guest-registers.patch b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch new file mode 100644 index 0000000000..d97a75bee3 --- /dev/null +++ b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch @@ -0,0 +1,112 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +@@ -263,6 +263,8 @@ + FEXCore::Core::CpuStateFrame* Frame, void* ucontext); + void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, + FEXCore::Core::CpuStateFrame* Frame, void* ucontext); ++ void ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext, ++ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask); + + ///< Setup the signal frame for x64. + uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup, +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -122,6 +122,32 @@ + } + } + ++void SignalDelegator::ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext, ++ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask) { ++#ifdef ARCHITECTURE_arm64 ++ const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF; ++ const bool AllSpilled = Spilled == 0xFFFF; ++ if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ return; ++ } ++ ++ for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) { ++ const uint8_t HostReg = Config.SRAGPRMapping[i]; ++ const bool InFrame = AllSpilled || (Spilled & (1U << HostReg)); ++ const uint64_t Delivered = InFrame ? Frame->State.gregs[i] : ArchHelpers::Context::GetArmReg(ucontext, HostReg); ++ if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) { ++ continue; ++ } ++ ++ if (InFrame) { ++ Frame->State.gregs[i] = GuestGPRs[i]; ++ } else { ++ ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]); ++ } ++ } ++#endif ++} ++ + void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + auto* guest_uctx = reinterpret_cast<FEXCore::x86_64::ucontext_t*>(Context->UContextLocation); +@@ -202,6 +228,27 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0])); + } ++ } else { ++ uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS]; ++#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x]; ++ COPY_REG(R8); ++ COPY_REG(R9); ++ COPY_REG(R10); ++ COPY_REG(R11); ++ COPY_REG(R12); ++ COPY_REG(R13); ++ COPY_REG(R14); ++ COPY_REG(R15); ++ COPY_REG(RDI); ++ COPY_REG(RSI); ++ COPY_REG(RBP); ++ COPY_REG(RBX); ++ COPY_REG(RDX); ++ COPY_REG(RAX); ++ COPY_REG(RCX); ++ COPY_REG(RSP); ++#undef COPY_REG ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL); + } + } + +@@ -280,6 +327,17 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); + } ++ } else { ++ uint64_t GuestGPRs[8]; ++ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->sc.ax; ++ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->sc.cx; ++ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->sc.dx; ++ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->sc.bx; ++ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->sc.sp; ++ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->sc.bp; ++ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->sc.si; ++ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->sc.di; ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL); + } + } + +@@ -359,6 +417,17 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); + } ++ } else { ++ uint64_t GuestGPRs[8]; ++ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RAX]; ++ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RCX]; ++ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDX]; ++ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBX]; ++ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSP]; ++ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBP]; ++ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSI]; ++ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDI]; ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL); + } + } + diff --git a/tools/fex/patches/0013-path-syscalls-through-libc.patch b/tools/fex/patches/0013-path-syscalls-through-libc.patch new file mode 100644 index 0000000000..1aa641b311 --- /dev/null +++ b/tools/fex/patches/0013-path-syscalls-through-libc.patch @@ -0,0 +1,144 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 11ff163..4c3be85 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -209,6 +209,41 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, + } + #endif + ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) { ++ uint64_t Result = ::syscall(syscall_num, arg1); ++ SYSCALL_ERRNO(); ++} ++ ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough2(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2); ++ SYSCALL_ERRNO(); ++} ++ ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough3(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3); ++ SYSCALL_ERRNO(); ++} ++ ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough4(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4); ++ SYSCALL_ERRNO(); ++} ++ ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough5(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4, arg5); ++ SYSCALL_ERRNO(); ++} ++ + static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3<SYSCALL_DEF(read)>); + REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3<SYSCALL_DEF(write)>); +@@ -220,11 +255,11 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(shmctl, SyscallPassthrough3<SYSCALL_DEF(shmctl)>); + REGISTER_SYSCALL_IMPL(getpid, SyscallPassthrough0<SYSCALL_DEF(getpid)>); + REGISTER_SYSCALL_IMPL(socket, SyscallPassthrough3<SYSCALL_DEF(socket)>); +- REGISTER_SYSCALL_IMPL(connect, SyscallPassthrough3<SYSCALL_DEF(connect)>); ++ REGISTER_SYSCALL_IMPL(connect, SyscallPathPassthrough3<SYSCALL_DEF(connect)>); + REGISTER_SYSCALL_IMPL(sendto, SyscallPassthrough6<SYSCALL_DEF(sendto)>); + REGISTER_SYSCALL_IMPL(recvfrom, SyscallPassthrough6<SYSCALL_DEF(recvfrom)>); + REGISTER_SYSCALL_IMPL(shutdown, SyscallPassthrough2<SYSCALL_DEF(shutdown)>); +- REGISTER_SYSCALL_IMPL(bind, SyscallPassthrough3<SYSCALL_DEF(bind)>); ++ REGISTER_SYSCALL_IMPL(bind, SyscallPathPassthrough3<SYSCALL_DEF(bind)>); + REGISTER_SYSCALL_IMPL(listen, SyscallPassthrough2<SYSCALL_DEF(listen)>); + REGISTER_SYSCALL_IMPL(getsockname, SyscallPassthrough3<SYSCALL_DEF(getsockname)>); + REGISTER_SYSCALL_IMPL(getpeername, SyscallPassthrough3<SYSCALL_DEF(getpeername)>); +@@ -238,9 +273,9 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(flock, SyscallPassthrough2<SYSCALL_DEF(flock)>); + REGISTER_SYSCALL_IMPL(fsync, SyscallPassthrough1<SYSCALL_DEF(fsync)>); + REGISTER_SYSCALL_IMPL(fdatasync, SyscallPassthrough1<SYSCALL_DEF(fdatasync)>); +- REGISTER_SYSCALL_IMPL(truncate, SyscallPassthrough2<SYSCALL_DEF(truncate)>); ++ REGISTER_SYSCALL_IMPL(truncate, SyscallPathPassthrough2<SYSCALL_DEF(truncate)>); + REGISTER_SYSCALL_IMPL(getcwd, SyscallPassthrough2<SYSCALL_DEF(getcwd)>); +- REGISTER_SYSCALL_IMPL(chdir, SyscallPassthrough1<SYSCALL_DEF(chdir)>); ++ REGISTER_SYSCALL_IMPL(chdir, SyscallPathPassthrough1<SYSCALL_DEF(chdir)>); + REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1<SYSCALL_DEF(fchdir)>); + REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2<SYSCALL_DEF(fchmod)>); + REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3<SYSCALL_DEF(fchown)>); +@@ -280,7 +315,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(mlock, SyscallPassthrough2<SYSCALL_DEF(mlock)>); + REGISTER_SYSCALL_IMPL(munlock, SyscallPassthrough2<SYSCALL_DEF(munlock)>); + REGISTER_SYSCALL_IMPL(pivot_root, SyscallPassthrough2<SYSCALL_DEF(pivot_root)>); +- REGISTER_SYSCALL_IMPL(chroot, SyscallPassthrough1<SYSCALL_DEF(chroot)>); ++ REGISTER_SYSCALL_IMPL(chroot, SyscallPathPassthrough1<SYSCALL_DEF(chroot)>); + REGISTER_SYSCALL_IMPL(sync, SyscallPassthrough0<SYSCALL_DEF(sync)>); + REGISTER_SYSCALL_IMPL(acct, SyscallPassthrough1<SYSCALL_DEF(acct)>); + REGISTER_SYSCALL_IMPL(mount, SyscallPassthrough5<SYSCALL_DEF(mount)>); +@@ -312,17 +347,17 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(keyctl, SyscallPassthrough5<SYSCALL_DEF(keyctl)>); + REGISTER_SYSCALL_IMPL(ioprio_set, SyscallPassthrough2<SYSCALL_DEF(ioprio_set)>); + REGISTER_SYSCALL_IMPL(ioprio_get, SyscallPassthrough3<SYSCALL_DEF(ioprio_get)>); +- REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPassthrough3<SYSCALL_DEF(inotify_add_watch)>); ++ REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPathPassthrough3<SYSCALL_DEF(inotify_add_watch)>); + REGISTER_SYSCALL_IMPL(inotify_rm_watch, SyscallPassthrough2<SYSCALL_DEF(inotify_rm_watch)>); + REGISTER_SYSCALL_IMPL(migrate_pages, SyscallPassthrough4<SYSCALL_DEF(migrate_pages)>); +- REGISTER_SYSCALL_IMPL(mkdirat, SyscallPassthrough3<SYSCALL_DEF(mkdirat)>); +- REGISTER_SYSCALL_IMPL(mknodat, SyscallPassthrough4<SYSCALL_DEF(mknodat)>); +- REGISTER_SYSCALL_IMPL(fchownat, SyscallPassthrough5<SYSCALL_DEF(fchownat)>); +- REGISTER_SYSCALL_IMPL(unlinkat, SyscallPassthrough3<SYSCALL_DEF(unlinkat)>); +- REGISTER_SYSCALL_IMPL(renameat, SyscallPassthrough4<SYSCALL_DEF(renameat)>); +- REGISTER_SYSCALL_IMPL(linkat, SyscallPassthrough5<SYSCALL_DEF(linkat)>); +- REGISTER_SYSCALL_IMPL(symlinkat, SyscallPassthrough3<SYSCALL_DEF(symlinkat)>); +- REGISTER_SYSCALL_IMPL(fchmodat, SyscallPassthrough3<SYSCALL_DEF(fchmodat)>); ++ REGISTER_SYSCALL_IMPL(mkdirat, SyscallPathPassthrough3<SYSCALL_DEF(mkdirat)>); ++ REGISTER_SYSCALL_IMPL(mknodat, SyscallPathPassthrough4<SYSCALL_DEF(mknodat)>); ++ REGISTER_SYSCALL_IMPL(fchownat, SyscallPathPassthrough5<SYSCALL_DEF(fchownat)>); ++ REGISTER_SYSCALL_IMPL(unlinkat, SyscallPathPassthrough3<SYSCALL_DEF(unlinkat)>); ++ REGISTER_SYSCALL_IMPL(renameat, SyscallPathPassthrough4<SYSCALL_DEF(renameat)>); ++ REGISTER_SYSCALL_IMPL(linkat, SyscallPathPassthrough5<SYSCALL_DEF(linkat)>); ++ REGISTER_SYSCALL_IMPL(symlinkat, SyscallPathPassthrough3<SYSCALL_DEF(symlinkat)>); ++ REGISTER_SYSCALL_IMPL(fchmodat, SyscallPathPassthrough3<SYSCALL_DEF(fchmodat)>); + REGISTER_SYSCALL_IMPL(unshare, SyscallPassthrough1<SYSCALL_DEF(unshare)>); + REGISTER_SYSCALL_IMPL(splice, SyscallPassthrough6<SYSCALL_DEF(splice)>); + REGISTER_SYSCALL_IMPL(tee, SyscallPassthrough4<SYSCALL_DEF(tee)>); +@@ -343,7 +378,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(kcmp, SyscallPassthrough5<SYSCALL_DEF(kcmp)>); + REGISTER_SYSCALL_IMPL(sched_setattr, SyscallPassthrough3<SYSCALL_DEF(sched_setattr)>); + REGISTER_SYSCALL_IMPL(sched_getattr, SyscallPassthrough4<SYSCALL_DEF(sched_getattr)>); +- REGISTER_SYSCALL_IMPL(renameat2, SyscallPassthrough5<SYSCALL_DEF(renameat2)>); ++ REGISTER_SYSCALL_IMPL(renameat2, SyscallPathPassthrough5<SYSCALL_DEF(renameat2)>); + REGISTER_SYSCALL_IMPL(getrandom, SyscallPassthrough3<SYSCALL_DEF(getrandom)>); + REGISTER_SYSCALL_IMPL(memfd_create, SyscallPassthrough2<SYSCALL_DEF(memfd_create)>); + REGISTER_SYSCALL_IMPL(membarrier, SyscallPassthrough2<SYSCALL_DEF(membarrier)>); +@@ -468,7 +503,7 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(get_robust_list, SyscallPassthrough3<SYSCALL_DEF(get_robust_list)>); + REGISTER_SYSCALL_IMPL_X64(sync_file_range, SyscallPassthrough4<SYSCALL_DEF(sync_file_range)>); + REGISTER_SYSCALL_IMPL_X64(vmsplice, SyscallPassthrough4<SYSCALL_DEF(vmsplice)>); +- REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPassthrough4<SYSCALL_DEF(utimensat)>); ++ REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPathPassthrough4<SYSCALL_DEF(utimensat)>); + REGISTER_SYSCALL_IMPL_X64(fallocate, SyscallPassthrough4<SYSCALL_DEF(fallocate)>); + REGISTER_SYSCALL_IMPL_X64(timerfd_settime, SyscallPassthrough4<SYSCALL_DEF(timerfd_settime)>); + REGISTER_SYSCALL_IMPL_X64(timerfd_gettime, SyscallPassthrough2<SYSCALL_DEF(timerfd_gettime)>); +@@ -492,7 +527,7 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(cachestat, UnimplementedSyscallSafe); + } + if (Handler->IsHostKernelVersionAtLeast(6, 6, 0)) { +- REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPassthrough4<SYSCALL_DEF(fchmodat2)>); ++ REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPathPassthrough4<SYSCALL_DEF(fchmodat2)>); + } else { + REGISTER_SYSCALL_IMPL_X64(fchmodat2, UnimplementedSyscallSafe); + } +@@ -529,7 +564,7 @@ namespace x32 { + REGISTER_SYSCALL_IMPL_X32(timer_settime64, SyscallPassthrough4<SYSCALL_DEF(timer_settime)>); + REGISTER_SYSCALL_IMPL_X32(timerfd_gettime64, SyscallPassthrough2<SYSCALL_DEF(timerfd_gettime)>); + REGISTER_SYSCALL_IMPL_X32(timerfd_settime64, SyscallPassthrough4<SYSCALL_DEF(timerfd_settime)>); +- REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPassthrough4<SYSCALL_DEF(utimensat)>); ++ REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPathPassthrough4<SYSCALL_DEF(utimensat)>); + REGISTER_SYSCALL_IMPL_X32(ppoll_time64, SyscallPassthrough5<SYSCALL_DEF(ppoll)>); + REGISTER_SYSCALL_IMPL_X32(io_pgetevents_time64, SyscallPassthrough6<SYSCALL_DEF(io_pgetevents)>); + REGISTER_SYSCALL_IMPL_X32(mq_timedsend_time64, SyscallPassthrough5<SYSCALL_DEF(mq_timedsend)>); diff --git a/tools/fex/patches/0014-guest-preload-drops-host-libraries.patch b/tools/fex/patches/0014-guest-preload-drops-host-libraries.patch new file mode 100644 index 0000000000..204c5c5dc6 --- /dev/null +++ b/tools/fex/patches/0014-guest-preload-drops-host-libraries.patch @@ -0,0 +1,51 @@ +diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +index e1f601b..cebf1f5 100644 +--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h ++++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +@@ -222,6 +222,32 @@ class ELFCodeLoader final : public FEX::CodeLoader { + + public: + ++ static fextl::string GuestPreload(const char* List, const fextl::string& RootFS) { ++ fextl::string Result; ++ for (const char* Start = List; *Start; Start += *Start ? 1 : 0) { ++ size_t Length = strcspn(Start, ": "); ++ fextl::string Entry(Start, Length); ++ Start += Length; ++ if (Entry.empty()) { ++ continue; ++ } ++ if (Entry[0] == '/') { ++ auto Type = ::ELFLoader::ELFContainer::GetELFType(ResolveRootfsFile(Entry, RootFS)); ++ if (Type == ::ELFLoader::ELFContainer::TYPE_NONE) { ++ Type = ::ELFLoader::ELFContainer::GetELFType(Entry); ++ } ++ if (Type == ::ELFLoader::ELFContainer::TYPE_OTHER_ELF) { ++ continue; ++ } ++ } ++ if (!Result.empty()) { ++ Result += ':'; ++ } ++ Result += Entry; ++ } ++ return Result; ++ } ++ + static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) { + // If the path is relative then just run that + if (File[0] != '/') { +@@ -330,6 +356,13 @@ public: + if (envp[i] == nullptr) { + break; + } ++ if (strncmp(envp[i], "LD_PRELOAD=", 11) == 0) { ++ auto Preload = GuestPreload(envp[i] + 11, RootFS); ++ if (!Preload.empty()) { ++ EnvironmentVariables.emplace_back("LD_PRELOAD=" + Preload); ++ } ++ continue; ++ } + EnvironmentVariables.emplace_back(envp[i]); + } + } diff --git a/tools/fex/patches/0015-gl-thunk-overlays-libopengl.patch b/tools/fex/patches/0015-gl-thunk-overlays-libopengl.patch new file mode 100644 index 0000000000..b1557d3c39 --- /dev/null +++ b/tools/fex/patches/0015-gl-thunk-overlays-libopengl.patch @@ -0,0 +1,15 @@ +diff --git a/Data/ThunksDB.json b/Data/ThunksDB.json +index d52ff04..886379a 100644 +--- a/Data/ThunksDB.json ++++ b/Data/ThunksDB.json +@@ -6,7 +6,9 @@ + "@PREFIX_LIB@/libGL.so", + "@PREFIX_LIB@/libGL.so.1", + "@PREFIX_LIB@/libGL.so.1.2.0", +- "@PREFIX_LIB@/libGL.so.1.7.0" ++ "@PREFIX_LIB@/libGL.so.1.7.0", ++ "@PREFIX_LIB@/libOpenGL.so.0", ++ "@PREFIX_LIB@/libOpenGL.so.0.0.0" + ] + }, + "Vulkan": { diff --git a/tools/fex/patches/0016-identity-syscalls-through-libc.patch b/tools/fex/patches/0016-identity-syscalls-through-libc.patch new file mode 100644 index 0000000000..3823e28e1d --- /dev/null +++ b/tools/fex/patches/0016-identity-syscalls-through-libc.patch @@ -0,0 +1,106 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 4c3be85..e287cd2 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -209,6 +209,13 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, + } + #endif + ++template<int syscall_num> ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough0(FEXCore::Core::CpuStateFrame* Frame) { ++ uint64_t Result = ::syscall(syscall_num); ++ SYSCALL_ERRNO(); ++} ++ + template<int syscall_num> + requires (syscall_num != -1) + uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) { +@@ -278,29 +285,29 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(chdir, SyscallPathPassthrough1<SYSCALL_DEF(chdir)>); + REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1<SYSCALL_DEF(fchdir)>); + REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2<SYSCALL_DEF(fchmod)>); +- REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3<SYSCALL_DEF(fchown)>); ++ REGISTER_SYSCALL_IMPL(fchown, SyscallPathPassthrough3<SYSCALL_DEF(fchown)>); + REGISTER_SYSCALL_IMPL(umask, SyscallPassthrough1<SYSCALL_DEF(umask)>); +- REGISTER_SYSCALL_IMPL(getuid, SyscallPassthrough0<SYSCALL_DEF(getuid)>); ++ REGISTER_SYSCALL_IMPL(getuid, SyscallPathPassthrough0<SYSCALL_DEF(getuid)>); + REGISTER_SYSCALL_IMPL(syslog, SyscallPassthrough3<SYSCALL_DEF(syslog)>); +- REGISTER_SYSCALL_IMPL(getgid, SyscallPassthrough0<SYSCALL_DEF(getgid)>); +- REGISTER_SYSCALL_IMPL(setuid, SyscallPassthrough1<SYSCALL_DEF(setuid)>); +- REGISTER_SYSCALL_IMPL(setgid, SyscallPassthrough1<SYSCALL_DEF(setgid)>); +- REGISTER_SYSCALL_IMPL(geteuid, SyscallPassthrough0<SYSCALL_DEF(geteuid)>); +- REGISTER_SYSCALL_IMPL(getegid, SyscallPassthrough0<SYSCALL_DEF(getegid)>); ++ REGISTER_SYSCALL_IMPL(getgid, SyscallPathPassthrough0<SYSCALL_DEF(getgid)>); ++ REGISTER_SYSCALL_IMPL(setuid, SyscallPathPassthrough1<SYSCALL_DEF(setuid)>); ++ REGISTER_SYSCALL_IMPL(setgid, SyscallPathPassthrough1<SYSCALL_DEF(setgid)>); ++ REGISTER_SYSCALL_IMPL(geteuid, SyscallPathPassthrough0<SYSCALL_DEF(geteuid)>); ++ REGISTER_SYSCALL_IMPL(getegid, SyscallPathPassthrough0<SYSCALL_DEF(getegid)>); + REGISTER_SYSCALL_IMPL(setpgid, SyscallPassthrough2<SYSCALL_DEF(setpgid)>); + REGISTER_SYSCALL_IMPL(getppid, SyscallPassthrough0<SYSCALL_DEF(getppid)>); + REGISTER_SYSCALL_IMPL(setsid, SyscallPassthrough0<SYSCALL_DEF(setsid)>); +- REGISTER_SYSCALL_IMPL(setreuid, SyscallPassthrough2<SYSCALL_DEF(setreuid)>); +- REGISTER_SYSCALL_IMPL(setregid, SyscallPassthrough2<SYSCALL_DEF(setregid)>); +- REGISTER_SYSCALL_IMPL(getgroups, SyscallPassthrough2<SYSCALL_DEF(getgroups)>); +- REGISTER_SYSCALL_IMPL(setgroups, SyscallPassthrough2<SYSCALL_DEF(setgroups)>); +- REGISTER_SYSCALL_IMPL(setresuid, SyscallPassthrough3<SYSCALL_DEF(setresuid)>); +- REGISTER_SYSCALL_IMPL(getresuid, SyscallPassthrough3<SYSCALL_DEF(getresuid)>); +- REGISTER_SYSCALL_IMPL(setresgid, SyscallPassthrough3<SYSCALL_DEF(setresgid)>); +- REGISTER_SYSCALL_IMPL(getresgid, SyscallPassthrough3<SYSCALL_DEF(getresgid)>); ++ REGISTER_SYSCALL_IMPL(setreuid, SyscallPathPassthrough2<SYSCALL_DEF(setreuid)>); ++ REGISTER_SYSCALL_IMPL(setregid, SyscallPathPassthrough2<SYSCALL_DEF(setregid)>); ++ REGISTER_SYSCALL_IMPL(getgroups, SyscallPathPassthrough2<SYSCALL_DEF(getgroups)>); ++ REGISTER_SYSCALL_IMPL(setgroups, SyscallPathPassthrough2<SYSCALL_DEF(setgroups)>); ++ REGISTER_SYSCALL_IMPL(setresuid, SyscallPathPassthrough3<SYSCALL_DEF(setresuid)>); ++ REGISTER_SYSCALL_IMPL(getresuid, SyscallPathPassthrough3<SYSCALL_DEF(getresuid)>); ++ REGISTER_SYSCALL_IMPL(setresgid, SyscallPathPassthrough3<SYSCALL_DEF(setresgid)>); ++ REGISTER_SYSCALL_IMPL(getresgid, SyscallPathPassthrough3<SYSCALL_DEF(getresgid)>); + REGISTER_SYSCALL_IMPL(getpgid, SyscallPassthrough1<SYSCALL_DEF(getpgid)>); +- REGISTER_SYSCALL_IMPL(setfsuid, SyscallPassthrough1<SYSCALL_DEF(setfsuid)>); +- REGISTER_SYSCALL_IMPL(setfsgid, SyscallPassthrough1<SYSCALL_DEF(setfsgid)>); ++ REGISTER_SYSCALL_IMPL(setfsuid, SyscallPathPassthrough1<SYSCALL_DEF(setfsuid)>); ++ REGISTER_SYSCALL_IMPL(setfsgid, SyscallPathPassthrough1<SYSCALL_DEF(setfsgid)>); + REGISTER_SYSCALL_IMPL(getsid, SyscallPassthrough1<SYSCALL_DEF(getsid)>); + REGISTER_SYSCALL_IMPL(capget, SyscallPassthrough2<SYSCALL_DEF(capget)>); + REGISTER_SYSCALL_IMPL(capset, SyscallPassthrough2<SYSCALL_DEF(capset)>); +@@ -537,23 +544,23 @@ namespace x64 { + namespace x32 { + void RegisterPassthrough(FEX::HLE::SyscallHandler* Handler) { + RegisterCommon(Handler); +- REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPassthrough0<SYSCALL_DEF(getuid)>); +- REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPassthrough0<SYSCALL_DEF(getgid)>); +- REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPassthrough0<SYSCALL_DEF(geteuid)>); +- REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPassthrough0<SYSCALL_DEF(getegid)>); +- REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPassthrough2<SYSCALL_DEF(setreuid)>); +- REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPassthrough2<SYSCALL_DEF(setregid)>); +- REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPassthrough2<SYSCALL_DEF(getgroups)>); +- REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPassthrough2<SYSCALL_DEF(setgroups)>); +- REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPassthrough3<SYSCALL_DEF(fchown)>); +- REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPassthrough3<SYSCALL_DEF(setresuid)>); +- REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPassthrough3<SYSCALL_DEF(getresuid)>); +- REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPassthrough3<SYSCALL_DEF(setresgid)>); +- REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPassthrough3<SYSCALL_DEF(getresgid)>); +- REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPassthrough1<SYSCALL_DEF(setuid)>); +- REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPassthrough1<SYSCALL_DEF(setgid)>); +- REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPassthrough1<SYSCALL_DEF(setfsuid)>); +- REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPassthrough1<SYSCALL_DEF(setfsgid)>); ++ REGISTER_SYSCALL_IMPL_X32(getuid32, SyscallPathPassthrough0<SYSCALL_DEF(getuid)>); ++ REGISTER_SYSCALL_IMPL_X32(getgid32, SyscallPathPassthrough0<SYSCALL_DEF(getgid)>); ++ REGISTER_SYSCALL_IMPL_X32(geteuid32, SyscallPathPassthrough0<SYSCALL_DEF(geteuid)>); ++ REGISTER_SYSCALL_IMPL_X32(getegid32, SyscallPathPassthrough0<SYSCALL_DEF(getegid)>); ++ REGISTER_SYSCALL_IMPL_X32(setreuid32, SyscallPathPassthrough2<SYSCALL_DEF(setreuid)>); ++ REGISTER_SYSCALL_IMPL_X32(setregid32, SyscallPathPassthrough2<SYSCALL_DEF(setregid)>); ++ REGISTER_SYSCALL_IMPL_X32(getgroups32, SyscallPathPassthrough2<SYSCALL_DEF(getgroups)>); ++ REGISTER_SYSCALL_IMPL_X32(setgroups32, SyscallPathPassthrough2<SYSCALL_DEF(setgroups)>); ++ REGISTER_SYSCALL_IMPL_X32(fchown32, SyscallPathPassthrough3<SYSCALL_DEF(fchown)>); ++ REGISTER_SYSCALL_IMPL_X32(setresuid32, SyscallPathPassthrough3<SYSCALL_DEF(setresuid)>); ++ REGISTER_SYSCALL_IMPL_X32(getresuid32, SyscallPathPassthrough3<SYSCALL_DEF(getresuid)>); ++ REGISTER_SYSCALL_IMPL_X32(setresgid32, SyscallPathPassthrough3<SYSCALL_DEF(setresgid)>); ++ REGISTER_SYSCALL_IMPL_X32(getresgid32, SyscallPathPassthrough3<SYSCALL_DEF(getresgid)>); ++ REGISTER_SYSCALL_IMPL_X32(setuid32, SyscallPathPassthrough1<SYSCALL_DEF(setuid)>); ++ REGISTER_SYSCALL_IMPL_X32(setgid32, SyscallPathPassthrough1<SYSCALL_DEF(setgid)>); ++ REGISTER_SYSCALL_IMPL_X32(setfsuid32, SyscallPathPassthrough1<SYSCALL_DEF(setfsuid)>); ++ REGISTER_SYSCALL_IMPL_X32(setfsgid32, SyscallPathPassthrough1<SYSCALL_DEF(setfsgid)>); + REGISTER_SYSCALL_IMPL_X32(sendfile64, SyscallPassthrough4<SYSCALL_DEF(sendfile)>); + REGISTER_SYSCALL_IMPL_X32(clock_gettime64, SyscallPassthrough2<SYSCALL_DEF(clock_gettime)>); + REGISTER_SYSCALL_IMPL_X32(clock_settime64, SyscallPassthrough2<SYSCALL_DEF(clock_settime)>); diff --git a/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch b/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch new file mode 100644 index 0000000000..2192b9b0af --- /dev/null +++ b/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch @@ -0,0 +1,26 @@ +diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +index 2881ad9..abc84f3 100644 +--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp ++++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +@@ -518,7 +518,7 @@ int main(int argc, char** argv, char** const envp) { + FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, Program.ProgramName); + } else { + // Anonymous program. +- FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, "<Anonymous>"); ++ FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, Program.ProgramPath); + FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, "<Anonymous>"); + } + } else { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +index a7a432b..4a77d87 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +@@ -441,7 +441,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + if (*OldArgv) { + // The direct fallback uses the executable path as argv[0]. An FD-backed load uses the + // binfmt preserve-argv0 layout, so the caller-supplied argv[0] has to stay in the vector. +- if (!NeedsLoaderFD) { ++ if (!NeedsLoaderFD && !IsFDExec) { + ++OldArgv; + } + while (*OldArgv) { diff --git a/tools/fex/patches/0018-socket-credentials-through-libc.patch b/tools/fex/patches/0018-socket-credentials-through-libc.patch new file mode 100644 index 0000000000..d7ac6a2b12 --- /dev/null +++ b/tools/fex/patches/0018-socket-credentials-through-libc.patch @@ -0,0 +1,18 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index e287cd2..2181667 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -469,10 +469,10 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(setitimer, SyscallPassthrough3<SYSCALL_DEF(setitimer)>); + REGISTER_SYSCALL_IMPL_X64(sendfile, SyscallPassthrough4<SYSCALL_DEF(sendfile)>); + REGISTER_SYSCALL_IMPL_X64(accept, SyscallPassthrough3<SYSCALL_DEF(accept)>); +- REGISTER_SYSCALL_IMPL_X64(sendmsg, SyscallPassthrough3<SYSCALL_DEF(sendmsg)>); +- REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPassthrough3<SYSCALL_DEF(recvmsg)>); ++ REGISTER_SYSCALL_IMPL_X64(sendmsg, SyscallPathPassthrough3<SYSCALL_DEF(sendmsg)>); ++ REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPathPassthrough3<SYSCALL_DEF(recvmsg)>); + REGISTER_SYSCALL_IMPL_X64(setsockopt, SyscallPassthrough5<SYSCALL_DEF(setsockopt)>); +- REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPassthrough5<SYSCALL_DEF(getsockopt)>); ++ REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPathPassthrough5<SYSCALL_DEF(getsockopt)>); + REGISTER_SYSCALL_IMPL_X64(wait4, SyscallPassthrough4<SYSCALL_DEF(wait4)>); + REGISTER_SYSCALL_IMPL_X64(semop, SyscallPassthrough3<SYSCALL_DEF(semop)>); + REGISTER_SYSCALL_IMPL_X64(getrlimit, SyscallPassthrough2<SYSCALL_DEF(getrlimit)>); diff --git a/tools/fex/probes/async-signal-context.c b/tools/fex/probes/async-signal-context.c new file mode 100644 index 0000000000..9c2c262a5b --- /dev/null +++ b/tools/fex/probes/async-signal-context.c @@ -0,0 +1,84 @@ +#define _GNU_SOURCE +#include <pthread.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/syscall.h> +#include <ucontext.h> +#include <unistd.h> + +volatile long base; +static volatile long hits, matched, stale, stop; +static long want; +static pid_t target; +extern char probe_loop_start[], probe_loop_end[]; + +static void handler(int sig, siginfo_t *info, void *context) { + greg_t *g = ((ucontext_t *)context)->uc_mcontext.gregs; + (void)sig; + (void)info; + if (g[REG_RIP] >= (greg_t)probe_loop_start && g[REG_RIP] < (greg_t)probe_loop_end) { + long below = base - g[REG_RSP]; + if (g[REG_RBX] == 0x1111111111111111L && g[REG_R12] == 0x2222222222222222L && g[REG_R13] == 0x3333333333333333L && + g[REG_R14] == 0x4444444444444444L && g[REG_R15] == 0x5555555555555555L && (unsigned long)g[REG_RCX] <= 4096 && + (below == 0 || below == 8)) + matched++; + else + stale++; + } + hits++; +} + +static void *sender(void *arg) { + (void)arg; + while (!stop) { + syscall(SYS_tgkill, getpid(), target, SIGUSR1); + usleep(50); + } + return NULL; +} + +int main(int argc, char **argv) { + struct sigaction action = {0}; + pthread_t thread; + want = argc > 1 ? atol(argv[1]) : 2000; + action.sa_sigaction = handler; + action.sa_flags = SA_SIGINFO | SA_RESTART; + sigaction(SIGUSR1, &action, NULL); + sigset_t usr1; + sigemptyset(&usr1); + sigaddset(&usr1, SIGUSR1); + pthread_sigmask(SIG_UNBLOCK, &usr1, NULL); + target = syscall(SYS_gettid); + if (pthread_create(&thread, NULL, sender, NULL) != 0) { + fprintf(stderr, "cannot start the signal sender\n"); + return 2; + } + while (matched + stale < want) { + __asm__ volatile("mov $0x1111111111111111, %%rbx\n" + "mov $0x2222222222222222, %%r12\n" + "mov $0x3333333333333333, %%r13\n" + "mov $0x4444444444444444, %%r14\n" + "mov $0x5555555555555555, %%r15\n" + "mov %%rsp, base(%%rip)\n" + "mov $4096, %%ecx\n" + ".globl probe_loop_start\n" + "probe_loop_start:\n" + "push %%rax\n" + "1: dec %%ecx\n" + "jnz 1b\n" + "pop %%rax\n" + "mov $4096, %%ecx\n" + "2: dec %%ecx\n" + "jnz 2b\n" + ".globl probe_loop_end\n" + "probe_loop_end:\n" + : + : + : "rbx", "rcx", "r12", "r13", "r14", "r15", "memory"); + } + stop = 1; + pthread_join(thread, NULL); + printf("signals=%ld matched=%ld stale=%ld\n", hits, matched, stale); + return stale ? 1 : 0; +} diff --git a/tools/fex/probes/signal-handler-escape.c b/tools/fex/probes/signal-handler-escape.c new file mode 100644 index 0000000000..71e1a12fca --- /dev/null +++ b/tools/fex/probes/signal-handler-escape.c @@ -0,0 +1,90 @@ +#define _GNU_SOURCE +#include <setjmp.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +static sigjmp_buf main_env, inner_env; +static volatile int depth, nested_mode; +static volatile long escapes, nested, returns, wrong; + +static void fault(long i) { + *(volatile int *)(long)(8 + (i & 7)) = 1; +} + +static void segv(int sig, siginfo_t *info, void *context) { + (void)sig; + (void)info; + (void)context; + if (!nested_mode) { + escapes++; + siglongjmp(main_env, 1); + } + if (depth == 1) { + nested++; + siglongjmp(inner_env, 1); + } + depth = 1; + for (volatile int k = 0; k < 3; k++) + if (sigsetjmp(inner_env, 0) == 0) + fault(k); + depth = 0; + escapes++; + siglongjmp(main_env, 1); +} + +static void trap(int sig, siginfo_t *info, void *context) { + (void)sig; + (void)info; + (void)context; + returns++; +} + +static void install(int onstack) { + struct sigaction action; + memset(&action, 0, sizeof(action)); + action.sa_sigaction = segv; + action.sa_flags = SA_SIGINFO | SA_NODEFER | (onstack ? SA_ONSTACK : 0); + sigaction(SIGSEGV, &action, NULL); +} + +static long run(long count, int with_trap) { + long start = escapes; + for (volatile long i = 0; i < count; i++) { + if (with_trap) { + volatile long before = i * 3; + __asm__ volatile("int3" ::: "memory"); + if (before != i * 3) + wrong++; + } + if (sigsetjmp(main_env, 1) == 0) + fault(i); + } + return escapes - start; +} + +int main(int argc, char **argv) { + long want = argc > 1 ? atol(argv[1]) : 50000; + stack_t ss = {.ss_sp = malloc(262144), .ss_size = 262144}; + struct sigaction action; + sigaltstack(&ss, NULL); + memset(&action, 0, sizeof(action)); + action.sa_sigaction = trap; + action.sa_flags = SA_SIGINFO; + sigaction(SIGTRAP, &action, NULL); + + install(1); + long onstack = run(want, 0); + install(0); + long offstack = run(want, 0); + install(1); + long mixed = run(want, 1); + nested_mode = 1; + long outer = run(want, 0); + + printf("onstack=%ld offstack=%ld mixed=%ld returns=%ld outer=%ld nested=%ld wrong=%ld\n", onstack, offstack, mixed, returns, + outer, nested, wrong); + return onstack == want && offstack == want && mixed == want && returns == want && outer == want && nested == 3 * want && !wrong ? 0 + : 1; +} diff --git a/tools/fex/probes/signal-register-update.c b/tools/fex/probes/signal-register-update.c new file mode 100644 index 0000000000..a1fdaec4d5 --- /dev/null +++ b/tools/fex/probes/signal-register-update.c @@ -0,0 +1,88 @@ +#define _GNU_SOURCE +#include <signal.h> +#include <stdio.h> +#include <string.h> +#include <sys/time.h> +#include <ucontext.h> + +#define MARK 0x5eed + +static volatile sig_atomic_t alarms; +static volatile sig_atomic_t give_up; + +static void count_alarm(void) { + if (++alarms > 100) { + give_up = 1; + } +} + +static void on_alarm(int sig, siginfo_t *si, void *ctx) { + (void)sig; + (void)si; + ucontext_t *uc = ctx; + count_alarm(); +#ifdef __x86_64__ + uc->uc_mcontext.gregs[REG_R12] = MARK; +#else + uc->uc_mcontext.gregs[REG_ESI] = MARK; +#endif +} + +#ifdef __i386__ +static void on_alarm_legacy(int sig, struct sigcontext sc) { + (void)sig; + count_alarm(); + ((volatile struct sigcontext *)&sc)->esi = MARK; +} +#endif + +int main(int argc, char **argv) { + int legacy = argc > 1 && strcmp(argv[1], "legacy") == 0; + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_flags = SA_RESTART; +#ifdef __i386__ + if (legacy) { + sa.sa_handler = (void (*)(int))on_alarm_legacy; + } else +#endif + { + legacy = 0; + sa.sa_sigaction = on_alarm; + sa.sa_flags |= SA_SIGINFO; + } + sigaction(SIGALRM, &sa, NULL); + struct itimerval it = {{0, 20000}, {0, 20000}}; + setitimer(ITIMER_REAL, &it, NULL); + + unsigned long spins, seen; +#ifdef __x86_64__ + __asm__ volatile("xor %%r12, %%r12\n" + "xor %0, %0\n" + "1: inc %0\n" + "test %%r12, %%r12\n" + "jnz 2f\n" + "cmpl $0, %2\n" + "je 1b\n" + "2: mov %%r12, %1\n" + : "=&r"(spins), "=&r"(seen) + : "m"(give_up) + : "r12", "cc"); +#else + __asm__ volatile("xor %%esi, %%esi\n" + "xor %0, %0\n" + "1: inc %0\n" + "test %%esi, %%esi\n" + "jnz 2f\n" + "cmpl $0, %2\n" + "je 1b\n" + "2: mov %%esi, %1\n" + : "=&r"(spins), "=&r"(seen) + : "m"(give_up) + : "esi", "cc"); +#endif + struct itimerval off = {{0, 0}, {0, 0}}; + setitimer(ITIMER_REAL, &off, NULL); + printf("frame=%s seen=%d alarms=%d spins=%lu\n", legacy ? "legacy" : "rt", seen == MARK, (int)alarms, spins); + return seen == MARK ? 0 : 1; +} diff --git a/tools/fex/probes/syscall-host-stack.c b/tools/fex/probes/syscall-host-stack.c new file mode 100644 index 0000000000..bd348fcfd3 --- /dev/null +++ b/tools/fex/probes/syscall-host-stack.c @@ -0,0 +1,65 @@ +#define _GNU_SOURCE +#include <cpuid.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/syscall.h> + +#define YMM_STEP(a, b) "vpaddq %%ymm" #b ", %%ymm" #a ", %%ymm" #a "\n" +#define MMX_STEP(a, b) "paddq %%mm" #b ", %%mm" #a "\n" + +static int has_avx2(void) { + unsigned a, b, c, d; + if (!__get_cpuid(1, &a, &b, &c, &d) || !(c & bit_AVX) || !(c & bit_OSXSAVE)) + return 0; + unsigned lo, hi; + __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); + if ((lo & 6) != 6 || !__get_cpuid_count(7, 0, &a, &b, &c, &d)) + return 0; + return (b & bit_AVX2) != 0; +} + +static long ymm_round(long n) { + long pid = 0; + for (long i = 0; i < n; i++) { + __asm__ volatile( + YMM_STEP(0, 1) YMM_STEP(1, 2) YMM_STEP(2, 3) YMM_STEP(3, 4) YMM_STEP(4, 5) YMM_STEP(5, 6) YMM_STEP(6, 7) YMM_STEP(7, 8) + YMM_STEP(8, 9) YMM_STEP(9, 10) YMM_STEP(10, 11) YMM_STEP(11, 12) YMM_STEP(12, 13) YMM_STEP(13, 14) YMM_STEP(14, 15) + YMM_STEP(15, 0) YMM_STEP(0, 15) YMM_STEP(1, 14) YMM_STEP(2, 13) YMM_STEP(3, 12) YMM_STEP(4, 11) YMM_STEP(5, 10) + YMM_STEP(6, 9) YMM_STEP(7, 8) + "mov %1, %%eax\n" + "syscall\n" + : "=a"(pid) + : "i"(SYS_getpid) + : "rcx", "r11", "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", + "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"); + } + __asm__ volatile("vzeroupper" ::: "memory"); + return pid; +} + +static long mmx_round(long n) { + long pid = 0; + for (long i = 0; i < n; i++) { + __asm__ volatile( + MMX_STEP(0, 1) MMX_STEP(1, 2) MMX_STEP(2, 3) MMX_STEP(3, 4) MMX_STEP(4, 5) MMX_STEP(5, 6) MMX_STEP(6, 7) MMX_STEP(7, 0) + "mov %1, %%eax\n" + "syscall\n" + : "=a"(pid) + : "i"(SYS_getpid) + : "rcx", "r11", "memory", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7"); + } + __asm__ volatile("emms" ::: "memory"); + return pid; +} + +int main(int argc, char **argv) { + long want = argc > 1 ? atol(argv[1]) : 2000000; + int avx = has_avx2(); + long done = 0; + for (; done < want; done += 1000) { + if (avx ? ymm_round(1000) <= 0 : mmx_round(1000) <= 0) + return 2; + } + printf("mode=%s syscalls=%ld\n", avx ? "avx" : "mmx", done); + return 0; +} diff --git a/tools/fex/probes/vdso-signal-state.c b/tools/fex/probes/vdso-signal-state.c new file mode 100644 index 0000000000..56057594c3 --- /dev/null +++ b/tools/fex/probes/vdso-signal-state.c @@ -0,0 +1,49 @@ +#define _GNU_SOURCE +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/time.h> +#include <time.h> + +static volatile sig_atomic_t alarms; + +static void on_alarm(int sig) { + (void)sig; + alarms++; +} + +int main(int argc, char **argv) { + int seconds = argc > 1 ? atoi(argv[1]) : 3; + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = on_alarm; + sa.sa_flags = SA_RESTART; + sigaction(SIGALRM, &sa, NULL); + struct itimerval it = {{0, 1000}, {0, 1000}}; + setitimer(ITIMER_REAL, &it, NULL); + + struct timespec start, now, last; + clock_gettime(CLOCK_MONOTONIC, &start); + last = start; + unsigned long calls = 0, bad = 0; + unsigned long a = 1, b = 3, c = 1 ^ 0x5a5a5a5a5a5a5a5aUL; + do { + clock_gettime(CLOCK_MONOTONIC, &now); + calls++; + __asm__ volatile("" : "+r"(a), "+r"(b), "+r"(c)); + if (b != a * 3 || c != (a ^ 0x5a5a5a5a5a5a5a5aUL)) + bad++; + if (now.tv_sec < last.tv_sec || (now.tv_sec == last.tv_sec && now.tv_nsec < last.tv_nsec)) + bad++; + last = now; + a = a * 6364136223846793005UL + 1442695040888963407UL; + b = a * 3; + c = a ^ 0x5a5a5a5a5a5a5a5aUL; + } while ((now.tv_sec - start.tv_sec) * 1000000000L + (now.tv_nsec - start.tv_nsec) < seconds * 1000000000L); + + struct itimerval off = {{0, 0}, {0, 0}}; + setitimer(ITIMER_REAL, &off, NULL); + printf("calls=%lu alarms=%d bad=%lu\n", calls, (int)alarms, bad); + return bad || alarms == 0; +} diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 953bab4a0c..bf14bf25b5 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -358,3 +358,70 @@ and clears the held flag. wlroots counts repeated presses of one button and send reaches zero, so a second finger touching before the first lifted left the button pressed in the seat for good: the game saw a held click, and later taps only raised and lowered the count. A finger now presses the button only when no earlier finger holds it. `tools/tests/test_gamescope_touch_click.py` compiles the rule from this patch. + +## 0135 Wayland backend: a limit on the planes handed to the host + +`wayland_overlay_planes` says how many planes above the base one the host compositor shows without composing them +itself. With more layers than that, gamescope composites them into one picture, as it already does for a scaler or +`composite_force`. -1, the default, keeps every layer on its own plane. The app sets it while a host that shows the +game picture directly cannot give an overlay a display layer of its own, so the overlay is drawn into the game +picture here and the frame still reaches the display without a copy. + +## 0136 rendervulkan, Wayland backend: composite only into output images the host has released + +The composite output images were used in a fixed rotation of three, with no check that the host compositor had +released the one about to be written. A host that puts the buffer on the display itself, without copying it, was +still reading that image when the next composite wrote into it. A backend framebuffer now says whether the host +holds it, the Wayland backend answers from the buffer's release event, and the composite takes the next image the +host does not hold. Backends that are not a session get five images instead of three, so one is free while the +host holds two and the last and deferred pictures stay intact. Session backends keep three images and their order. + +## 0137 Wayland backend: the host's refresh rates and the app's target + +A nested session had one refresh rate, the host's, so Steam offered no refresh control and a frame limit never moved +the display. The backend binds the host's `droiddeck_refresh_v1`, takes the list of rates the host display can switch +between and returns it as the connector's dynamic refresh rates, so the rates reach Steam with the rest of the +display state and are sent again when the list changes. On every present it tells the host the refresh rate the +frame limit resolves to and the limit itself; the host switches its display and the new rate comes back through +`wl_output`, which the nested refresh already follows. A host without the global leaves all of this as it was. + +## 0138 Frame limiter: a limit the refresh rate does not divide is spread evenly + +The limiter held a window for a whole number of refreshes, the refresh rate divided by the limit and rounded down. A +limit of 45 or 40 on a 60 Hz display rounded to one refresh per frame, so the limit did nothing, and each frame was +timed from the moment the previous one was shown, so a late frame pushed every frame after it. The limited cycle is +now the exact time between frames at the limit, and each window keeps the time its next frame is due on that line. +A frame is released on the refresh nearest its due time: 45 on 60 Hz shows frames for one, one and two refreshes in +turn, 40 for one and two, and a limit that divides the refresh rate is paced as before. A frame that arrives most of a +refresh late, or more than a refresh early, starts the line again from that frame, so a stall is not followed by a +burst. `tools/tests/test_gamescope_limiter_cadence.py` compiles the two rules from this patch and runs them across +refresh rates and limits. + +## 0139 HDR output can be switched while a session runs + +The Wayland backend read `hdr_enabled` once, when the host compositor described its output, and kept the answer: a +session started with HDR off told its clients the display had no HDR for as long as it ran, and its environment +carried `DXVK_HDR=0`. Whether the display can show HDR now comes from the host's output description alone, and +`hdr_enabled` decides only whether HDR is used, so setting it during a session takes effect on the next frame in +either direction. The 10-bit output format is chosen only while HDR is enabled, so an SDR session keeps the 8-bit +output it had, and the output images are made again in the other format when the setting changes. On a display that can show HDR, a session that starts with HDR off leaves `DXVK_HDR` unset instead of +forcing it to 0, so a game started after HDR is switched on finds it. + +## 0140 Focus is chosen again when a window turns visible or fully transparent + +A window is a focus candidate only while its `_NET_WM_WINDOW_OPACITY` is above zero, but a change of that property +did not ask for focus to be chosen again. Wine sets the property for layered windows, and a window that fades in maps +fully transparent, so it was skipped when it mapped and stayed skipped once it was opaque until something else +changed focus. In a nested session with no other window the SDL window stayed hidden, and the game ran with nothing +on screen. Focus is now chosen again whenever a window's opacity crosses zero in either direction; a change between +two visible opacities leaves focus alone. `tools/tests/test_gamescope_focus_opacity.py` compiles the rule from this +patch and checks the property handler applies it. + +## 0141 wlserver: the nested mouse moves the pointer while touch is Disabled + +The nested Wayland pointer reaches wlserver as touch 0 (`bAlwaysWarpCursor`, see 0111), and in the Disabled touch click +mode `wlserver_touchmotion` returned before anything moved. Buttons take `wlserver_mousebutton`, so they still arrived, +at a pointer that never left the top-left corner. Steam picks Disabled for some games (Don't Starve Together): the drawn +cursor followed the mouse while every click landed at (0,0). In Disabled the nested pointer now warps the X pointer as +in the other modes; real fingers are still ignored. `tools/tests/test_gamescope_disabled_touch_mouse.py` compiles the +branch from this patch. diff --git a/tools/gamescope/patches/0135-wayland-overlay-plane-limit.patch b/tools/gamescope/patches/0135-wayland-overlay-plane-limit.patch new file mode 100644 index 0000000000..7961ec5050 --- /dev/null +++ b/tools/gamescope/patches/0135-wayland-overlay-plane-limit.patch @@ -0,0 +1,20 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 372fc08..fe38c7d 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -126,6 +126,7 @@ namespace gamescope + gamescope::ConVar<bool> cv_wayland_mouse_warp_without_keyboard_focus( "wayland_mouse_warp_without_keyboard_focus", true, "Should we only forward mouse warps to the app when we have keyboard focus?" ); + gamescope::ConVar<bool> cv_wayland_mouse_relmotion_without_keyboard_focus( "wayland_mouse_relmotion_without_keyboard_focus", false, "Should we only forward mouse relative motion to the app when we have keyboard focus?" ); + gamescope::ConVar<bool> cv_wayland_use_modifiers( "wayland_use_modifiers", true, "Use DMA-BUF modifiers?" ); ++ gamescope::ConVar<int> cv_wayland_overlay_planes( "wayland_overlay_planes", -1, "How many planes above the base one the host shows without composing them itself; more are composited here into one. -1 for no limit." ); + + gamescope::ConVar<float> cv_wayland_hdr10_saturation_scale( "wayland_hdr10_saturation_scale", 1.0, "Saturation scale for HDR10 content by gamut expansion. 1.0 - 1.2 is a good range to play with." ); + +@@ -1102,6 +1103,7 @@ namespace gamescope + eLayer0Filter == GamescopeUpscaleFilter::PIXEL ) && !bLayer0ScreenSize; + + bNeedsFullComposite |= cv_composite_force; ++ bNeedsFullComposite |= cv_wayland_overlay_planes >= 0 && pFrameInfo->layers.count() > 1 + cv_wayland_overlay_planes; + bNeedsFullComposite |= pFrameInfo->useFSRLayer0; + bNeedsFullComposite |= pFrameInfo->useNISLayer0; + bNeedsFullComposite |= pFrameInfo->useSGSRLayer0; diff --git a/tools/gamescope/patches/0136-composite-into-released-output-images.patch b/tools/gamescope/patches/0136-composite-into-released-output-images.patch new file mode 100644 index 0000000000..2f827f8703 --- /dev/null +++ b/tools/gamescope/patches/0136-composite-into-released-output-images.patch @@ -0,0 +1,218 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index fe38c7d..be99e6d 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -503,6 +503,8 @@ namespace gamescope + wl_buffer *GetHostBuffer() const { return m_pHostBuffer; } + wlr_buffer *GetClientBuffer() const { return m_pClientBuffer; } + ++ bool HeldByHost() const override { return m_bCompositorAcquired; } ++ + void Wayland_Buffer_Release( wl_buffer *pBuffer ); + static const wl_buffer_listener s_BufferListener; + +diff --git a/src/backend.h b/src/backend.h +index fbfa7c7..30b42ca 100644 +--- a/src/backend.h ++++ b/src/backend.h +@@ -288,6 +288,8 @@ namespace gamescope + virtual void SetReleasePoint( std::shared_ptr<CReleaseTimelinePoint> pReleasePoint ) = 0; + + virtual IBackendFb *EnsureImported() = 0; ++ ++ virtual bool HeldByHost() const { return false; } + }; + + class IBackendPlane +diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp +index 0835bfe..42cc9c4 100644 +--- a/src/rendervulkan.cpp ++++ b/src/rendervulkan.cpp +@@ -3644,15 +3644,12 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput ) + outputImageflags.bSampled = true; // for pipewire blits + outputImageflags.bOutputImage = true; + +- pOutput->outputImages.resize(3); // extra image for partial composition. +- pOutput->outputImagesPartialOverlay.resize(3); ++ const uint32_t uImageCount = GetBackend()->IsSessionBased() ? 3u : 5u; + +- pOutput->outputImages[0] = nullptr; +- pOutput->outputImages[1] = nullptr; +- pOutput->outputImages[2] = nullptr; +- pOutput->outputImagesPartialOverlay[0] = nullptr; +- pOutput->outputImagesPartialOverlay[1] = nullptr; +- pOutput->outputImagesPartialOverlay[2] = nullptr; ++ pOutput->outputImages.clear(); ++ pOutput->outputImagesPartialOverlay.clear(); ++ pOutput->outputImages.resize( uImageCount ); ++ pOutput->outputImagesPartialOverlay.resize( uImageCount ); + + uint32_t uDRMFormat = pOutput->uOutputFormat; + +@@ -3662,28 +3659,14 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput ) + if ( g_uOutputRotation & 1u ) + std::swap( uOutputWidth, uOutputHeight ); + +- pOutput->outputImages[0] = new CVulkanTexture(); +- bool bSuccess = pOutput->outputImages[0]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImages[1] = new CVulkanTexture(); +- bSuccess = pOutput->outputImages[1]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ); +- if ( bSuccess != true ) ++ for ( uint32_t i = 0; i < uImageCount; i++ ) + { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImages[2] = new CVulkanTexture(); +- bSuccess = pOutput->outputImages[2]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; ++ pOutput->outputImages[i] = new CVulkanTexture(); ++ if ( !pOutput->outputImages[i]->BInit( uOutputWidth, uOutputHeight, 1u, uDRMFormat, outputImageflags ) ) ++ { ++ vk_log.errorf( "failed to allocate buffer for KMS" ); ++ return false; ++ } + } + + // Oh no. +@@ -3696,28 +3679,14 @@ static bool vulkan_make_output_images( VulkanOutput_t *pOutput ) + { + uint32_t uPartialDRMFormat = pOutput->uOutputFormatOverlay; + +- pOutput->outputImagesPartialOverlay[0] = new CVulkanTexture(); +- bool bSuccess = pOutput->outputImagesPartialOverlay[0]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[0].get() ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImagesPartialOverlay[1] = new CVulkanTexture(); +- bSuccess = pOutput->outputImagesPartialOverlay[1]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[1].get() ); +- if ( bSuccess != true ) ++ for ( uint32_t i = 0; i < uImageCount; i++ ) + { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; +- } +- +- pOutput->outputImagesPartialOverlay[2] = new CVulkanTexture(); +- bSuccess = pOutput->outputImagesPartialOverlay[2]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[2].get() ); +- if ( bSuccess != true ) +- { +- vk_log.errorf( "failed to allocate buffer for KMS" ); +- return false; ++ pOutput->outputImagesPartialOverlay[i] = new CVulkanTexture(); ++ if ( !pOutput->outputImagesPartialOverlay[i]->BInit( uOutputWidth, uOutputHeight, 1u, uPartialDRMFormat, outputImageflags, nullptr, 0, 0, pOutput->outputImages[i].get() ) ) ++ { ++ vk_log.errorf( "failed to allocate buffer for KMS" ); ++ return false; ++ } + } + } + +@@ -3755,6 +3724,8 @@ bool vulkan_remake_output_images() + g_device.waitIdle(); + + pOutput->nOutImage = 0; ++ pOutput->nLastOutImage = 0; ++ pOutput->nDeferredOutImage = 0; + + // Delete screenshot/capture textures to be remade if needed + for (auto& pScreenshotTexture : pOutput->pScreenshotTextures) +@@ -4604,6 +4575,30 @@ namespace + + ReshadeEffectPipeline *g_pLastReshadeEffect = nullptr; + ++static bool vulkan_output_image_held( uint32_t nImage ) ++{ ++ for ( const auto &pImage : { g_output.outputImages[ nImage ], g_output.outputImagesPartialOverlay[ nImage ] } ) ++ { ++ if ( pImage != nullptr && pImage->GetBackendFb() != nullptr && pImage->GetBackendFb()->HeldByHost() ) ++ return true; ++ } ++ return false; ++} ++ ++static uint32_t vulkan_free_output_image( uint32_t nFirst ) ++{ ++ const uint32_t uCount = g_output.outputImages.size(); ++ for ( uint32_t i = 0; i < uCount; i++ ) ++ { ++ const uint32_t nImage = ( nFirst + i ) % uCount; ++ if ( uCount > 3 && ( nImage == g_output.nLastOutImage || nImage == g_output.nDeferredOutImage ) ) ++ continue; ++ if ( !vulkan_output_image_held( nImage ) ) ++ return nImage; ++ } ++ return nFirst; ++} ++ + std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamescope::Rc<CVulkanTexture> pPipewireTexture, bool partial, gamescope::Rc<CVulkanTexture> pOutputOverride, bool increment, std::unique_ptr<CVulkanCmdBuffer> pInCommandBuffer ) + { + EOTF outputTF = frameInfo->outputEncodingEOTF; +@@ -4643,6 +4638,9 @@ std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamesco + if ( !pOutputOverride && !vulkan_ensure_output_images() ) + return std::nullopt; + ++ if ( !pOutputOverride && !GetBackend()->UsesVulkanSwapchain() ) ++ g_output.nOutImage = vulkan_free_output_image( g_output.nOutImage ); ++ + gamescope::Rc<CVulkanTexture> compositeImage; + if ( pOutputOverride ) + compositeImage = pOutputOverride; +@@ -4877,7 +4875,9 @@ std::optional<uint64_t> vulkan_composite( struct FrameInfo_t *frameInfo, gamesco + + if ( !GetBackend()->UsesVulkanSwapchain() && pOutputOverride == nullptr && increment ) + { +- g_output.nOutImage = ( g_output.nOutImage + 1 ) % 3; ++ g_output.nDeferredOutImage = g_output.nLastOutImage; ++ g_output.nLastOutImage = g_output.nOutImage; ++ g_output.nOutImage = ( g_output.nOutImage + 1 ) % g_output.outputImages.size(); + } + + return sequence; +@@ -4931,19 +4931,7 @@ bool vulkan_format_supports_features(VkFormat format, VkFormatFeatureFlags featu + + gamescope::Rc<CVulkanTexture> vulkan_get_last_output_image( bool partial, bool defer ) + { +- // Get previous image ( +2 ) +- // 1 2 3 +- // | +- // | +- uint32_t nRegularImage = ( g_output.nOutImage + 2 ) % 3; +- +- // Get previous previous image ( +1 ) +- // 1 2 3 +- // | +- // | +- uint32_t nDeferredImage = ( g_output.nOutImage + 1 ) % 3; +- +- uint32_t nOutImage = defer ? nDeferredImage : nRegularImage; ++ uint32_t nOutImage = defer ? g_output.nDeferredOutImage : g_output.nLastOutImage; + + if ( partial ) + { +diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp +index e0ede11..8ae3b71 100644 +--- a/src/rendervulkan.hpp ++++ b/src/rendervulkan.hpp +@@ -591,6 +591,8 @@ struct VulkanOutput_t + std::vector<gamescope::OwningRc<CVulkanTexture>> presentationImages; + + uint32_t nOutImage; // swapchain index in nested mode, or ping/pong between two RTs ++ uint32_t nLastOutImage = 0; ++ uint32_t nDeferredOutImage = 0; + std::vector<gamescope::OwningRc<CVulkanTexture>> outputImages; + std::vector<gamescope::OwningRc<CVulkanTexture>> outputImagesPartialOverlay; + gamescope::OwningRc<CVulkanTexture> temporaryHackyBlankImage; diff --git a/tools/gamescope/patches/0137-wayland-backend-host-refresh-rates.patch b/tools/gamescope/patches/0137-wayland-backend-host-refresh-rates.patch new file mode 100644 index 0000000000..04860928c4 --- /dev/null +++ b/tools/gamescope/patches/0137-wayland-backend-host-refresh-rates.patch @@ -0,0 +1,293 @@ +diff --git a/protocol/droiddeck-refresh-v1.xml b/protocol/droiddeck-refresh-v1.xml +new file mode 100644 +index 0000000..c4464a0 +--- /dev/null ++++ b/protocol/droiddeck-refresh-v1.xml +@@ -0,0 +1,81 @@ ++<?xml version="1.0" encoding="UTF-8"?> ++<protocol name="droiddeck_refresh_v1"> ++ <copyright> ++ Copyright 2026 DroidDeck contributors ++ ++ 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. ++ </copyright> ++ ++ <interface name="droiddeck_refresh_v1" version="1"> ++ <description summary="panel refresh rates a nested compositor may ask for"> ++ A nested compositor paces its clients against the refresh rate of the ++ panel it is shown on. When its clients are held to a frame rate the ++ panel's current rate does not divide evenly, frames are shown for an ++ uneven number of refreshes. This interface lets the nested compositor ++ see every refresh rate the panel can run at its current size and ask ++ for the one that suits the frame rate it is pacing to. ++ ++ On bind the compositor sends one rate event per refresh rate, lowest ++ first, followed by done. The list is sent again, in full, whenever it ++ changes (a different panel, or a limit the user placed on the panel's ++ rate). The rate the panel is running at is still reported the standard ++ way, through wl_output.mode. ++ ++ A request is a preference, not a guarantee: the user, the platform or ++ another output mirroring the panel may hold the panel at another rate. ++ The client reads the result from wl_output.mode. ++ </description> ++ ++ <request name="destroy" type="destructor"> ++ <description summary="destroy the object"> ++ The preference set through this object is dropped. ++ </description> ++ </request> ++ ++ <request name="set_target"> ++ <description summary="ask for a refresh rate"> ++ refresh is the panel rate the client would like, in Hz, taken from ++ the advertised list; 0 withdraws the preference. frame_rate is the ++ frame rate the client holds its content to, in frames per second, or ++ 0 when the content is not held to a rate. The compositor may multiply ++ the content's frame rate itself (generated frames); when it does, it ++ picks the advertised rate that the multiplied frame rate divides ++ evenly instead of the requested one. ++ </description> ++ <arg name="refresh" type="uint" summary="wanted panel refresh rate in Hz, 0 for none"/> ++ <arg name="frame_rate" type="uint" summary="content frame rate in frames per second, 0 for unpaced"/> ++ </request> ++ ++ <event name="rate"> ++ <description summary="a refresh rate the panel can run"> ++ Sent once per rate, lowest first, in Hz rounded to the nearest whole ++ number. ++ </description> ++ <arg name="refresh" type="uint" summary="panel refresh rate in Hz"/> ++ </event> ++ ++ <event name="done"> ++ <description summary="the list of rates is complete"> ++ Ends a list of rate events. The rates received since the previous ++ done replace the earlier list. ++ </description> ++ </event> ++ </interface> ++</protocol> +diff --git a/protocol/meson.build b/protocol/meson.build +index cf8fbd1..71fe31b 100644 +--- a/protocol/meson.build ++++ b/protocol/meson.build +@@ -43,6 +43,8 @@ protocols = [ + 'gamescope-private.xml', + 'gamescope-action-binding.xml', + ++ 'droiddeck-refresh-v1.xml', ++ + # wlroots protocols + 'wlr-layer-shell-unstable-v1.xml', + ] +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index be99e6d..9862641 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -38,6 +38,7 @@ + #include <primary-selection-unstable-v1-client-protocol.h> + #include <fractional-scale-v1-client-protocol.h> + #include <xdg-toplevel-icon-v1-client-protocol.h> ++#include <droiddeck-refresh-v1-client-protocol.h> + #include "wlr_end.hpp" + + #include "drm_include.h" +@@ -705,6 +706,10 @@ namespace gamescope + virtual bool UsesVulkanSwapchain() const override; + + virtual bool IsSessionBased() const override; ++ virtual bool HackTemporarySetDynamicRefresh( int nRefresh ) override; ++ ++ std::span<const uint32_t> GetHostRefreshRates() const; ++ void SyncHostRefreshTarget(); + virtual bool SupportsExplicitSync() const override; + + virtual bool IsPaused() const override; +@@ -778,6 +783,10 @@ namespace gamescope + void Wayland_Output_Geometry( wl_output *pOutput, int32_t nX, int32_t nY, int32_t nPhysicalWidth, int32_t nPhysicalHeight, int32_t nSubpixel, const char *pMake, const char *pModel, int32_t nTransform ); + void Wayland_Output_Mode( wl_output *pOutput, uint32_t uFlags, int32_t nWidth, int32_t nHeight, int32_t nRefresh ); + void Wayland_Output_Done( wl_output *pOutput ); ++ ++ void Wayland_Refresh_Rate( droiddeck_refresh_v1 *pRefresh, uint32_t uRefresh ); ++ void Wayland_Refresh_Done( droiddeck_refresh_v1 *pRefresh ); ++ static const droiddeck_refresh_v1_listener s_RefreshListener; + void Wayland_Output_Scale( wl_output *pOutput, int32_t nFactor ); + void Wayland_Output_Name( wl_output *pOutput, const char *pName ); + void Wayland_Output_Description( wl_output *pOutput, const char *pDescription ); +@@ -829,6 +838,12 @@ namespace gamescope + OwningRc<CWaylandFb> m_pOwnedBlackFb; + OwningRc<CVulkanTexture> m_pBlackTexture; + wp_presentation *m_pPresentation = nullptr; ++ droiddeck_refresh_v1 *m_pHostRefresh = nullptr; ++ std::array<uint32_t, 16> m_HostRefreshRates{}; ++ std::atomic<uint32_t> m_uHostRefreshRateCount = { 0 }; ++ std::vector<uint32_t> m_PendingHostRefreshRates; ++ int m_nSentHostRefresh = 0; ++ int m_nSentHostFrameRate = 0; + frog_color_management_factory_v1 *m_pFrogColorMgmtFactory = nullptr; + wp_color_manager_v1 *m_pWPColorManager = nullptr; + wp_image_description_v1 *m_pWPImageDescriptions[ GamescopeAppTextureColorspace_Count ]{}; +@@ -890,6 +905,11 @@ namespace gamescope + .global = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Registry_Global ), + .global_remove = WAYLAND_NULL(), + }; ++ const droiddeck_refresh_v1_listener CWaylandBackend::s_RefreshListener = ++ { ++ .rate = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Refresh_Rate ), ++ .done = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Refresh_Done ), ++ }; + const wl_output_listener CWaylandBackend::s_OutputListener = + { + .geometry = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_Output_Geometry ), +@@ -1087,6 +1107,7 @@ namespace gamescope + { + droiddeck::frame_trace::Record( droiddeck::frame_trace::Event::OutputPresent ); + UpdateFullscreenState(); ++ m_pBackend->SyncHostRefreshTarget(); + + bool bNeedsFullComposite = false; + +@@ -1244,7 +1265,7 @@ namespace gamescope + } + std::span<const uint32_t> CWaylandConnector::GetValidDynamicRefreshRates() const + { +- return std::span<const uint32_t>{}; ++ return m_pBackend->GetHostRefreshRates(); + } + + void CWaylandConnector::GetNativeColorimetry( +@@ -2396,6 +2417,52 @@ namespace gamescope + return false; + } + ++ std::span<const uint32_t> CWaylandBackend::GetHostRefreshRates() const ++ { ++ const uint32_t uCount = m_uHostRefreshRateCount; ++ if ( uCount < 2 ) ++ return std::span<const uint32_t>{}; ++ return std::span<const uint32_t>{ m_HostRefreshRates.data(), uCount }; ++ } ++ ++ bool CWaylandBackend::HackTemporarySetDynamicRefresh( int nRefresh ) ++ { ++ if ( !m_pHostRefresh ) ++ return false; ++ SyncHostRefreshTarget(); ++ return true; ++ } ++ ++ void CWaylandBackend::SyncHostRefreshTarget() ++ { ++ if ( !m_pHostRefresh ) ++ return; ++ const int nFrameRate = steamcompmgr_get_app_target_fps(); ++ const int nRefresh = steamcompmgr_get_app_dynamic_refresh(); ++ if ( nRefresh == m_nSentHostRefresh && nFrameRate == m_nSentHostFrameRate ) ++ return; ++ xdg_log.infof( "Asking the host for %dhz at %dfps", nRefresh, nFrameRate ); ++ droiddeck_refresh_v1_set_target( m_pHostRefresh, nRefresh, nFrameRate ); ++ m_nSentHostRefresh = nRefresh; ++ m_nSentHostFrameRate = nFrameRate; ++ } ++ ++ void CWaylandBackend::Wayland_Refresh_Rate( droiddeck_refresh_v1 *pRefresh, uint32_t uRefresh ) ++ { ++ m_PendingHostRefreshRates.push_back( uRefresh ); ++ } ++ void CWaylandBackend::Wayland_Refresh_Done( droiddeck_refresh_v1 *pRefresh ) ++ { ++ std::sort( m_PendingHostRefreshRates.begin(), m_PendingHostRefreshRates.end() ); ++ const uint32_t uCount = std::min<size_t>( m_PendingHostRefreshRates.size(), m_HostRefreshRates.size() ); ++ m_uHostRefreshRateCount = 0; ++ std::copy_n( m_PendingHostRefreshRates.begin(), uCount, m_HostRefreshRates.begin() ); ++ m_uHostRefreshRateCount = uCount; ++ m_PendingHostRefreshRates.clear(); ++ steamcompmgr_display_rates_changed(); ++ force_repaint(); ++ } ++ + bool CWaylandBackend::SupportsExplicitSync() const + { + // GAMESCOPE_DISABLE_EXPLICIT_SYNC=1: a kernel without DRM_IOCTL_SYNCOBJ_EVENTFD (before +@@ -2647,6 +2714,11 @@ namespace gamescope + wl_output_add_listener( pOutput , &s_OutputListener, this ); + m_pOutputs.emplace( std::make_pair<struct wl_output *, WaylandOutputInfo>( std::move( pOutput ), WaylandOutputInfo{} ) ); + } ++ else if ( !strcmp( pInterface, droiddeck_refresh_v1_interface.name ) ) ++ { ++ m_pHostRefresh = (droiddeck_refresh_v1 *)wl_registry_bind( pRegistry, uName, &droiddeck_refresh_v1_interface, 1u ); ++ droiddeck_refresh_v1_add_listener( m_pHostRefresh, &s_RefreshListener, this ); ++ } + else if ( !strcmp( pInterface, frog_color_management_factory_v1_interface.name ) ) + { + m_pFrogColorMgmtFactory = (frog_color_management_factory_v1 *)wl_registry_bind( pRegistry, uName, &frog_color_management_factory_v1_interface, 1u ); +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index 38b304b..d7d11b3 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -1229,6 +1229,25 @@ static int g_nCombinedAppRefreshCycleOverride[gamescope::GAMESCOPE_SCREEN_TYPE_C + bool g_nCombinedAppRefreshCycleChangeRefresh[gamescope::GAMESCOPE_SCREEN_TYPE_COUNT] = { true, true }; + bool g_nCombinedAppRefreshCycleChangeFPS[gamescope::GAMESCOPE_SCREEN_TYPE_COUNT] = { true, true }; + ++int steamcompmgr_get_app_target_fps() ++{ ++ return g_nSteamCompMgrTargetFPS; ++} ++ ++int steamcompmgr_get_app_dynamic_refresh() ++{ ++ if ( !GetBackend()->GetCurrentConnector() ) ++ return 0; ++ return g_nDynamicRefreshRate[ GetBackend()->GetCurrentConnector()->GetScreenType() ]; ++} ++ ++static std::atomic<bool> g_bDisplayRatesChanged = { false }; ++ ++void steamcompmgr_display_rates_changed() ++{ ++ g_bDisplayRatesChanged = true; ++} ++ + static void _update_app_target_refresh_cycle() + { + if ( !GetBackend()->GetCurrentConnector() ) +@@ -9703,7 +9722,8 @@ void update_vrr_atoms(xwayland_ctx_t *root_ctx, bool force, bool* needs_flush = + *needs_flush = true; + } + +- if ( g_nOutputRefresh != g_nCurrentRefreshRate_CachedValue || force ) ++ const bool bDisplayRatesChanged = g_bDisplayRatesChanged.exchange( false ); ++ if ( g_nOutputRefresh != g_nCurrentRefreshRate_CachedValue || bDisplayRatesChanged || force ) + { + int32_t nRefresh = gamescope::ConvertmHzToHz( g_nOutputRefresh ); + XChangeProperty(root_ctx->dpy, root_ctx->root, root_ctx->atoms.gamescopeDisplayRefreshRateFeedback, XA_CARDINAL, 32, PropModeReplace, +diff --git a/src/steamcompmgr.hpp b/src/steamcompmgr.hpp +index ff54d8e..9e0bb79 100644 +--- a/src/steamcompmgr.hpp ++++ b/src/steamcompmgr.hpp +@@ -202,4 +202,7 @@ MouseCursor *steamcompmgr_get_server_cursor(uint32_t serverId); + + extern gamescope::ConVar<bool> cv_tearing_enabled; + ++extern int steamcompmgr_get_app_target_fps(); ++extern int steamcompmgr_get_app_dynamic_refresh(); ++extern void steamcompmgr_display_rates_changed(); + extern void steamcompmgr_set_app_refresh_cycle_override( gamescope::GamescopeScreenType type, int override_fps, bool change_refresh, bool change_fps_cap ); diff --git a/tools/gamescope/patches/0138-limiter-even-cadence.patch b/tools/gamescope/patches/0138-limiter-even-cadence.patch new file mode 100644 index 0000000000..429aa78933 --- /dev/null +++ b/tools/gamescope/patches/0138-limiter-even-cadence.patch @@ -0,0 +1,67 @@ +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index d7d11b3..cfec551 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -7188,6 +7188,19 @@ init_runtime_info() + update_runtime_info(); + } + ++static uint64_t limiter_latch_target( uint64_t ulPreviousTarget, uint64_t ulLatched, uint64_t ulLimitedCycle, uint64_t ulRefreshCycle ) ++{ ++ const uint64_t ulTarget = ulPreviousTarget + ulLimitedCycle; ++ const bool bLate = ulTarget + ulRefreshCycle * 3 / 4 < ulLatched; ++ const bool bEarly = ulTarget > ulLatched + ulRefreshCycle; ++ return ( bLate || bEarly ) ? ulLatched : ulTarget; ++} ++ ++static bool limiter_holds_vblank( uint64_t ulTarget, uint64_t ulNow, uint64_t ulLimitedCycle, uint64_t ulRefreshCycle ) ++{ ++ return ulNow + ulRefreshCycle / 2 < ulTarget + ulLimitedCycle; ++} ++ + static void + steamcompmgr_flush_frame_done( steamcompmgr_win_t *w ) + { +@@ -7206,6 +7219,9 @@ steamcompmgr_flush_frame_done( steamcompmgr_win_t *w ) + + w->last_commit_first_latch_time = timespec_to_nanos(now); + ++ w->limiter_latch_target_time = limiter_latch_target( w->limiter_latch_target_time, w->last_commit_first_latch_time, ++ g_SteamCompMgrLimitedAppRefreshCycle, g_SteamCompMgrAppRefreshCycle ); ++ + // Acknowledge commit once. + wlserver_lock(); + +@@ -7258,8 +7274,7 @@ static bool steamcompmgr_should_vblank_window( bool bShouldLimitFPS, uint64_t vb + { + if ( w && now ) + { +- uint64_t schedule = w->last_commit_first_latch_time + g_SteamCompMgrLimitedAppRefreshCycle; +- if ( now + g_SteamCompMgrAppRefreshCycle / 2 < schedule ) ++ if ( limiter_holds_vblank( w->limiter_latch_target_time, now, g_SteamCompMgrLimitedAppRefreshCycle, g_SteamCompMgrAppRefreshCycle ) ) + bSendCallback = false; + } + else +@@ -11047,9 +11062,7 @@ steamcompmgr_main(int argc, char **argv) + } + else + { +- int nVblankDivisor = nRealRefreshHz / nTargetFPS; +- +- g_SteamCompMgrLimitedAppRefreshCycle = g_SteamCompMgrAppRefreshCycle * nVblankDivisor; ++ g_SteamCompMgrLimitedAppRefreshCycle = g_SteamCompMgrAppRefreshCycle * nRealRefreshHz / nTargetFPS; + } + } + } +diff --git a/src/steamcompmgr_shared.hpp b/src/steamcompmgr_shared.hpp +index 0fcc80b..3c74d62 100644 +--- a/src/steamcompmgr_shared.hpp ++++ b/src/steamcompmgr_shared.hpp +@@ -146,6 +146,7 @@ struct steamcompmgr_win_t { + bool outdatedInteractiveFocus = false; + + uint64_t last_commit_first_latch_time = 0; ++ uint64_t limiter_latch_target_time = 0; + uint64_t last_commit_present_time = 0; + + bool hasHwndStyle = false; diff --git a/tools/gamescope/patches/0139-hdr-switch-live.patch b/tools/gamescope/patches/0139-hdr-switch-live.patch new file mode 100644 index 0000000000..3c1b839620 --- /dev/null +++ b/tools/gamescope/patches/0139-hdr-switch-live.patch @@ -0,0 +1,54 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 9862641..e9d2923 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -1972,7 +1972,7 @@ namespace gamescope + { + auto *pHDRInfo = &m_pConnector->m_HDRInfo; + if (m_pBackend->SupportsColorManagement()) { +- pHDRInfo->bExposeHDRSupport = ( cv_hdr_enabled && m_pConnector->m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance ); ++ pHDRInfo->bExposeHDRSupport = ( m_pConnector->m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance ); + pHDRInfo->eOutputEncodingEOTF = pHDRInfo->bExposeHDRSupport ? EOTF_PQ : EOTF_Gamma22; + } + +@@ -2282,7 +2282,7 @@ namespace gamescope + + assert( u8BitFormat != DRM_FORMAT_INVALID ); + +- *pPrimaryPlaneFormat = u10BitFormat != DRM_FORMAT_INVALID ? u10BitFormat : u8BitFormat; ++ *pPrimaryPlaneFormat = ( cv_hdr_enabled && u10BitFormat != DRM_FORMAT_INVALID ) ? u10BitFormat : u8BitFormat; + *pOverlayPlaneFormat = u8BitFormat; + } + +@@ -2493,13 +2493,17 @@ namespace gamescope + + // XXX: We should do this a better way that handles per-window and appid stuff + // down the line +- if ( cv_hdr_enabled && GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport ) ++ if ( !GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport ) ++ { ++ setenv( "DXVK_HDR", "0", true ); ++ } ++ else if ( cv_hdr_enabled ) + { + setenv( "DXVK_HDR", "1", true ); + } + else + { +- setenv( "DXVK_HDR", "0", true ); ++ unsetenv( "DXVK_HDR" ); + } + + WritePatchedEdid( GetCurrentConnector()->GetRawEDID(), GetCurrentConnector()->GetHDRInfo(), false ); +diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp +index 42cc9c4..d0d21f0 100644 +--- a/src/rendervulkan.cpp ++++ b/src/rendervulkan.cpp +@@ -3735,6 +3735,7 @@ bool vulkan_remake_output_images() + + if ( vulkan_defer_output_images() ) + { ++ GetBackend()->GetPreferredOutputFormat( &pOutput->uOutputFormat, &pOutput->uOutputFormatOverlay ); + pOutput->outputImages.clear(); + pOutput->outputImagesPartialOverlay.clear(); + pOutput->temporaryHackyBlankImage = vulkan_create_debug_blank_texture(); diff --git a/tools/gamescope/patches/0140-focus-follows-window-opacity.patch b/tools/gamescope/patches/0140-focus-follows-window-opacity.patch new file mode 100644 index 0000000000..e4bd4f99b9 --- /dev/null +++ b/tools/gamescope/patches/0140-focus-follows-window-opacity.patch @@ -0,0 +1,32 @@ +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index cfec551..e98d320 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -6945,6 +6945,12 @@ handle_system_tray_opcode(xwayland_ctx_t *ctx, XClientMessageEvent *ev) + } + } + ++static bool ++opacity_changes_focus_candidacy( unsigned int oldOpacity, unsigned int newOpacity ) ++{ ++ return ( oldOpacity > TRANSLUCENT ) != ( newOpacity > TRANSLUCENT ); ++} ++ + /* See http://tronche.com/gui/x/icccm/sec-4.html#s-4.1.4 */ + static void + handle_wm_change_state(xwayland_ctx_t *ctx, steamcompmgr_win_t *w, XClientMessageEvent *ev) +@@ -7329,8 +7335,14 @@ handle_property_notify(xwayland_ctx_t *ctx, XPropertyEvent *ev) + + if (newOpacity != w->opacity) + { ++ const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity ); + w->opacity = newOpacity; + ++ if ( bFocusCandidacyChanged ) ++ { ++ MakeFocusDirty(); ++ } ++ + if ( gameFocused && ( w == ctx->focus.overlayWindow || w == ctx->focus.notificationWindow ) ) + { + hasRepaintNonBasePlane = true; diff --git a/tools/gamescope/patches/0141-nested-mouse-moves-when-touch-is-disabled.patch b/tools/gamescope/patches/0141-nested-mouse-moves-when-touch-is-disabled.patch new file mode 100644 index 0000000000..c165ccc50b --- /dev/null +++ b/tools/gamescope/patches/0141-nested-mouse-moves-when-touch-is-disabled.patch @@ -0,0 +1,16 @@ +diff --git a/src/wlserver.cpp b/src/wlserver.cpp +index df352b0..9740875 100644 +--- a/src/wlserver.cpp ++++ b/src/wlserver.cpp +@@ -3326,7 +3326,10 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool + } + else if ( eMode == gamescope::TouchClickModes::Disabled ) + { +- return; ++ if ( !bAlwaysWarpCursor ) ++ return; ++ ++ wlserver_mousewarp( tx, ty, time, false ); + } + else if ( eMode == gamescope::TouchClickModes::Trackpad ) + { diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index bf5211b032..52d5d20e44 100644 --- a/tools/gamescope/release.env +++ b/tools/gamescope/release.env @@ -1,3 +1,3 @@ GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components -GAMESCOPE_TAG=gamescope-3.16.29-p23 -GAMESCOPE_SHA256=f5f2b8f658234ad2910a1be53c238188db7e7b2a9079f8cc5fa9ea006bebbe7e +GAMESCOPE_TAG=gamescope-3.16.29-1a29c65d +GAMESCOPE_SHA256=18620dfedb65860da00003e965cc09784a650ef6ecc9a17056405fe0a1392a02 diff --git a/tools/linuxfs/build-x86-preloads.sh b/tools/linuxfs/build-x86-preloads.sh index a9c32a18d6..ccb00eeab4 100755 --- a/tools/linuxfs/build-x86-preloads.sh +++ b/tools/linuxfs/build-x86-preloads.sh @@ -1,26 +1,34 @@ #!/bin/sh set -eu out=${1:?usage: build-x86-preloads.sh <linuxfs asset directory>} +tools() { + prefix= + if [ "${X86_CROSS:-}" = 1 ]; then + case $1 in i386) prefix=i686-linux-gnu- ;; *) prefix=x86_64-linux-gnu- ;; esac + fi + GCC=${prefix}gcc GXX=${prefix}g++ STRIP=${prefix}strip OBJDUMP=${prefix}objdump NM=${prefix}nm +} for arch in x86_64 i386; do + tools $arch case $arch in x86_64) bits=-m64 ;; i386) bits=-m32 ;; esac mkdir -p "$out/$arch" - gcc $bits -shared -fPIC -O2 -Wall -pthread \ + $GCC $bits -shared -fPIC -O2 -Wall -pthread \ -o "$out/$arch/libddsession.so" tools/linuxfs/preload/*.c -ldl - g++ $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \ + $GXX $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \ -pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \ -o "$out/$arch/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl - strip --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so" + $STRIP --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so" for lib in "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"; do - newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1) + newest=$($OBJDUMP -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1) minor=${newest#GLIBC_2.} if [ "$minor" -gt 31 ]; then echo "$lib needs $newest; Steam Linux Runtime 3.0 has glibc 2.31" >&2 exit 1 fi - if objdump -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then + if $OBJDUMP -p "$lib" | grep -q 'NEEDED.*lib\(stdc++\|gcc_s\)'; then echo "$lib links the C++ runtime dynamically" >&2 exit 1 fi @@ -28,37 +36,39 @@ for arch in x86_64 i386; do done for target in x86_64/faultreport i386/faultreport; do arch=${target%/*} name=${target#*/} + tools $arch case $arch in x86_64) bits=-m64 ;; i386) bits=-m32 ;; esac lib=$out/$arch/lib$name.so - gcc $bits -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \ + $GCC $bits -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \ -o "$lib" tools/linuxfs/fex/$name.c - strip --strip-unneeded "$lib" - if objdump -p "$lib" | grep -q NEEDED || [ -n "$(nm -D --undefined-only "$lib" 2>/dev/null)" ]; then + $STRIP --strip-unneeded "$lib" + if $OBJDUMP -p "$lib" | grep -q NEEDED || [ -n "$($NM -D --undefined-only "$lib" 2>/dev/null)" ]; then echo "$lib must not need any library" >&2 exit 1 fi done +tools x86_64 lib=$out/x86_64/libwebkitinput.so -gcc -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \ +$GCC -m64 -shared -fPIC -O2 -Wall -Wextra -nostdlib -fno-stack-protector -fno-builtin -fvisibility=hidden \ -o "$lib" tools/linuxfs/fex/webkitinput.c -strip --strip-unneeded "$lib" -if objdump -p "$lib" | grep -q NEEDED || [ "$(nm -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then +$STRIP --strip-unneeded "$lib" +if $OBJDUMP -p "$lib" | grep -q NEEDED || [ "$($NM -D --undefined-only "$lib" | awk '{print $1 $2}' | LC_ALL=C sort | tr '\n' ' ')" != "wdlsym wg_getenv wg_object_get_data wg_object_set wg_object_set_data wg_type_check_instance_is_a wgtk_container_forall wgtk_container_get_type wgtk_key_snooper_install wgtk_widget_get_toplevel wwebkit_user_script_new wwebkit_user_script_unref wwebkit_web_view_get_type wwebkit_web_view_get_uri wwebkit_web_view_run_javascript " ]; then echo "$lib must need nothing but weak GLib, GTK and WebKit calls" >&2 exit 1 fi stub=$(mktemp -d) -gcc -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null +$GCC -m64 -shared -nostdlib -Wl,-soname,/usr/lib/x86_64-linux-gnu/libvulkan.so.1 -o "$stub/libvulkan.so.1" -x c /dev/null lib=$out/x86_64/libvulkan-thunk.so -gcc -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \ +$GCC -m64 -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden -Wl,-soname,libvulkan.so.1 -Wl,-z,nodelete -Wl,--no-as-needed \ -o "$lib" tools/linuxfs/fex/vulkanpin.c "$stub/libvulkan.so.1" -ldl rm -rf "$stub" -strip --strip-unneeded "$lib" -newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1) -if ! objdump -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \ - || ! objdump -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then +$STRIP --strip-unneeded "$lib" +newest=$($OBJDUMP -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1) +if ! $OBJDUMP -p "$lib" | grep -q 'NEEDED *\/usr/lib/x86_64-linux-gnu/libvulkan\.so\.1$' \ + || ! $OBJDUMP -p "$lib" | grep -q 'FLAGS_1 *0x0*8$' || [ "${newest#GLIBC_2.}" -gt 31 ]; then echo "$lib must be nodelete, need the Vulkan thunk and run on glibc 2.31" >&2 exit 1 fi diff --git a/tools/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index d063bab657..6a1cdc4d08 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -24,7 +24,7 @@ if [ -n "${DD_DEBUG_DIR:-}" ]; then exec >>"$DD_DEBUG_DIR/desktop.log" 2>&1 echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${DD_WIDTH:-1280}x${DD_HEIGHT:-720}" fi -find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' -exec rm -rf {} + 2>/dev/null +find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' ! -name 'droiddeck-display-buffers' -exec rm -rf {} + 2>/dev/null chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null mkdir -p /tmp/.X11-unix /tmp/.ICE-unix && chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null export DD_DESKTOP=1 @@ -115,6 +115,12 @@ fi if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND export KWIN_COMPOSE=O2 MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true + # On the system PowerVR driver, Firefox's hardware WebRender on zink leaves stale, half-drawn + # frames; its software renderer draws correctly. + [ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0 + # The system driver's (PowerVR, Xclipse) libhybris Wayland swapchain needs the app compositor's Android-buffer + # protocol, which KWin lacks: Plasma's clients present through DRI instead. + [ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export LIBGL_KOPPER_DISABLE=true if [ -z "${KWIN_RENDER_NODES:-}" ]; then for node in /dev/dri/renderD0 /dev/dri/renderD307 /dev/dri/renderD*; do if [ -c "$node" ]; then export KWIN_RENDER_NODES="$node"; break; fi diff --git a/tools/linuxfs/desktop/droiddeck-desktop-gpu b/tools/linuxfs/desktop/droiddeck-desktop-gpu index a0173f7b6d..a25e21e366 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop-gpu +++ b/tools/linuxfs/desktop/droiddeck-desktop-gpu @@ -1,7 +1,6 @@ #!/usr/bin/python3 import os import re -import shutil HOME = os.environ.get("HOME", "/root") SYSTEM_DIR = "/usr/share/applications" @@ -10,8 +9,6 @@ FLATPAK_DIR = os.path.join(HOME, ".local/share/flatpak/exports/share/application USER_DIR = os.path.join(HOME, ".local/share/applications") MARK = "X-DroidDeck-GPU=1" SKIP = re.compile(r"^(steam|droiddeck-game-|droiddeck-steam|steamdeck-)", re.I) -CHROMIUM_ENV = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 " -CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11" def enabled(): @@ -27,33 +24,6 @@ def main_group(text): return lines[:start + 1], lines[start + 1:end], lines[end:] -def split_program(exec_line): - if exec_line.startswith('"'): - end = exec_line.find('"', 1) - if end < 0: - return None, None - return exec_line[:end + 1], exec_line[end + 1:] - program, _, rest = exec_line.partition(" ") - return program, (" " + rest) if rest else "" - - -def chromium(exec_line): - program, _ = split_program(exec_line) - if not program: - return False - program = program.strip('"') - path = program if os.path.isabs(program) else shutil.which(program) - if not path: - return False - here = os.path.dirname(os.path.realpath(path)) - return any(os.path.exists(os.path.join(d, "chrome-sandbox")) for d in (here, os.path.dirname(here))) - - -def chromium_exec(exec_line): - program, rest = split_program(exec_line) - return CHROMIUM_ENV + program + CHROMIUM_FLAGS + rest - - def gpu_exec(exec_line): if exec_line.startswith("/usr/bin/flatpak run ") or exec_line.startswith("flatpak run "): exec_line = "/usr/local/bin/droiddeck-flatpak-run " + exec_line.split(" run ", 1)[1] @@ -75,24 +45,8 @@ def wrap(text, gpu_on=True): if not exec_line or exec_line.startswith("droiddeck-gpu "): return None cats = set(filter(None, keys.get("Categories", "").split(";"))) - gpu = gpu_on and bool(cats & {"Game", "Emulator"}) - browser = chromium(exec_line) - if not gpu and not browser: + if not (gpu_on and cats & {"Game", "Emulator"}): return None - if browser: - exec_line = chromium_exec(exec_line) - if not gpu: - def fix(lines): - return ["Exec=" + chromium_exec(l[5:].strip()) if l.startswith("Exec=") and chromium(l[5:].strip()) else l - for l in lines] - out_group = fix(group) - while out_group and not out_group[-1].strip(): - out_group.pop() - out_group.append(MARK) - out_rest = fix(rest) - if out_rest and out_rest[0].strip(): - out_rest.insert(0, "") - return "\n".join(head + out_group + out_rest) + "\n" out_group = [] actions = keys.get("Actions", "") for l in group: @@ -111,8 +65,7 @@ def wrap(text, gpu_on=True): wrapped_rest = [] for l in rest: if l.startswith("Exec=") and not l[5:].startswith("droiddeck-gpu "): - action = l[5:].strip() - l = "Exec=" + gpu_exec(chromium_exec(action) if chromium(action) else action) + l = "Exec=" + gpu_exec(l[5:].strip()) wrapped_rest.append(l) if wrapped_rest and wrapped_rest[0].strip(): wrapped_rest.insert(0, "") diff --git a/tools/linuxfs/licenses/dwarfs-LICENSE b/tools/linuxfs/licenses/dwarfs-LICENSE new file mode 100644 index 0000000000..747b40c737 --- /dev/null +++ b/tools/linuxfs/licenses/dwarfs-LICENSE @@ -0,0 +1,49 @@ +Parts of the DwarFS project are licensed under the MIT license, while others are +licensed under the GPL-3.0 license. In general, the code used to *read* DwarFS +images is licensed under the MIT license, while the code used to *write* DwarFS +images is licensed under the GPL-3.0 license. Also, all testing/benchmarking +code is currently licensed under the GPL-3.0 license. + +That means you can use `mkdwarfs` to create images and then use these images +with only the MIT-licensed code. + +The following libraries and associated header files are licensed under the +MIT license: + +- `dwarfs_common` +- `dwarfs_compressor` +- `dwarfs_decompressor` +- `dwarfs_extractor` +- `dwarfs_reader` + +The following libraries and associated header files are licensed under the +GPL-3.0 license: + +- `dwarfs_rewrite` +- `dwarfs_writer` + +Each header and source file should contain an SPDX identifier near the top +of the file. + +Please also check the licenses of the projects that DwarFS depends on. + +---- + +MIT License + +Copyright (c) Marcus Holland-Moritz + +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 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. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index 114e608e33..df0f4cedf1 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -432,7 +432,7 @@ class FocusWatcher(threading.Thread): class WebSocket: - def __init__(self, url, timeout): + def __init__(self, url, timeout, bounded=False): target = urllib.parse.urlsplit(url) if (target.scheme != "ws" or target.hostname not in ("127.0.0.1", "::1", "localhost") or target.username is not None or target.password is not None or target.fragment): @@ -442,6 +442,7 @@ class WebSocket: if target.query: path += "?" + target.query host = "127.0.0.1" if target.hostname == "localhost" else target.hostname + self.deadline = time.monotonic() + timeout if bounded else None self.s = socket.create_connection((host, target.port or 80), timeout=timeout) try: self._handshake(path, hostport) @@ -457,6 +458,7 @@ class WebSocket: ).encode()) head = b"" while b"\r\n\r\n" not in head: + self._wait() chunk = self.s.recv(4096) if not chunk: raise OSError("DevTools closed the connection during the handshake") @@ -468,8 +470,17 @@ class WebSocket: raise OSError("DevTools refused the WebSocket: " + status.decode(errors="replace")) self.buffer = head.split(b"\r\n\r\n", 1)[1] + def _wait(self): + if self.deadline is None: + return + left = self.deadline - time.monotonic() + if left <= 0: + raise socket.timeout("DevTools did not answer in time") + self.s.settimeout(left) + def _read(self, n): while len(self.buffer) < n: + self._wait() chunk = self.s.recv(65536) if not chunk: raise OSError("DevTools closed the connection") @@ -547,22 +558,51 @@ def cdp_targets(agent_dir, timeout=5): raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach the client's DevTools at %s: %s" % (url, e)) -def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15): - targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")] - want = target or "SharedJSContext" - match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")] - if not match: - names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets})) - raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names)) - ws = WebSocket(match[0]["webSocketDebuggerUrl"], timeout) +INSPECTOR_URL = re.compile(r"ws://127\.0\.0\.1:([0-9]{4,5})/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + + +def inspector_url(url): + found = INSPECTOR_URL.fullmatch(url) if isinstance(url, str) else None + if not found or not 1024 <= int(found.group(1)) <= 65535: + raise AgentError("INVALID_REQUEST", "inspector must be a ws://127.0.0.1 inspector URL with its session id") + return url + + +def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None, + command_line_api=False): + if inspector is not None: + url, name = inspector_url(inspector), "inspector" + else: + targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")] + want = target or "SharedJSContext" + match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")] + if not match: + names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets})) + raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names)) + url, name = match[0]["webSocketDebuggerUrl"], match[0].get("title") try: - ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": { - "expression": expression, "returnByValue": True, "awaitPromise": await_promise, - "userGesture": True, - }})) - deadline = time.monotonic() + timeout - while time.monotonic() < deadline: - message = json.loads(ws.recv()) + ws = WebSocket(url, timeout, bounded=True) + except socket.timeout: + raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout) + except OSError as e: + raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach DevTools: %s" % e) + try: + try: + ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": { + "expression": expression, "returnByValue": True, "awaitPromise": await_promise, + "userGesture": True, "includeCommandLineAPI": command_line_api, + }})) + except socket.timeout: + raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout) + except OSError as e: + raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e) + while True: + try: + message = json.loads(ws.recv()) + except socket.timeout: + raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout) + except OSError as e: + raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e) if message.get("id") != 1: continue if "error" in message: @@ -573,9 +613,8 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15) text = (details.get("exception") or {}).get("description") or details.get("text") or "exception" raise AgentError("JS_EXCEPTION", text) value = result.get("result", {}) - return {"target": match[0].get("title"), "type": value.get("type"), + return {"target": name, "type": value.get("type"), "value": value.get("value"), "description": value.get("description")} - raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout) finally: ws.close() @@ -1157,7 +1196,7 @@ def handle(agent_dir, req): if not isinstance(expression, str) or not expression: raise AgentError("INVALID_REQUEST", "cdp eval needs an expression") return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)), - request_timeout(req, 15)) + request_timeout(req, 15), req.get("inspector"), req.get("commandLineApi") is True) if kind == "steam-selection": return steam_selection(agent_dir, request_timeout(req, 5)) if kind == "quit": @@ -1167,6 +1206,15 @@ def handle(agent_dir, req): raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind) +def reply(agent_dir, req): + try: + return dict(handle(agent_dir, req), ok=True) + except AgentError as e: + return {"ok": False, "error": {"code": e.code, "message": str(e)}} + except Exception as e: + return {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}} + + def answer(agent_dir, path): rid = path.stem try: @@ -1186,12 +1234,7 @@ def answer(agent_dir, path): except OSError: pass if req is not None: - try: - result = dict(handle(agent_dir, req), ok=True) - except AgentError as e: - result = {"ok": False, "error": {"code": e.code, "message": str(e)}} - except Exception as e: - result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}} + result = reply(agent_dir, req) write_json(agent_dir / "resp" / (rid + ".json"), result) @@ -1218,6 +1261,13 @@ def serve(agent_dir, focus=True, poll=0.1): def main(argv): + if argv and argv[0] == "--cdp-inspector": + if len(argv) != 4: + print("usage: droiddeck-agent --cdp-inspector <inspector url> <seconds> <expression>", file=sys.stderr) + return 2 + print(json.dumps(reply(Path("/"), {"kind": "cdp", "inspector": argv[1], "timeout": argv[2], + "expression": argv[3], "commandLineApi": True}))) + return 0 base = os.environ.get("DD_LAUNCH_DIR") if not base: print("DD_LAUNCH_DIR is not set", file=sys.stderr) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-exec b/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-exec index 454333efa9..5bcbacbdd8 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-exec +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-exec @@ -9,6 +9,40 @@ if [ -x /usr/local/bin/droiddeck-fex ]; then 3|62) exec /usr/local/bin/droiddeck-fex run --mode on -- "$image" "$@" ;; esac fi +if [ -n "${DDNATV_ROOT:-}" ]; then + image=$(realpath -- "$image") || exit 127 + cache=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/droiddeck-appimage + mkdir -p "$cache" || exit 1 + exec 9>"$cache/.lock" + flock 9 || exit 1 + state() { printf '%s\n%s' "$1" "$(TZ=UTC0 stat -Lc '%s %y' -- "$1" 2>/dev/null)"; } + for dir in "$cache"/*/; do + dir=${dir%/} + [ ! -L "$dir" ] && [ -f "$dir/source" ] || continue + [ "$(cat "$dir/source")" = "$(state "$(head -n 1 "$dir/source")")" ] && continue + (flock -n 7 && rm -rf -- "${dir:?}") 7<"$dir/source" + done + find "$cache" -mindepth 1 -maxdepth 1 -name '.unpack.*' -mmin +60 -exec rm -rf -- {} + 2>/dev/null + source=$(state "$image") + unpacked=$cache/$(printf '%s' "$source" | md5sum | cut -c1-16) + if [ "$(cat "$unpacked/source" 2>/dev/null)" != "$source" ] || [ ! -e "$unpacked/squashfs-root/AppRun" ]; then + echo "== appimage: unpacking $image" + work=$(mktemp -d "$cache/.unpack.XXXXXX") || exit 1 + if ! (cd "$work" && /usr/local/bin/droiddeck-fex extract "$image") || [ ! -e "$work/squashfs-root/AppRun" ]; then + rm -rf -- "${work:?}" + echo "droiddeck-appimage-exec: could not unpack $image" >&2 + exit 1 + fi + printf '%s\n' "$source" > "$work/source" + rm -rf -- "${unpacked:?}" + mv -- "$work" "$unpacked" || exit 1 + fi + exec 8<"$unpacked/source" + flock -s 8 || exit 1 + exec 9>&- + export APPIMAGE=$image APPDIR=$unpacked/squashfs-root ARGV0=$image OWD=$PWD + exec "$APPDIR/AppRun" "$@" +fi if [ -x /usr/local/lib/droiddeck/uruntime ]; then export TARGET_APPIMAGE=$image exec /usr/local/lib/droiddeck/uruntime "$@" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run b/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run index b4a1910f24..d0d33c595e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-appimage-run @@ -45,11 +45,20 @@ if [ "$qt" = wayland ] && [ -n "$wayland" ]; then elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then export QT_QPA_PLATFORM=xcb fi +arch=$(cat "$dir/arch" 2>/dev/null) +if [ "$arch" = arm64 ]; then + find -H "$APPDIR" -maxdepth 6 ! -type d \( -name libGL.so.1 -o -name libGLX.so.0 -o -name libEGL.so.1 -o -name libGLESv2.so.2 \ + -o -name libOpenGL.so.0 -o -name libGLdispatch.so.0 \) -print 2>/dev/null | + while IFS= read -r lib; do + kept=$dir/bundled-gl/${lib#"$APPDIR"/} + mkdir -p "${kept%/*}" && mv -f "$lib" "$kept" && echo "== appimage: the session's ${lib##*/} replaces the bundled one" + done +fi fex=$(cat "$dir/fex" 2>/dev/null) case $fex in on|off) ;; *) fex=auto ;; esac run=("$APPDIR/AppRun") if [ -x /usr/local/bin/droiddeck-fex ]; then - case $fex:$(cat "$dir/arch" 2>/dev/null) in + case $fex:$arch in auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;; auto:arm64) ;; *) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;; diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index 066f9c572e..d24ead6eb5 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -37,9 +37,6 @@ USER_PREFERENCES = "UserPreferencesMask" WINE_USER_PREFERENCES = bytes((0x10, 0x00, 0x00, 0x80, 0x12, 0x00, 0x00, 0x00)) CLIENT_AREA_ANIMATION = (4, 0x02) WALLPAPER_MAX = (1280, 720) -FEX_REQUEST = "battlenet-fex.request" -FEX_RESULT = "battlenet-fex.result" -FEX_WAIT = 120 START_GRACE = 90 POLL = 2 STOP_WAIT = 5 @@ -82,8 +79,7 @@ AGENT_START = 90 AGENT_HELPER = "agent.js" AGENT_RUNTIME = "agent-runtime" AGENT_LOG = "agent.log" -AGENT_LOG_LIMIT = 4 << 20 -HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"] +HEADLESS = "/usr/local/bin/droiddeck-headless" PRODUCT = re.compile(r"[a-z0-9_]{1,32}") LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}") COUNTRY = re.compile(r"[A-Z]{3}") @@ -779,32 +775,6 @@ def write_menu(path=MENU): say("menu entry not written: %s" % error) -def ask_fex(launch_dir, wait=FEX_WAIT): - if not launch_dir or not os.path.isdir(launch_dir): - say("not inside a DroidDeck session; FEX stays as Components has it") - return None - result = os.path.join(launch_dir, FEX_RESULT) - request = os.path.join(launch_dir, FEX_REQUEST) - try: - os.unlink(result) - except OSError: - pass - with open(request + ".tmp", "w", encoding="utf-8") as f: - f.write("appid=%s\n" % APP_ID) - os.replace(request + ".tmp", request) - deadline = time.monotonic() + wait - while time.monotonic() < deadline: - try: - with open(result, encoding="utf-8") as f: - answer = f.read().strip() - except OSError: - time.sleep(0.5) - continue - os.unlink(result) - return answer - return None - - def wine_processes(pfx, proc="/proc"): want = os.path.realpath(pfx).rstrip("/") found = [] @@ -1148,8 +1118,6 @@ def stop_leftovers(pfx): def open_client(root, reinstall=False): pfx = os.path.join(prefix(root), "pfx") write_menu() - answer = ask_fex(os.environ.get("DD_LAUNCH_DIR")) - say("FEX: %s" % (answer or "no answer from the app; Components' choice stays")) if running(pfx): say("Battle.net is already running in its prefix; waiting for it to close") wait_while_open(pfx, grace=0) @@ -1238,8 +1206,6 @@ def launch(root, code): try: own = None if lock is not None and not running(pfx): - answer = ask_fex(os.environ.get("DD_LAUNCH_DIR")) - say("FEX: %s" % (answer or "no answer from the app; Components' choice stays")) verb = None if stop_leftovers(pfx) else "run" configure(root, LIBRARY) own = start(launcher(root), verb) @@ -1449,33 +1415,23 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country=" windows = install_path(root, folder) emit("STATE", "starting") base = os.path.join(CACHE, "agent-%s" % uid) + os.makedirs(CACHE, exist_ok=True) for suffix in (".json", ".game", ".form", ".error"): try: os.unlink(base + suffix) except OSError: pass - runtime = os.path.join(CACHE, AGENT_RUNTIME) - os.makedirs(runtime, mode=0o700, exist_ok=True) env = agent_env() - for name in ("DISPLAY", "WAYLAND_DISPLAY"): - env.pop(name, None) - env["XDG_RUNTIME_DIR"] = runtime - cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-", - windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")] + cmd = [HEADLESS, os.path.join(CACHE, AGENT_RUNTIME), "--log", os.path.join(CACHE, AGENT_LOG), "--", + os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-", + windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")] say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd))) - output = os.path.join(CACHE, AGENT_LOG) - try: - if os.path.getsize(output) > AGENT_LOG_LIMIT: - os.replace(output, output + ".1") - except OSError: - pass before = {pid for pid, _ in wine_processes(pfx)} - with open(output, "ab") as log: - try: - child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env) - except OSError as error: - emit("ERROR", "stopped gamescope: %s" % error) - return 1 + try: + child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) + except OSError as error: + emit("ERROR", "stopped gamescope: %s" % error) + return 1 seen = None mark = None moved = time.monotonic() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge b/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge new file mode 100755 index 0000000000..de334b7453 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge @@ -0,0 +1,129 @@ +#!/bin/bash +set -u +umask 077 +self=${BASH_SOURCE[0]} +proc=${DD_PROC:-/proc} +state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge} +runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run} +headless=${DD_HEADLESS_RUN:-${self%/*}/droiddeck-headless} +wait_s=${DD_CURSEFORGE_WAIT:-60} +cmd=${1:-} +dir=${2:-} +flag=--inspect-publish-uid=stderr +case $cmd in start|stop) ;; *) echo "usage: droiddeck-curseforge start|stop <imported AppImage directory>" >&2; exit 2 ;; esac +if [ ! -d "$dir/app" ]; then + echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2 + exit 2 +fi + +running() { + local p + for p in "$proc"/[0-9]*; do + tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && return 0 + done + return 1 +} + +started_at() { + local stat + stat=$(cat "/proc/$1/stat" 2>/dev/null) || return 1 + stat=${stat##*) } + set -- $stat + echo "${20}" +} + +tracked() { + local pid at launched + read -r pid at launched 2>/dev/null < "$state/pid" || return 1 + case $pid in ''|*[!0-9]*) return 1 ;; esac + kill -0 "$pid" 2>/dev/null && [ "$(started_at "$pid")" = "$at" ] || return 1 + printf '%s %s\n' "$pid" "$launched" +} + +ours() { + local pid launched + read -r pid launched <<<"$(tracked)" + [ -n "$pid" ] && [ "$launched" = "$dir" ] && echo "$pid" +} + +lock() { + mkdir -p "$state" && chmod 700 "$state" || return 1 + exec 9>"$state/lock" || return 1 + flock 9 +} + +inspector() { + grep -aom1 'ws://127\.0\.0\.1:[0-9]*/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}' "$state/log" 2>/dev/null +} + +start() { + local url pid child= + lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; } + if ! ours >/dev/null; then + if tracked >/dev/null || running; then + exec 9>&- + echo busy + return 3 + fi + mv -f "$state/log" "$state/log.1" 2>/dev/null + env -u DBUS_SESSION_BUS_ADDRESS setsid "$headless" "$state/runtime" --log "$state/log" -- \ + "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >/dev/null 2>&1 9>&- & + pid=$! + child=$pid + printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid" + fi + exec 9>&- + for _ in $(seq 1 $((wait_s * 2))); do + if url=$(inspector); then + echo "$url" + hold "$child" + return 0 + fi + ours >/dev/null || break + sleep 0.5 + done + tail -n 20 "$state/log" >&2 + return 5 +} + +hold() { + local pid + if [ -n "$1" ]; then + wait "$1" + return 0 + fi + pid=$(ours) || return 0 + while kill -0 "$pid" 2>/dev/null && [ "$(ours)" = "$pid" ]; do + sleep 1 + done +} + +stop() { + local pid p + lock || return 1 + pid=$(ours) || { tracked >/dev/null || rm -f "$state/pid"; exec 9>&-; return 0; } + kill -TERM -- "-$pid" 2>/dev/null + for _ in $(seq 1 20); do + kill -0 -- "-$pid" 2>/dev/null || break + sleep 0.5 + done + kill -KILL -- "-$pid" 2>/dev/null + kill -KILL "$pid" 2>/dev/null + for p in "$proc"/[0-9]*; do + tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null + done + rm -f "$state/pid" + exec 9>&- + return 0 +} + +case $cmd in + start) + start + exit $? + ;; + stop) + stop + exit 0 + ;; +esac diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks index e91b7090ff..24dd97d4c0 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/python3 import hashlib import json import os diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-diagnostic-inventory b/tools/linuxfs/overlay/usr/local/bin/droiddeck-diagnostic-inventory index 947c5bb1c3..86645bed2b 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-diagnostic-inventory +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-diagnostic-inventory @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/python3 import argparse import hashlib import json diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index e8edb67d5e..af236125f7 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -27,6 +27,7 @@ GAME_ENVIRONMENT = os.path.join(HOME, ".config", "droiddeck", "game-environment. BIN_DIR = os.path.dirname(os.path.abspath(__file__)) PRELOADS = "/usr/local/lib/droiddeck-fex" URUNTIME = "/usr/local/lib/droiddeck/uruntime" +DWARFSEXTRACT = "/usr/local/lib/droiddeck/dwarfsextract" HOST_PRELOAD = "/etc/ld.so.preload" FEX_APPID = "3127680" OWN_FEX = "/usr/local" @@ -51,7 +52,7 @@ PROVIDED = frozenset(( "libssl.so.3", "libcrypto.so.3", "libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1", "libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8", - "libgbm.so.1", "libdrm.so.2", "libexpat.so.1", + "libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0", )) PROVIDED_NEEDS = { "libwayland-client.so.0": ("libffi.so.8",), @@ -670,6 +671,8 @@ def guest_environment(fex, env): result.setdefault("FEX_SILENTLOG", "0") result.setdefault("FEX_OUTPUTLOG", "stderr") result.pop("GLIBC_TUNABLES", None) + if "aarch64" in result.get("GCONV_PATH", ""): + result["GCONV_PATH"] = "" result.setdefault("GC_DISABLE_INCREMENTAL", "1") if fex["portable"]: result["FEX_PORTABLE"] = "1" @@ -822,6 +825,30 @@ def extracted(): return os.path.isdir("squashfs-root") +def dwarfs_image(image): + try: + offset = appimage_offset(image) + with open(image, "rb") as f: + f.seek(offset) + return f.read(6) == b"DWARFS" + except (OSError, ValueError, struct.error): + return False + + +def dwarfs_extract(image): + clear_extracted() + os.mkdir("squashfs-root") + with open(image, "rb") as source: + status = subprocess.call([DWARFSEXTRACT, "--input", "/proc/self/fd/%d" % source.fileno(), + "--image-offset=%d" % appimage_offset(image), "--output", "squashfs-root", + "--log-level=error"], stdout=subprocess.DEVNULL, pass_fds=(source.fileno(),)) + if status == 0 and extracted(): + return True + say("dwarfsextract could not extract it (status %d)" % status) + clear_extracted() + return False + + def want_fex(): with locked(): update_own_fex() @@ -849,8 +876,12 @@ def extract(image): clear_extracted() x86 = elf_arch(image) in X86.values() if os.access(URUNTIME, os.X_OK): - run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, - env=dict(os.environ, TARGET_APPIMAGE=image)) + with open(image, "rb") as source: + native = bool(os.environ.get("DDNATV_ROOT")) + target = "/proc/self/fd/%d" % source.fileno() if native else image + run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, + env=dict(os.environ, TARGET_APPIMAGE=target), + pass_fds=(source.fileno(),) if native else ()) errors = run.stderr.decode("utf-8", "replace") sys.stderr.write(errors) status = run.returncode @@ -863,6 +894,10 @@ def extract(image): return 0 say("uruntime could not extract it (status %d)" % status) clear_extracted() + if os.access(DWARFSEXTRACT, os.X_OK) and dwarfs_image(image) and dwarfs_extract(image): + if x86: + want_fex() + return 0 fex = prepare() if x86 else None if fex is not None: status = subprocess.call([fex["bin"], image, "--appimage-extract"], stdout=subprocess.DEVNULL, @@ -880,7 +915,17 @@ def extract(image): want_fex() return 0 say("unsquashfs could not extract it (status %d)" % status) - elif fex is None: + seven = shutil.which("7z") + if seven: + clear_extracted() + status = subprocess.call([seven, "x", "-tSquashFS", "-y", "-osquashfs-root", image], stdout=subprocess.DEVNULL) + if status == 0 and extracted(): + if x86: + want_fex() + return 0 + say("7-Zip could not extract it (status %d)" % status) + clear_extracted() + elif fex is None and not unsquashfs: say("this AppImage could not be unpacked here: no AppImage runtime for ARM64, no FEX yet and no unsquashfs") return 1 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index b4b574a0aa..e1bee1c12a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -152,12 +152,24 @@ def deep_rock_gdk_raytracing(game): return {}, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"], "Deep Rock Galactic GDK: ray tracing off (D3D12 pipeline creation fails on Thor)" +@fix +def dragons_dogma_2_wine_detection(game): + if game.app_id == "2054970" and not any(a.lower().startswith("/winedetectionenabled:") for a in game.args): + return {}, ["/WineDetectionEnabled:False"], "Dragon's Dogma 2: the game's Wine detection off (its Wine path does not start)" + + @fix def ff7_rebirth_feature_level(game): if game.stem in ("ff7rebirth", "ff7rebirth_"): return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Final Fantasy VII Rebirth: D3D12 feature level 12_2 (the device-reported level fails its DX12 check)" +@fix +def hades2_feature_level(game): + if game.stem == "hades2": + return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Hades II: D3D12 feature level 12_2 (on Adreno 6xx/7xx it finds no D3D12 adapter at the detected level)" + + @fix def kcd2_feature_level(game): if game.app_id == "1771300": @@ -230,6 +242,57 @@ def skip_red_launcher(command): return command +DQM4_MESH_DETAIL = {"r.SkeletalMeshLODBias": "-4", "r.SkeletalMeshLODRadiusScale": "0.25"} + + +def with_system_settings(text, settings): + lines = text.splitlines() + try: + section = lines.index("[SystemSettings]") + except ValueError: + if lines and lines[-1].strip(): + lines.append("") + lines.append("[SystemSettings]") + section = len(lines) - 1 + end = next((i for i in range(section + 1, len(lines)) if lines[i].startswith("[")), len(lines)) + block = [line for line in lines[section + 1:end] if line.split("=", 1)[0].strip() not in settings] + while block and not block[-1].strip(): + block.pop() + block += ["%s=%s" % item for item in settings.items()] + tail = lines[end:] + return "\n".join(lines[:section + 1] + block + ([""] if tail else []) + tail) + "\n" + + +# The game ignores -ini: overrides and deletes a writable Engine.ini after reading it, so this runs at every launch. +def dragon_quest_monsters_4_mesh_detail(exe, env): + project = Path(exe).stem.split("-", 1)[0] + if not project.lower().startswith("dragonquestmonsters4"): + return + prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx" + config = prefix / "drive_c/users/steamuser/AppData/Local" / project / "Saved/Config/Windows/Engine.ini" + try: + if not prefix.is_dir(): + return + text = config.read_text(encoding="utf-8") if config.exists() else "" + updated = with_system_settings(text, DQM4_MESH_DETAIL) + if updated == text: + return + config.parent.mkdir(parents=True, exist_ok=True) + handle, staged = tempfile.mkstemp(prefix=".engine-", dir=config.parent) + try: + with os.fdopen(handle, "w", encoding="utf-8") as target: + target.write(updated) + if config.exists(): + os.chmod(staged, config.stat().st_mode & 0o7777) + os.replace(staged, config) + except BaseException: + os.unlink(staged) + raise + print("droiddeck-game-env: Dragon Quest Monsters 4: full-detail monster meshes", file=sys.stderr) + except (OSError, UnicodeDecodeError) as error: + print("droiddeck-game-env: Dragon Quest Monsters 4 mesh detail left as is (%s)" % error, file=sys.stderr) + + UBISOFT_LAUNCHER = "drive_c/Program Files (x86)/Ubisoft/Ubisoft Game Launcher" UBISOFT_SETTINGS = "drive_c/users/steamuser/AppData/Local/Ubisoft Game Launcher/settings.yaml" @@ -1400,6 +1463,7 @@ def main(): command = skip_red_launcher(command) if len(command) > 2: death_stranding_allocator(app_id, command[2]) + dragon_quest_monsters_4_mesh_detail(command[2], effective_env) ubisoft_overlay_off(env) project_zomboid_jvm(command) fixes, extra, notes = engine_fixes(command[2], command[3:], app_id) if len(command) > 2 else ({}, [], []) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless b/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless new file mode 100755 index 0000000000..c8bc6cee0b --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless @@ -0,0 +1,24 @@ +#!/bin/bash +set -u +runtime=${1:-} +shift +log= +if [ "${1:-}" = --log ]; then + log=${2:-} + shift 2 +fi +if [ -z "$runtime" ] || [ "${1:-}" != -- ] || [ $# -lt 2 ]; then + echo "usage: droiddeck-headless <private runtime directory> [--log <file>] -- <command> [args...]" >&2 + exit 2 +fi +shift +umask 077 +mkdir -p "$runtime" && chmod 700 "$runtime" || exit 1 +if [ -n "$log" ]; then + size=$(stat -c %s "$log" 2>/dev/null || echo 0) + [ "$size" -gt "${DD_HEADLESS_LOG_LIMIT:-4194304}" ] && mv -f "$log" "$log.1" + exec >>"$log" 2>&1 +fi +unset DISPLAY WAYLAND_DISPLAY GAMESCOPE_WAYLAND_DISPLAY XAUTHORITY +export XDG_RUNTIME_DIR=$runtime +exec gamescope --backend headless -w 640 -h 480 -- "$@" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime b/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime index d6fd4cd3bc..f296a57c6a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/python3 import json import os import select diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index ee13167e38..8bcf875fce 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -540,7 +540,7 @@ if [ -z "${DD_INSIDE:-}" ]; then args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h") if [ "${game_size:-0}" != 1 ] && { [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; }; then args+=(-S stretch) - export DD_STRETCHED=1 + export DD_STRETCHED=1 DD_STRETCH_OUTPUT="${width}x${height}" DD_STRETCH_GAME="${nested}x${nested_h}" fi if [ "${DD_REFRESH:-0}" -gt 0 ]; then args+=(-r "$DD_REFRESH") @@ -593,6 +593,12 @@ dd_xprop_set_all() { done [ "$ok" = 1 ] } +dd_stretch_game_screen() { + local idx w h super + IFS=', ' read -r idx w h super <<<"$1" + [ "$idx" = 1 ] && [ "${w}x${h}" = "$2" ] && [ "${super:-0}" = 0 ] || return 1 + xprop -root -f GAMESCOPE_XWAYLAND_MODE_CONTROL 32c -set GAMESCOPE_XWAYLAND_MODE_CONTROL "$idx, ${3%x*}, ${3#*x}, 1" 2>/dev/null +} export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11 reap_orphans() { local round p stat pid left @@ -1205,7 +1211,7 @@ case $mode in [ "${DD_STRETCHED:-0}" = 1 ] && stretch=1 [ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1 atoms=(STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP) - [ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER) + [ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER GAMESCOPE_XWAYLAND_MODE_CONTROL) prop_value() { case $1 in *'not found'*|*=) pv=$2; return ;; esac pv=${1#*=} @@ -1273,6 +1279,11 @@ case $mode in xprop -root -f GAMESCOPE_NEW_SCALING_SCALER 32c -set GAMESCOPE_NEW_SCALING_SCALER 4 2>/dev/null \ && echo "== stretch 16:9 to panel: the client's scaler was Auto, set to Stretch" ;; + GAMESCOPE_XWAYLAND_MODE_CONTROL*) + prop_value "$line" "" + dd_stretch_game_screen "$pv" "$DD_STRETCH_OUTPUT" "$DD_STRETCH_GAME" \ + && echo "== stretch 16:9 to panel: the client sized the game screen to the output ($DD_STRETCH_OUTPUT), set to $DD_STRETCH_GAME" + ;; esac done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null) ) & @@ -1417,11 +1428,10 @@ case $mode in export STEAM_STEAMRT_RECURSION_GUARD=1 export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} export SDL_VIDEO_X11_DGAMOUSE=0 - dd_steam_path=$PATH + dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH" dd_steam_angle=vulkan dd_steam_presentation=() if [ "${DD_STEAM_GL_PRESENT:-}" = 1 ]; then - dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH" export DISABLE_GAMESCOPE_WSI=1 LIBGL_KOPPER_DISABLE=true dd_steam_angle=gl dd_steam_presentation=(-cef-disable-gpu-compositing) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat index b39682bc29..32a9889b87 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat @@ -66,19 +66,32 @@ BRIGHTNESS_JS = r""" """.replace("__BINDING__", BRIGHTNESS_BINDING) +def control_request(name, text, directory): + path = os.path.join(directory, name) + with open(path + ".tmp", "w") as target: + target.write(text + "\n") + os.replace(path + ".tmp", path) + + def brightness_request(payload, directory=CONTROLS_DIR): try: value = float(payload) if not math.isfinite(value) or not 0 <= value <= 1: return - path = os.path.join(directory, "brightness.request") - with open(path + ".tmp", "w") as target: - target.write(str(value) + "\n") - os.replace(path + ".tmp", path) + control_request("brightness.request", str(value), directory) except (ValueError, TypeError, OSError): return +def hdr_request(payload, directory=CONTROLS_DIR): + if payload not in ("0", "1"): + return + try: + control_request("hdr.request", payload, directory) + except OSError: + return + + INSTALL_JS = r""" (() => { if (window.__droiddeckCompat) return "present"; @@ -256,6 +269,49 @@ TOUR_JS = r""" return "off"; })() """ +SET_SETTING_JS = r"""(field, value) => { + const bytes = []; + for (let n of [field * 8, value]) { + while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); } + bytes.push(n); + } + return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes))); + }""" +HDR_BINDING = "droiddeckHdrChanged" +HDR_JS = r""" +(() => { + if (window.__droiddeckHdr) return "present"; + const settings = window.settingsStore; + if (typeof settings?.clientSettings?.gamescope_hdr_enabled !== "boolean" || + typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable"; + const write = __SET_SETTING__; + const HOLD_MS = 3000; + const self = { known: settings.clientSettings.gamescope_hdr_enabled, pending: null, until: 0 }; + self.set = value => { + if (typeof value !== "boolean") return true; + self.known = value; + if (settings.clientSettings.gamescope_hdr_enabled === value && self.pending === null) return true; + self.pending = value; + self.until = performance.now() + HOLD_MS; + write(21015, value ? 1 : 0); + return true; + }; + self.check = () => { + const value = settings.clientSettings.gamescope_hdr_enabled; + if (typeof value !== "boolean") return; + if (self.pending !== null) { + if (value !== self.pending && performance.now() < self.until) return; + self.pending = null; + } + if (value === self.known) return; + self.known = value; + if (typeof window.__BINDING__ === "function") window.__BINDING__(value ? "1" : "0"); + }; + self.interval = setInterval(self.check, 500); + window.__droiddeckHdr = self; + return "installed"; +})() +""".replace("__BINDING__", HDR_BINDING).replace("__SET_SETTING__", SET_SETTING_JS) FRAME_LIMIT_JS = r""" (() => { if (window.__droiddeckFrameLimit) return "present"; @@ -281,14 +337,7 @@ FRAME_LIMIT_JS = r""" } if (!service || !settings?.clientSettings || typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable"; const self = { timer: null }; - const write = value => { - const bytes = []; - for (let n of [21002 * 8, value]) { - while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); } - bytes.push(n); - } - return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes))); - }; + const write = value => (__SET_SETTING__)(21002, value); self.check = async () => { let rates; try { @@ -316,7 +365,7 @@ FRAME_LIMIT_JS = r""" window.__droiddeckFrameLimit = self; return "installed"; })() -""" +""".replace("__SET_SETTING__", SET_SETTING_JS) WINDOW_BINDING = "droiddeckWindowAction" WINDOW_TARGET = "createflags=18" WINDOW_MOVES = {"nw": 0, "n": 1, "ne": 2, "e": 3, "se": 4, "s": 5, "sw": 6, "w": 7, "move": 8} @@ -923,6 +972,9 @@ class Helper: self.controls_installed = False self.frame_limit_state = None self.frame_limit_retry = 0 + self.hdr_state = None + self.hdr_installed = False + self.hdr_retry = 0 self.windows = {} self.windows_retry = 0 @@ -983,6 +1035,29 @@ class Helper: except (Closed, OSError, ValueError): del self.windows[ident] + def sync_hdr(self): + try: + with open(os.path.join(CONTROLS_DIR, "state.json")) as source: + value = json.load(source).get("hdr") + if not isinstance(value, bool): + return + if not self.hdr_installed: + if time.monotonic() < self.hdr_retry: + return + self.page.call("Runtime.addBinding", {"name": HDR_BINDING}) + self.hdr_installed = self.page.evaluate(HDR_JS) in ("installed", "present") + if not self.hdr_installed: + self.hdr_retry = time.monotonic() + 10 + return + if value != self.hdr_state: + if self.page.evaluate("window.__droiddeckHdr ? window.__droiddeckHdr.set(%s) : false" % json.dumps(value)) is True: + self.hdr_state = value + else: + self.hdr_state = None + self.hdr_installed = False + except (OSError, ValueError, TypeError, AttributeError): + pass + def sync_frame_limit(self): if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry: return @@ -1095,6 +1170,9 @@ class Helper: self.controls_installed = False self.frame_limit_state = None self.frame_limit_retry = 0 + self.hdr_state = None + self.hdr_installed = False + self.hdr_retry = 0 self.sync_controls() return True @@ -1231,6 +1309,8 @@ class Helper: for e in events: if called(e, BRIGHTNESS_BINDING): brightness_request(e.get("params", {}).get("payload")) + if called(e, HDR_BINDING): + hdr_request(e.get("params", {}).get("payload")) if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str): self.open_chooser(e["params"]["payload"]) return events @@ -1260,6 +1340,7 @@ class Helper: while True: self.sync_controls() self.sync_frame_limit() + self.sync_hdr() self.sync_windows() sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else []) sources += [page.ws for page in self.windows.values()] diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games index c618cadf35..a3cbb9578e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/python3 import ctypes as C import functools import json @@ -71,6 +71,10 @@ def store_game(game): return bool(game.get("store")) +def steam_program(game): + return game.get("route") is not False + + def manifest_ids(steamapps, name): matches = [] try: @@ -230,7 +234,7 @@ def remember_tried(steam_root, account, appids): def watch(steam_root, listing): - games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native")] + games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native") and steam_program(game)] if os.environ.get("DD_STEAM_OFFLINE") == "1" or not games: return candidates, sources = {}, {} @@ -526,6 +530,13 @@ def release(steam_root, game, stale, reason): print(f"droiddeck-steam-games: {game.get('name', appid)} {reason}; it is no longer Steam app {appid}") +def release_stale(steam_root, game, stale): + try: + release(steam_root, game, stale, "names another Steam app now") + except OSError as error: + print(f"droiddeck-steam-games: earlier import not undone ({error})") + + PREFIX_LINKS = ".droiddeck-prefix-links.json" @@ -603,17 +614,18 @@ def route(steam_root, acct, games): if game.get("native"): shortcuts.append(game) continue + if not steam_program(game): + release_stale(steam_root, game, lambda old: old == SPACEWAR) + share_prefix(steam_root, game) + shortcuts.append(game) + continue folder = game.get("folder", "") appid = candidates.get(folder, candidates.get(legacy_path(folder))) stamp = source_stamp(game) recorded = sources.get(folder, sources.get(legacy_path(folder))) current = stamp is not None and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:]) named = isinstance(appid, int) and 0 < appid < 0x80000000 and appid != SPACEWAR - try: - release(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid), - "names another Steam app now") - except OSError as error: - print(f"droiddeck-steam-games: earlier import not undone ({error})") + release_stale(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid)) confirmed = named and current and owned.get(str(appid)) is True if confirmed: try: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install index c58790f87a..bbacb7652f 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install @@ -65,12 +65,15 @@ if [ -n "$repair" ]; then [ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part" done fi +cache_only= +applied= +[ "${1:-}" = --cache ] && cache_only=1 sync= if [ "${1:-}" = --sync ]; then case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac manifest=steam_client_${sync}_linuxarm64 fi -[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0 +[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0 work=$(mktemp -d) trap 'rm -rf "$work"' EXIT @@ -130,6 +133,156 @@ fetch() { done } +# The same decisions as fetch for the parallel workers, with curl in the foreground and a plain sleep between tries: +# the shell here cannot open /dev/fd for process substitution from a background job. +fetch_one() { + local url=$1 dest=$2 size=$3 sum=$4 part=$5 failures=0 bad=0 finished=0 before rc http wait + while :; do + if [ -f "$dest" ] && { [ "$finished" = 1 ] || { [ "$size" -gt 0 ] && [ "$(size_of "$dest")" -ge "$size" ]; }; }; then + echo "$sum $dest" | sha256sum -c --quiet 2>/dev/null && return 0 + rm -f "$dest" + finished=0 bad=$((bad + 1)) + [ "$bad" -lt 3 ] || { echo "droiddeck-steam-install: $part does not match its checksum" >&2; return 1; } + fi + before=$(size_of "$dest") + http=$(curl -fsSL "${limits[@]}" -w '%{http_code}' -C - -o "$dest" "$url") && rc=0 || rc=$? + if [ "$rc" = 0 ]; then finished=1; continue; fi + case "$rc:${http:-}" in + 22:416 | 33:*) rm -f "$dest" ;; + 22:4??) + echo "droiddeck-steam-install: $part: HTTP $http from ${url%/*}" >&2 + return 1 + ;; + esac + if [ "$(size_of "$dest")" -gt "$before" ]; then failures=0; else failures=$((failures + 1)); fi + if [ "$failures" -gt "${#delays[@]}" ]; then + echo "droiddeck-steam-install: could not download $part (curl exit $rc); what arrived is kept for the next try" >&2 + return 1 + fi + wait=${delays[$((failures > 0 ? failures - 1 : 0))]} + step "downloading Steam: $part - interrupted (curl exit $rc), trying again in ${wait} s" + sleep "$wait" + done +} + +parallel=${DD_STEAM_PARALLEL:-4} +case $parallel in ''|*[!0-9]*|0) parallel=1 ;; esac +flock_command=${DD_STEAM_FLOCK:-flock} +command -v "$flock_command" > /dev/null 2>&1 || parallel=1 + +# unzip creates parent directories without guarding against another unzip doing the same, so two packages unpacked into +# one tree at once fail now and then. Unpacking is quick next to downloading, so the workers take turns on a flock: the +# kernel hands it on when its holder ends, however it ends, so there is no stale lock to recover. +unzip_alone() { + local rc + ( "$flock_command" 9 && unzip -qo "$1" -d "$steam_root" ) 9> "$state/unzip.lock" && rc=0 || rc=$? + return $rc +} + +# Takes the next unclaimed line number from a counter under a flock, and prints 0 when none is left. mkdir was tried for this +# and handed the same line to two workers now and then in the app's guest shell, so only the kernel's lock is trusted here. +claim_next() { + local n + while :; do + # A counter that cannot be read or written must fail the worker: a stale or empty number would give a package to two workers or to none. + n=$( { "$flock_command" 8 || exit 1 + n=$(cat "$state/next") || exit 1 + case $n in ''|*[!0-9]*) exit 1 ;; esac + echo $((n + 1)) > "$state/next" || exit 1 + echo "$n"; } 8> "$state/claim.lock" ) || return 1 + [ "$n" -le "$count" ] || { echo 0; return; } + if [ ! -e "$state/$n.done" ]; then + : > "$state/claim.$n" + echo "$n" + return + fi + done +} + +# Fetches every line of a list ("block file sum size") into $dir with up to $parallel connections. With a third +# argument each package is also unpacked into the client as it lands. One connection tops out near half of what a +# Wi-Fi link carries, so the packages arrive about twice as fast. Workers take the next unclaimed line themselves +# (claim_next) and only plain background jobs and wait on a pid are used, so nothing depends on job control. +run_parallel() { + local list=$1 dir=$2 unpack=${3:-} state index=0 block file sum size + local -a blocks=() files=() sums=() sizes=() pids=() + state=$work/parallel + rm -rf "$state" + mkdir -p "$state" + echo 1 > "$state/next" + while read -r block file sum size; do + index=$((index + 1)) + blocks[index]=$block files[index]=$file sums[index]=$sum sizes[index]=$size + if [ -n "$unpack" ] && [ -f "$dir/$file.unpacked" ]; then + : > "$state/$index.done" + fi + done < "$list" + local count=$index total_bytes=0 + for index in $(seq 1 "$count"); do total_bytes=$((total_bytes + sizes[index])); done + local slot + for slot in $(seq 1 "$parallel"); do + ( + trap ': > "$state/exit.$slot"' EXIT + while [ ! -e "$state/failed" ]; do + # run_parallel is called in an || list, which switches set -e off in here: a failed claim has to be checked by hand. + index=$(claim_next) || { : > "$state/failed"; exit 1; } + [ "$index" -gt 0 ] || exit 0 + file=${files[index]} + fetched="" + for host in "${cdn_order[@]}"; do + if fetch_one "$host/$file" "$dir/$file" "${sizes[index]}" "${sums[index]}" "${blocks[index]}"; then + fetched=$host + break + fi + done + if [ -z "$fetched" ]; then + echo "droiddeck-steam-install: $file failed on every CDN" >&2 + : > "$state/failed" + exit 1 + fi + if [ -n "$unpack" ]; then + unzip_alone "$dir/$file" || { : > "$state/failed"; exit 1; } + : > "$dir/$file.unpacked" + rm -f "$dir/$file" + fi + : > "$state/$index.done" + done + ) & + pids+=($!) + done + local shown="" got n alive mark current last="" since=$SECONDS stall=${DD_STEAM_STALL:-90} + while :; do + alive=0 + for slot in $(seq 1 "$parallel"); do [ -e "$state/exit.$slot" ] || alive=1; done + got=0 n=0 current="" + for index in $(seq 1 "$count"); do + if [ -e "$state/$index.done" ]; then + got=$((got + sizes[index])) n=$((n + 1)) + elif [ -e "$state/claim.$index" ]; then + current=$index + [ -f "$dir/${files[index]}" ] && got=$((got + $(size_of "$dir/${files[index]}"))) + fi + done + mark=$((got / 1000000)) + if [ -n "$current" ] && [ "$mark" != "$shown" ]; then + shown=$mark + step "downloading Steam: ${blocks[current]} ($((n + 1))/$count), $mark of $((total_bytes / 1000000)) MB" + fi + [ "$n" -lt "$count" ] || alive=0 + if [ "$got" != "$last" ]; then last=$got since=$SECONDS; fi + # A worker killed from outside never writes its exit marker. Stop reporting once nothing has moved for a while + # and wait on the workers: wait returns the killed one's status, so the install fails instead of hanging. + [ $((SECONDS - since)) -lt "$stall" ] || alive=0 + [ "$alive" = 1 ] || break + sleep 1 + done + local failed="" + for slot in "${pids[@]}"; do wait "$slot" || failed=1; done + [ ! -e "$state/failed" ] || failed=1 + rm -rf "$state" + [ -z "$failed" ] +} + fetch_manifest() { cdn="" for candidate in $cdn_list; do @@ -167,6 +320,66 @@ if ! fetch_manifest; then fallback=1 fetch_manifest || exit 1 fi +if [ -n "$cache_only" ]; then + cache=$steam_root/package + cached=$cache/droiddeck-cached + [ "$(cat "$cached" 2>/dev/null)" = "$version" ] && exit 0 + awk -F'"' ' + /^\t"/ && NF >= 3 && $4 == "" { block = $2 } + $2 == "file" { file[block] = $4 } + $2 == "sha2" { sha[block] = $4 } + $2 == "size" { size[block] = $4 } + $2 == "zipvz" { vz[block] = $4 } + $2 == "sha2vz" { vzsha[block] = $4 } + END { + for (b in file) { + f = file[b]; h = sha[b]; n = size[b] + 0 + if (b in vz) { f = vz[b]; h = vzsha[b]; k = split(f, bits, "_"); n = bits[k] + 0 } + print b, f, h, n + } + } + ' "$work/manifest" | sort > "$work/cache" + mkdir -p "$cache" + total=$(grep -c . "$work/cache" 2>/dev/null || echo 0) + total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache") + done_bytes=0 + i=0 + if [ "$parallel" -gt 1 ]; then + run_parallel "$work/cache" "$cache" || exit 1 + else + while read -r block file sum size; do + i=$((i + 1)) + progress "$cache/$file" "$block" + fetched="" + for host in "${cdn_order[@]}"; do + if fetch "$host/$file" "$cache/$file" "$size" "$sum" "$block"; then + fetched=$host + break + fi + done + [ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; } + done_bytes=$((done_bytes + size)) + done < "$work/cache" + fi + applier= + trap 'kill "$applier" 2>/dev/null || :; wait "$applier" 2>/dev/null || :; rm -f "$cache/$manifest.installed" "$cached"; exit 143' TERM INT HUP + echo "$version" > "$cached" + preapply=${DD_STEAM_PREAPPLY:-/usr/local/bin/droiddeck-steam-preapply} + if [ -x "$preapply" ] && command -v python3 >/dev/null 2>&1; then + python3 "$preapply" "$cache" "$steam_root" "$work/manifest" "$manifest" & + applier=$! + if wait "$applier"; then + cp -f "$work/manifest" "$cache/$manifest.manifest" + chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true + while read -r _ file _; do rm -f "$cache/$file"; done < "$work/cache" + [ -f "$stamp" ] || applied=1 + else + rm -f "$cache/$manifest.installed" "$cached" + fi + fi + trap - TERM INT HUP + [ -n "$applied" ] || exit 0 +fi if [ -n "$sync" ]; then installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true) if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then @@ -175,6 +388,7 @@ if [ -n "$sync" ]; then fi echo "== STEP $(date -u +%H:%M:%S) updating the arm64 Steam client to $version (was ${installed:-none}) for the x86-64 client" fi +if [ -z "$applied" ]; then total=$(grep -c . "$work/parts" 2>/dev/null || echo 0) total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/parts") @@ -186,6 +400,9 @@ for left in "$parts"/*; do grep -qF " $name " "$work/parts" || rm -rf "$left" done done_bytes=0 +if [ "$parallel" -gt 1 ]; then + run_parallel "$work/parts" "$parts" unpack || exit 1 +else while read -r block file sum size; do i=$((${i:-0} + 1)) if [ -f "$parts/$file.unpacked" ]; then @@ -206,6 +423,8 @@ while read -r block file sum size; do rm -f "$parts/$file" done_bytes=$((done_bytes + size)) done < "$work/parts" +fi +fi find "$steam_root" -depth -name '*\\*' | while read -r odd; do fixed=${odd//\\//} mkdir -p "$(dirname "$fixed")" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply new file mode 100755 index 0000000000..841111af21 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Extract Steam's cached update packages and record them the way Steam's own updater does.""" +import hashlib, lzma, os, re, stat, struct, sys, time, zipfile, io, zlib, calendar + +OSVER = "-184" +MTIME_OFFSET = 28800 + + +def blocks(manifest): + out, cur, depth = {}, None, 0 + for line in manifest.splitlines(): + m = re.match(r'^(\t+)"([^"]+)"\s*(?:"([^"]*)")?\s*$', line) + if m and m.group(3) is None and len(m.group(1)) == 1: + cur = m.group(2) + out[cur] = {} + elif m and m.group(3) is not None and len(m.group(1)) == 2 and cur: + out[cur][m.group(2)] = m.group(3) + return out + + +def unvz(d): + if d[:3] != b"VZa" or d[-2:] != b"zv": + raise ValueError("not a VZip") + props = d[7] + dict_size = struct.unpack("<I", d[8:12])[0] + crc, size = struct.unpack("<II", d[-10:-2]) + f = [{"id": lzma.FILTER_LZMA1, "dict_size": dict_size, + "lc": props % 9, "lp": (props // 9) % 5, "pb": props // 45}] + out = lzma.LZMADecompressor(format=lzma.FORMAT_RAW, filters=f).decompress(d[12:-10], max_length=size) + if len(out) != size or zlib.crc32(out) & 0xFFFFFFFF != crc: + raise ValueError("bad VZip") + return out + + +def inside(root, path): + return os.path.commonpath([root, path]) == root + + +def main(package_dir, steam_root, manifest_path, name): + steam_root = os.path.realpath(steam_root) + manifest = open(manifest_path, encoding="utf-8", errors="replace").read() + rows = {} + for block, attrs in blocks(manifest).items(): + for key in ("zipvz", "file"): + f = attrs.get(key) + if f and os.path.isfile(os.path.join(package_dir, f)): + break + else: + raise SystemExit(f"missing package for {block}") + data = open(os.path.join(package_dir, f), "rb").read() + zdata = unvz(data) if key == "zipvz" else data + del data + with zipfile.ZipFile(io.BytesIO(zdata)) as z: + for info in z.infolist(): + rel = info.filename.replace("\\", "/") + if rel.startswith("/") or ".." in rel.split("/"): + raise SystemExit(f"unsafe path in {block}: {rel}") + dest = os.path.join(steam_root, rel) + if not inside(steam_root, os.path.realpath(os.path.dirname(dest.rstrip("/")))): + raise SystemExit(f"path leaves the Steam root in {block}: {rel}") + mode = (info.external_attr >> 16) & 0xFFFF + mtime = calendar.timegm(info.date_time + (0, 0, 0)) + MTIME_OFFSET + if rel.endswith("/"): + os.makedirs(dest, exist_ok=True) + rows[rel] = (-1, mtime, 0) + continue + os.makedirs(os.path.dirname(dest), exist_ok=True) + if stat.S_ISLNK(mode): + if os.path.lexists(dest): + os.unlink(dest) + os.symlink(z.read(info).decode(), dest) + rows[rel] = (-2, mtime, info.CRC) + continue + with open(dest + ".dd-tmp", "wb") as out: + out.write(z.read(info)) + os.chmod(dest + ".dd-tmp", (mode & 0o777) | 0o644 if mode else 0o644) + os.replace(dest + ".dd-tmp", dest) + rows[rel] = (info.file_size, mtime, info.CRC) + del zdata + body = "".join(f"{p},{s};{m};{c}\n" for p, (s, m, c) in sorted(rows.items(), key=lambda kv: kv[0].upper())) + body += f"OSVER={OSVER}\nVERSION=3\n" + sha = hashlib.sha1(body.encode()).hexdigest().upper() + pkg = os.path.join(steam_root, "package") + os.makedirs(pkg, exist_ok=True) + tmp = os.path.join(pkg, name + ".installed.dd-tmp") + with open(tmp, "w", encoding="utf-8") as f: + f.write(body + f"SHA1={sha}\n") + os.replace(tmp, os.path.join(pkg, name + ".installed")) + + +if __name__ == "__main__": + main(*sys.argv[1:5]) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts index 4cb3301d41..31d679677c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/python3 """Import added games while Steam is closed, preserving user-created shortcuts. Usage: droiddeck-steam-shortcuts <steam_root> <added-games.json> @@ -125,6 +125,14 @@ RECORD = ".droiddeck-shortcuts.json" AWAY_LIMIT = 256 FIELDS = ("AppName", "Exe", "StartDir", "icon", "LaunchOptions") FOLLOWED = ("StartDir", "LaunchOptions") +# Guest mountpoints whose contents live on storage the user can unplug. The app creates +# the mountpoint before binding it, so it outlives a removed card; libraries, store +# volumes and added game folders get one mountpoint each under these families. +REMOVABLE_ROOTS = ("/mnt/droiddeck-sd", "/mnt/bannerlator-sd") +REMOVABLE_FAMILIES = ("/mnt/droiddeck-lib", "/mnt/droiddeck-stores", "/root/Games") +# Guest trees the app always has, whatever storage is in the device. A target that is +# missing from one of these is gone even when its whole folder was removed. +INTERNAL_ROOTS = ("/root/Games/Stores", "/root/.local/share/Steam") def unquoted(value): @@ -146,6 +154,46 @@ def read_record(path): } +def under(path, root): + return path == root or path.startswith(root + "/") + + +def internal_target(target): + path = os.path.normpath(target) + return any(under(path, root) for root in INTERNAL_ROOTS) + + +def removable_mount(target): + """The guest mountpoint holding target, when it is storage the user can unplug.""" + path = os.path.normpath(target) + for root in REMOVABLE_ROOTS: + if under(path, root): + return root + for family in REMOVABLE_FAMILIES: + prefix = family + "/" + if path.startswith(prefix): + return prefix + path[len(prefix):].split("/", 1)[0] + return None + + +def storage_mounted(target): + """Whether the storage holding target is there this session. + + The app creates a guest mountpoint before binding storage to it, so a mountpoint that + lists nothing is one a removed card or volume left behind. A target under it may work + again when that storage returns, so its absence is not proof the file is gone. + """ + if internal_target(target): + return True + mount = removable_mount(target) + if mount is None: + return True + try: + return bool(os.listdir(mount)) + except OSError: + return False + + def merge(fresh, current, state, seen): state = state if isinstance(state, dict) else {} rev = state.get("rev") if isinstance(state.get("rev"), int) else 0 @@ -158,7 +206,16 @@ def merge(fresh, current, state, seen): entry = dict(current) entry["appid"] = fresh["appid"] exe = unquoted(fresh["Exe"]) - if exe != unquoted(current.get("Exe")) and (exe != unquoted(base.get("Exe")) or seen == rev): + target = unquoted(current.get("Exe")) + # A target Steam still points at after the file is gone starts nothing, so it is not + # an edit to keep: the app's own exe replaces it (#694: a hand-typed Target outlived + # the game update that removed the file, and every launch died before the game ran). + # Only when its storage is mounted and it is missing from a tree the app always has or + # from a folder that is still there. An absent folder under a mountpoint can equally be + # unplugged storage, and that target may work again next session. + gone = (bool(target) and not os.path.isfile(target) and storage_mounted(target) and + (internal_target(target) or os.path.isdir(os.path.dirname(target)))) + if exe != target and (gone or exe != unquoted(base.get("Exe")) or seen == rev): entry["Exe"], entry["StartDir"] = fresh["Exe"], fresh["StartDir"] for field in ("AppName", "icon"): if current.get(field) == base.get(field): diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale index c1c2cc6ebc..2a9585efe7 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ui-scale @@ -10,6 +10,7 @@ import tempfile DISPLAY = "External: gamescope|||Windowed" NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution" SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame") +SCREENSAVER_CURRENT = ("Customization", "Screensaver", "CurrentScreensaver") TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]') @@ -137,6 +138,10 @@ def seed_no_screensaver_in_game(text): return seed_value(text, SCREENSAVER_IN_GAME, '0') +def seed_bouncing_logo(text): + return seed_value(text, SCREENSAVER_CURRENT, 'steam-bouncinglogo') + + def atomic_write(path, text): path.parent.mkdir(parents=True, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent) @@ -179,6 +184,11 @@ def initialize_screensaver(steam_root): '== steam: no screensaver over a running game') +def initialize_screensaver_choice(steam_root): + return seed_once(steam_root, 'droiddeck-screensaver-choice-initialized', seed_bouncing_logo, + '== steam: bouncing logo screensaver') + + if __name__ == '__main__': status = 0 try: @@ -186,7 +196,7 @@ if __name__ == '__main__': except (OSError, ValueError, RecursionError) as error: print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr) status = 1 - for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)): + for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver), ('screensaver choice', initialize_screensaver_choice)): try: step(sys.argv[1]) except (OSError, ValueError, RecursionError) as error: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 index 2c77626a1c..97185184c3 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 @@ -713,14 +713,67 @@ x64_webhelper_gpu() { x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && [ "${DD_X64_CEF_GPU:-1}" != 0 ] } +x64_thunk_appconfigs() { + python3 - "$1" "$2" "$3" "$4" <<'PY' || true +import json, os, sys, tempfile +src, dst, cfg, on = sys.argv[1:5] +want = json.loads(cfg) +try: + names = sorted(os.listdir(src)) +except OSError: + names = [] +for name in names: + if not name.endswith(".json"): + continue + try: + db = json.load(open(os.path.join(src, name), encoding="utf-8")).get("ThunksDB") or {} + if not any(k in want["ThunksDB"] and not v for k, v in db.items()): + continue + except (OSError, ValueError, AttributeError): + continue + path = os.path.join(dst, name) + try: + cur = json.load(open(path, encoding="utf-8")) + except FileNotFoundError: + cur = None + except (OSError, ValueError): + continue + if cur is not None and cur != want: + continue + if on == "1" and cur is None: + try: + os.makedirs(dst, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=dst, prefix=".fex", suffix=".tmp") + except OSError: + continue + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(cfg + "\n") + os.link(tmp, path) + except OSError: + pass + finally: + try: + os.remove(tmp) + except OSError: + pass + elif on != "1" and cur is not None: + try: + os.remove(path) + except OSError: + pass +PY +} + x64_env() { export -p | grep -v -E '^declare -x (PWD|OLDPWD|SHLVL|_)=' > "$X64_HOME/arm-session.env.new" || true mv -f "$X64_HOME/arm-session.env.new" "$X64_HOME/arm-session.env" unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME STEAM_RUNTIME_PREFER_HOST_LIBRARIES gpu_vars="GALLIUM_DRIVER MESA_LOADER_DRIVER_OVERRIDE VK_ICD_FILENAMES VK_DRIVER_FILES LIBGL_KOPPER_DRI2 ZINK_DEBUG ZINK_DESCRIPTORS TU_DEBUG MESA_NO_ERROR mesa_glthread" +thunk_cfg='{"ThunksDB": {"GL": 1, "Vulkan": 1}}' rm -f "$X64_HOME/game-gpu.env" if x64_gpu; then - printf '{"ThunksDB": {"GL": 1, "Vulkan": 1}}\n' > "$X64_HOME/thunks.json" + printf '%s\n' "$thunk_cfg" > "$X64_HOME/thunks.json" { echo "export FEX_THUNKCONFIG='$X64_HOME/thunks.json'" echo "unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER" @@ -729,7 +782,10 @@ if x64_gpu; then done } > "$X64_HOME/game-gpu.env" fi -if x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ]; then +client_thunks=0 +x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && client_thunks=1 +x64_thunk_appconfigs /usr/local/share/fex-emu/AppConfig "$X64_HOME/.config/fex-emu/AppConfig" "$thunk_cfg" "$client_thunks" +if [ "$client_thunks" = 1 ]; then export FEX_THUNKCONFIG=$X64_HOME/thunks.json unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE else diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch index 5031cb93dc..76bdb395f0 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch @@ -5,6 +5,7 @@ import binascii import json import os import re +import runpy import shlex import shutil import stat @@ -337,6 +338,13 @@ UBISOFT_INSTALLER_URL = "https://static3.cdn.ubi.com/orbit/launcher_installer/Ub ROCKSTAR_SERVICE = Path("/usr/local/lib/droiddeck-rockstar") SERVICE_WAIT = 300.0 ROCKSTAR_FOLDER = "drive_c/Program Files/Rockstar Games/Launcher" +EPIC_SDK_SETUP = ROCKSTAR_FOLDER + "/Redistributables/SocialClub/Social-Club-Setup.exe" +SDK_SOURCE = ".droiddeck-sdk-source" +SDK_SETUP_LIMIT = 256 * 1024 * 1024 +EPIC_PARENT = Path("/usr/local/lib/droiddeck-epic/EpicGamesLauncher.exe") +EPIC_PARENT_ON = 'set "DD_P=1"' +EPIC_PARENT_SWITCH = "DD_EPIC_PARENT" +EPIC_SERVICE_WAIT = 60.0 ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas", "gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"} @@ -394,10 +402,9 @@ def rockstar_sdk(folder, sidecar): return False -def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None): +def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None, launcher=True): pfx = Path(compat_data) / "pfx" - launcher = r"C:\Program Files\Rockstar Games\Launcher" - values = [(r"Rockstar Games\Launcher", launcher)] + values = [(r"Rockstar Games\Launcher", r"C:\Program Files\Rockstar Games\Launcher")] if launcher else [] if title: values.append(("Rockstar Games\\" + title, windows_path(str(folder)))) entries = [("Software\\" + view + key, value) for view in ("", "Wow6432Node\\") for key, value in values] @@ -420,23 +427,29 @@ def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None): return result.returncode == 0 -def rockstar_runtime(folder, exe, compat_data, arch): +def rockstar_runtime(folder, exe, compat_data, arch, installer=None): if arch == "x86": - rockstar_runtime(folder, exe, compat_data, "x64") + rockstar_runtime(folder, exe, compat_data, "x64", installer) pfx = Path(compat_data) / "pfx" target = pfx / "drive_c" / ("Program Files (x86)" if arch == "x86" else "Program Files") / "Rockstar Games/Social Club" if not target.resolve().is_relative_to(pfx.resolve()): raise ValueError("invalid Social Club destination") required = ("socialclub.dll", "socialclub.pak") + (("SocialClubHelper.exe",) if arch == "x64" else ()) marker = target / ".droiddeck-installing" - if all((target / name).is_file() for name in required) and not marker.exists(): + source_file, stamp = target / SDK_SOURCE, None + if installer is not None: + info = installer.stat() + stamp = "%d %d %s" % (info.st_size, info.st_mtime_ns, installer) + current = stamp is None or source_file.is_file() and not source_file.is_symlink() and source_file.read_text(errors="replace") == stamp + if all((target / name).is_file() for name in required) and not marker.exists() and current: return "present" - root = folder.resolve() - installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent) - for sub in ("Redistributables", "Installers")] - installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= 256 * 1024 * 1024), None) if installer is None: - return "game-runtime" + root = folder.resolve() + installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent) + for sub in ("Redistributables", "Installers")] + installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= SDK_SETUP_LIMIT), None) + if installer is None: + return "game-runtime" tool = shutil.which("7z") if not tool: return "no-unpacker" @@ -488,15 +501,67 @@ def rockstar_runtime(folder, exe, compat_data, arch): raise os.replace(stage_path, output) marker.unlink() + if stamp is not None: + source_file.unlink(missing_ok=True) + source_file.write_text(stamp) return "installed" -def fetch_service(service, store, launch_dir, ask_app=None): +def epic_parent_switch(sidecar, env=None): + own = sidecar.get("env") if isinstance(sidecar.get("env"), dict) else {} + if EPIC_PARENT_SWITCH in own: + return str(own[EPIC_PARENT_SWITCH]).replace('"', "") + env = os.environ if env is None else env + try: + game_env = runpy.run_path(str(Path(__file__).resolve().with_name("droiddeck-game-env"))) + try: + config = json.loads((Path(env.get("HOME") or "/root") / ".config/droiddeck/game-environment.json").read_text(encoding="utf-8")) + except FileNotFoundError: + config = {"version": 1} + env = game_env["apply_config"](env, config, game_env["game_id"](env)) + except (OSError, ValueError, KeyError, TypeError, AttributeError): + pass + return env.get(EPIC_PARENT_SWITCH, "") + + +def wants_epic_parent(folder, switch): + if switch in ("0", "1"): + return switch == "1" + try: + return EPIC_PARENT_ON in (folder / LAUNCHER).read_text(errors="replace").splitlines() + except OSError: + return False + + +def epic_rockstar_sdk(folder, sidecar, compat_data, proton): + if not compat_data: + return None + pfx = Path(compat_data) / "pfx" + root = folder.resolve() + exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve() + if not exe.is_relative_to(root): + return None + setups = [(pfx / EPIC_SDK_SETUP, pfx)] + [(base / sub / "Social-Club-Setup.exe", root) for base in (root, exe.parent) + for sub in ("Redistributables", "Installers")] + setup = next((path for path, inside in setups if path.is_file() and path.resolve().is_relative_to(inside.resolve()) + and path.stat().st_size <= SDK_SETUP_LIMIT), None) + if setup is None: + return None + made = "present" if (pfx / "user.reg").is_file() else create_prefix(compat_data, proton) + if made not in ("created", "present"): + return "prefix-" + made + state = rockstar_runtime(folder, exe, compat_data, "x64", setup) + if state in ("present", "installed") and not rockstar_registry(folder, None, compat_data, proton, sdk_arch="x64", launcher=False): + return state + " registry-unavailable" + return state + + +def fetch_service(service, store, launch_dir, ask_app=None, timeout=SERVICE_WAIT): if service.is_file(): return True if not launch_dir: return False - answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=SERVICE_WAIT) + answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=timeout) return isinstance(answer, dict) and bool(answer.get("ok")) and service.is_file() @@ -1650,6 +1715,15 @@ def main(argv): pass log("ubisoft %s: not prepared (%s), starting directly" % (game, e)) if store == "epic": + try: + if launch_dir and not EPIC_PARENT.is_file() and wants_epic_parent(folder, epic_parent_switch(sidecar)): + got = fetch_service(EPIC_PARENT, "epic", launch_dir, timeout=EPIC_SERVICE_WAIT) + log("epic parent stand-in: " + ("staged" if got else "unavailable")) + sdk = epic_rockstar_sdk(folder, sidecar, compat_data, os.environ.get("DD_STORE_PROTON", "")) + except (OSError, ValueError, subprocess.TimeoutExpired) as error: + sdk = "failed (%s)" % type(error).__name__ + if sdk: + log("epic rockstar sdk: " + sdk) handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file() if not handled: drop_stale(folder) diff --git a/tools/linuxfs/preload/binfmt.c b/tools/linuxfs/preload/binfmt.c index 94cecdeb86..484a81094b 100644 --- a/tools/linuxfs/preload/binfmt.c +++ b/tools/linuxfs/preload/binfmt.c @@ -21,6 +21,29 @@ typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t __attribute__((visibility("hidden"))) char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]); +__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size) { + if (!file || !*file) return 0; + if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size; + const char *paths = getenv("PATH"); + if (!paths) paths = "/bin:/usr/bin"; + char candidate[PATH_MAX]; + int found = 0; + for (const char *p = paths;; ) { + const char *end = strchrnul(p, ':'); + int n = end > p ? snprintf(candidate, sizeof candidate, "%.*s/%s", (int)(end - p), p, file) + : snprintf(candidate, sizeof candidate, "%s", file); + struct stat st; + if (n > 0 && n < (int)sizeof candidate && n < (int)size && stat(candidate, &st) == 0 && S_ISREG(st.st_mode)) { + int runs = access(candidate, X_OK) == 0; + if (runs || !found) memcpy(out, candidate, (size_t)n + 1); + found = 1; + if (runs) return 1; + } + if (!*end) return found; + p = end + 1; + } +} + #if defined(__aarch64__) || defined(BINFMT_TEST) static int flag(const char *name) { @@ -32,17 +55,26 @@ static int handing_off(void) { return flag("DD_DESKTOP") || flag("DD_BINFMT"); } +static int appimage(int fd, const unsigned char *head, ssize_t n) { + Elf64_Ehdr eh; + if (n < (ssize_t)sizeof eh || head[EI_CLASS] != ELFCLASS64 || memcmp(head + EI_ABIVERSION, "AI\x02", 3)) return 0; + memcpy(&eh, head, sizeof eh); + char magic[6]; + off_t at = (off_t)eh.e_shoff + (off_t)eh.e_shentsize * eh.e_shnum; + return pread(fd, magic, sizeof magic, at) == (ssize_t)sizeof magic && (!memcmp(magic, "hsqs", 4) || !memcmp(magic, "DWARFS", 6)); +} + static int foreign(const char *path, int error) { if (!path || !strcmp(path, BINFMT_HANDLER)) return 0; int fd = open(path, O_RDONLY | O_CLOEXEC); if (fd < 0) return 0; struct stat st; - unsigned char head[20]; + unsigned char head[sizeof(Elf64_Ehdr)]; ssize_t n = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) ? read(fd, head, sizeof head) : -1; int kind = 0; if (n >= 20 && !memcmp(head, ELFMAG, SELFMAG)) { unsigned machine = head[EI_DATA] == ELFDATA2MSB ? (unsigned)head[18] << 8 | head[19] : head[18] | (unsigned)head[19] << 8; - kind = machine == EM_X86_64 || machine == EM_386 || error == EACCES ? 1 : 0; + kind = machine == EM_X86_64 || machine == EM_386 || appimage(fd, head, n) || error == EACCES ? 1 : 0; } else if (n >= 2 && head[0] == 'M' && head[1] == 'Z') { kind = 2; } else if (n >= 2 && head[0] == '#' && head[1] == '!' && error == EACCES) { @@ -58,21 +90,6 @@ static int wanted(const char *path, int error) { return (error == ENOEXEC || error == ENOENT || error == EACCES) && handing_off() && foreign(path, error); } -static int lookup(const char *file, char *out, size_t size) { - if (!file || !*file) return 0; - if (strchr(file, '/')) return snprintf(out, size, "%s", file) < (int)size; - const char *paths = getenv("PATH"); - if (!paths) paths = "/bin:/usr/bin"; - for (const char *p = paths;; ) { - const char *end = strchrnul(p, ':'); - int n = end > p ? snprintf(out, size, "%.*s/%s", (int)(end - p), p, file) : snprintf(out, size, "%s", file); - struct stat st; - if (n > 0 && n < (int)size && stat(out, &st) == 0 && S_ISREG(st.st_mode)) return 1; - if (!*end) return 0; - p = end + 1; - } -} - static int count(char *const argv[]) { int n = 0; while (argv && argv[n]) n++; @@ -117,12 +134,12 @@ __attribute__((visibility("hidden"))) int dd_binfmt_retry(const char *path, char __attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) { char path[PATH_MAX]; - if (handing_off() && lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp); + if (handing_off() && dd_program_lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp); } __attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) { char path[PATH_MAX]; - if (handing_off() && lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error); + if (handing_off() && dd_program_lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error); errno = error; return -1; } @@ -144,7 +161,7 @@ __attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char int execvpe(const char *file, char *const argv[], char *const envp[]) { char resolved[PATH_MAX]; - const char *path = lookup(file, resolved, sizeof resolved) ? resolved : file; + const char *path = dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file; char *const *adjusted = dd_webhelper_argv(path, argv, envp); static int (*real)(const char *, char *const[], char *const[]); if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execvpe"); @@ -156,7 +173,7 @@ int execvpe(const char *file, char *const argv[], char *const envp[]) { int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { char path[PATH_MAX]; - int found = lookup(file, path, sizeof path); + int found = dd_program_lookup(file, path, sizeof path); char *const *adjusted = dd_webhelper_argv(found ? path : file, argv, envp); static spawn_fn real, spawn; if (!real) real = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawnp"); diff --git a/tools/linuxfs/preload/clockpause.c b/tools/linuxfs/preload/clockpause.c index 8fe0b7ce77..70b4179329 100644 --- a/tools/linuxfs/preload/clockpause.c +++ b/tools/linuxfs/preload/clockpause.c @@ -25,7 +25,6 @@ #define CP_FDS 65536 static const int64_t *cp_shift; -static int cp_state; static size_t cp_cond_byte; static unsigned char cp_cond_mask; static unsigned char cp_fds[CP_FDS / 8]; @@ -94,25 +93,14 @@ static void cp_init(void) { } static int64_t cp_offset(void) { - const int64_t *shift; - int state = __atomic_load_n(&cp_state, __ATOMIC_ACQUIRE); - if (state == 0) { - int expected = 0; - if (__atomic_compare_exchange_n(&cp_state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) { - cp_init(); - __atomic_store_n(&cp_state, 2, __ATOMIC_RELEASE); - } - return 0; - } - if (state != 2) return 0; - shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE); + const int64_t *shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE); if (!shift) return 0; int64_t value = __atomic_load_n(shift, __ATOMIC_RELAXED); return value > 0 ? value : 0; } __attribute__((constructor)) static void cp_start(void) { - cp_offset(); + cp_init(); } static int cp_mono(clockid_t clock) { diff --git a/tools/linuxfs/preload/descriptor.c b/tools/linuxfs/preload/descriptor.c index 686030988c..5f2c19ed22 100644 --- a/tools/linuxfs/preload/descriptor.c +++ b/tools/linuxfs/preload/descriptor.c @@ -31,7 +31,7 @@ static int store_root(char *out, size_t size) { return n > 0 && (size_t)n < size ? n : -1; } -static int store_exists(void) { +static __attribute__((noinline)) int store_exists(void) { char root[PATH_MAX]; if (store_seen) return 1; @@ -223,10 +223,18 @@ int fremovexattr(int fd, const char *name) { return 0; } +static int watched(void) { + int saved = errno, found; + + found = dd_is_wineserver() && store_exists(); + errno = saved; + return found; +} + static int tracked(const char *path, char *out, size_t size) { int saved = errno, found; - found = dd_is_wineserver() && store_exists() && resolved(path, out, size) == 0; + found = resolved(path, out, size) == 0; errno = saved; return found; } @@ -258,22 +266,30 @@ static void follow(const char *from, const char *to) { errno = saved; } -__attribute__((visibility("hidden"))) -int dd_descriptor_unlink(const char *path, int (*real)(const char *)) { +static __attribute__((noinline)) int removed(const char *path, int (*real)(const char *), int folder) { char target[PATH_MAX]; int known = tracked(path, target, sizeof(target)), result = real(path); - if (result == 0 && known) forget(target, 0); + if (result == 0 && known) forget(target, folder); + return result; +} + +static __attribute__((noinline)) int moved(const char *from, const char *to, int (*real)(const char *, const char *)) { + char old[PATH_MAX], new[PATH_MAX]; + int known = tracked(from, old, sizeof(old)), result = real(from, to); + + if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new); return result; } __attribute__((visibility("hidden"))) -int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) { - char target[PATH_MAX]; - int known = tracked(path, target, sizeof(target)), result = real(path); +int dd_descriptor_unlink(const char *path, int (*real)(const char *)) { + return watched() ? removed(path, real, 0) : real(path); +} - if (result == 0 && known) forget(target, 1); - return result; +__attribute__((visibility("hidden"))) +int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) { + return watched() ? removed(path, real, 1) : real(path); } __attribute__((visibility("hidden"))) @@ -283,9 +299,5 @@ int dd_descriptor_remove(const char *path, int (*real)(const char *)) { __attribute__((visibility("hidden"))) int dd_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) { - char old[PATH_MAX], new[PATH_MAX]; - int known = tracked(from, old, sizeof(old)), result = real(from, to); - - if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new); - return result; + return watched() ? moved(from, to, real) : real(from, to); } diff --git a/tools/linuxfs/preload/inputudev.c b/tools/linuxfs/preload/inputudev.c index 823614bfd3..54aac381fa 100644 --- a/tools/linuxfs/preload/inputudev.c +++ b/tools/linuxfs/preload/inputudev.c @@ -582,6 +582,16 @@ const char *udev_device_get_action(void *device) { return real_get(device); } +const char *udev_device_get_driver(void *device) { + static const char *(*real_get)(void *); + struct pad *pad = device_pad(device); + + if (pad != NULL) return NULL; + if (real_get == NULL) real_get = next_symbol("udev_device_get_driver"); + if (real_get == NULL) return NULL; + return real_get(device); +} + dev_t udev_device_get_devnum(void *device) { static dev_t (*real_get)(void *); struct pad *pad = device_pad(device); @@ -686,6 +696,54 @@ void *udev_device_get_sysattr_list_entry(void *device) { return real_get != NULL ? real_get(device) : NULL; } +void *udev_device_get_current_tags_list_entry(void *device) { + static void *(*real_get)(void *); + + if (device_pad(device) != NULL) return NULL; + if (real_get == NULL) real_get = next_symbol("udev_device_get_current_tags_list_entry"); + return real_get != NULL ? real_get(device) : NULL; +} + +int udev_device_has_current_tag(void *device, const char *tag) { + static int (*real_has)(void *, const char *); + + if (device_pad(device) != NULL) return 0; + if (real_has == NULL) real_has = next_symbol("udev_device_has_current_tag"); + return real_has != NULL ? real_has(device, tag) : 0; +} + +void *udev_device_get_devlinks_list_entry(void *device) { + static void *(*real_get)(void *); + + if (device_pad(device) != NULL) return NULL; + if (real_get == NULL) real_get = next_symbol("udev_device_get_devlinks_list_entry"); + return real_get != NULL ? real_get(device) : NULL; +} + +unsigned long long udev_device_get_seqnum(void *device) { + static unsigned long long (*real_get)(void *); + + if (device_pad(device) != NULL) return 0; + if (real_get == NULL) real_get = next_symbol("udev_device_get_seqnum"); + return real_get != NULL ? real_get(device) : 0; +} + +unsigned long long udev_device_get_usec_since_initialized(void *device) { + static unsigned long long (*real_get)(void *); + + if (device_pad(device) != NULL) return 0; + if (real_get == NULL) real_get = next_symbol("udev_device_get_usec_since_initialized"); + return real_get != NULL ? real_get(device) : 0; +} + +int udev_device_set_sysattr_value(void *device, const char *sysattr, const char *value) { + static int (*real_set)(void *, const char *, const char *); + + if (device_pad(device) != NULL) return -EACCES; + if (real_set == NULL) real_set = next_symbol("udev_device_set_sysattr_value"); + return real_set != NULL ? real_set(device, sysattr, value) : -ENOSYS; +} + void *udev_device_new_from_devnum(void *udev, char type, dev_t devnum) { static void *(*real_new)(void *, char, dev_t); struct pad pad; @@ -1011,6 +1069,7 @@ static const struct udev_symbol udev_symbols[] = { {"udev_device_get_subsystem", (void *)udev_device_get_subsystem}, {"udev_device_get_devtype", (void *)udev_device_get_devtype}, {"udev_device_get_action", (void *)udev_device_get_action}, + {"udev_device_get_driver", (void *)udev_device_get_driver}, {"udev_device_get_devnum", (void *)udev_device_get_devnum}, {"udev_device_get_sysattr_value", (void *)udev_device_get_sysattr_value}, {"udev_device_get_property_value", (void *)udev_device_get_property_value}, @@ -1023,6 +1082,12 @@ static const struct udev_symbol udev_symbols[] = { {"udev_device_get_properties_list_entry", (void *)udev_device_get_properties_list_entry}, {"udev_device_get_tags_list_entry", (void *)udev_device_get_tags_list_entry}, {"udev_device_get_sysattr_list_entry", (void *)udev_device_get_sysattr_list_entry}, + {"udev_device_get_current_tags_list_entry", (void *)udev_device_get_current_tags_list_entry}, + {"udev_device_has_current_tag", (void *)udev_device_has_current_tag}, + {"udev_device_get_devlinks_list_entry", (void *)udev_device_get_devlinks_list_entry}, + {"udev_device_get_seqnum", (void *)udev_device_get_seqnum}, + {"udev_device_get_usec_since_initialized", (void *)udev_device_get_usec_since_initialized}, + {"udev_device_set_sysattr_value", (void *)udev_device_set_sysattr_value}, {"udev_enumerate_new", (void *)udev_enumerate_new}, {"udev_enumerate_ref", (void *)udev_enumerate_ref}, {"udev_enumerate_unref", (void *)udev_enumerate_unref}, @@ -1045,7 +1110,15 @@ static void *own_udev_symbol(const char *name) { } static void *dlvsym_any(const char *name) { +#if defined(__aarch64__) + static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.34"}; +#elif defined(__x86_64__) + static const char *versions[] = {"GLIBC_2.2.5", "GLIBC_2.34"}; +#elif defined(__i386__) + static const char *versions[] = {"GLIBC_2.0", "GLIBC_2.34"}; +#else static const char *versions[] = {"GLIBC_2.17", "GLIBC_2.2.5", "GLIBC_2.0", "GLIBC_2.34"}; +#endif size_t i; void *resolved = NULL; @@ -1073,7 +1146,7 @@ static int steam_runtime_path(const char *path) { const char *name = strrchr(path, '/'); size_t i; - if (name == NULL || strcmp(name + 1, "steam") != 0) return 0; + if (name == NULL || (strcmp(name + 1, "steam") != 0 && strcmp(name + 1, "streaming_client") != 0)) return 0; for (i = 0; i < sizeof(runtimes) / sizeof(runtimes[0]); i++) { size_t length = strlen(runtimes[i]); diff --git a/tools/linuxfs/preload/net.c b/tools/linuxfs/preload/net.c index f7c9db9406..388b92da6a 100644 --- a/tools/linuxfs/preload/net.c +++ b/tools/linuxfs/preload/net.c @@ -111,6 +111,9 @@ typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int); static unsigned guarded_port(void); __attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd); +__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len, + int (*real_bind)(int, const struct sockaddr *, socklen_t), + int *rc); __attribute__((visibility("hidden"))) int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc); __attribute__((visibility("hidden"))) int dd_nl_connect(int fd, const struct sockaddr *addr, @@ -121,6 +124,7 @@ int bind(int fd, const struct sockaddr *addr, socklen_t len) { int nl_rc; if (!real) real = (bind_fn)dlsym(RTLD_NEXT, "bind"); if (dd_nl_bind(fd, addr, len, &nl_rc)) return nl_rc; + if (dd_udevmon_bind(fd, addr, len, real, &nl_rc)) return nl_rc; if (dd_udevmon_stand_in(fd)) { if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) { errno = EINVAL; @@ -273,6 +277,7 @@ __attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *f __attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error); __attribute__((visibility("hidden"))) char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]); +__attribute__((visibility("hidden"))) int dd_program_lookup(const char *file, char *out, size_t size); __attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr, char *const argv[], char *const envp[], spawn_fn real); @@ -373,7 +378,8 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi } int execvp(const char *file, char *const argv_in[]) { - char *const *argv = dd_webhelper_argv(file, argv_in, environ); + char resolved[PATH_MAX]; + char *const *argv = dd_webhelper_argv(dd_program_lookup(file, resolved, sizeof resolved) ? resolved : file, argv_in, environ); static int (*real)(const char *, char *const[]); if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp"); maybe_answer_lsof(file, argv); diff --git a/tools/linuxfs/preload/netif.c b/tools/linuxfs/preload/netif.c index 5be0dde22a..38453ba5ab 100644 --- a/tools/linuxfs/preload/netif.c +++ b/tools/linuxfs/preload/netif.c @@ -22,6 +22,7 @@ #include <stdarg.h> #include <stddef.h> #include <stdio.h> +#include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> @@ -520,6 +521,13 @@ static void write_table(FILE *out, const char *table, const struct link *link) { fprintf(out, "%6s: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", link->name); } else if (strcmp(table, "arp") == 0) { fprintf(out, "IP address HW type Flags HW address Mask Device\n"); + } else if (strcmp(table, "tcp") == 0 || strcmp(table, "udp") == 0) { + fprintf(out, " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode%s\n", + table[0] == 'u' ? " ref pointer drops" : ""); + } else if (strcmp(table, "tcp6") == 0 || strcmp(table, "udp6") == 0) { + fprintf(out, " sl local_address remote_address " + "st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode%s\n", + table[0] == 'u' ? " ref pointer drops" : ""); } else { fprintf(out, "1\n"); } @@ -527,7 +535,10 @@ static void write_table(FILE *out, const char *table, const struct link *link) { #define CARRIER_TABLE 5 -static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier" }; +#define SOCKET_TABLES 6 + +static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier", + "tcp", "tcp6", "udp", "udp6" }; static long long net_denied_at[sizeof(net_tables) / sizeof(net_tables[0])]; #define CARRIER_SLOTS 8 @@ -564,8 +575,8 @@ static void remember_denial(int table, const char *path) { static int denied_table(const char *path) { if (strncmp(path, "/proc/net/", 10) == 0) { - for (int i = 0; i < CARRIER_TABLE; i++) { - if (strcmp(path + 10, net_tables[i]) == 0) return i; + for (int i = 0; i < (int) (sizeof(net_tables) / sizeof(net_tables[0])); i++) { + if (i != CARRIER_TABLE && strcmp(path + 10, net_tables[i]) == 0) return i; } return -1; } @@ -576,17 +587,17 @@ static int denied_table(const char *path) { return -1; } -static FILE *synthesize(const char *table) { +static FILE *synthesize(int table) { struct link link; - if (!load_link(&link)) return NULL; - int fd = memfd_create("droiddeck-net", MFD_CLOEXEC); + if (!load_link(&link) && table < SOCKET_TABLES) return NULL; + int fd = memfd_create("droiddeck-net", MFD_CLOEXEC | MFD_ALLOW_SEALING); if (fd < 0) return NULL; FILE *out = fdopen(fd, "w+"); if (out == NULL) { close(fd); return NULL; } - write_table(out, table, &link); + write_table(out, net_tables[table], &link); if (fflush(out) != 0) { fclose(out); return NULL; @@ -610,11 +621,11 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons path = dd_oom_adj_redirect(path, mode && (mode[0] == 'w' || mode[0] == 'a' || strchr(mode, '+'))); int table = path && mode && mode[0] == 'r' ? denied_table(path) : -1; FILE *f; - if (table >= 0 && denied_recently(table, path) && (f = synthesize(net_tables[table])) != NULL) return f; + if (table >= 0 && denied_recently(table, path) && (f = synthesize(table)) != NULL) return f; f = real(path, mode); if (f || table < 0) return f; int saved = errno; - if ((f = synthesize(net_tables[table])) != NULL) { + if ((f = synthesize(table)) != NULL) { if (saved == EACCES) remember_denial(table, path); return f; } @@ -622,6 +633,33 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons return NULL; } +int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden"))); + +int dd_net_open(const char *path, int flags, int fd) { + if (fd >= 0 || path == NULL || (flags & O_ACCMODE) != O_RDONLY || (flags & O_DIRECTORY)) return fd; + int table = denied_table(path); + if (table < 0) return fd; + int saved = errno; + FILE *f = synthesize(table); + if (f == NULL) { + errno = saved; + return fd; + } + char self[32]; + snprintf(self, sizeof(self), "/proc/self/fd/%d", fileno(f)); + int copy = open(self, O_RDONLY | (flags & O_CLOEXEC)); + if (copy < 0 && fcntl(fileno(f), F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL) == 0) { + copy = fcntl(fileno(f), flags & O_CLOEXEC ? F_DUPFD_CLOEXEC : F_DUPFD, 0); + } + fclose(f); + if (copy < 0) { + errno = saved; + return fd; + } + if (saved == EACCES) remember_denial(table, path); + return copy; +} + FILE *fopen(const char *path, const char *mode) { static fopen_fn real; if (real == NULL) real = (fopen_fn) dlsym(RTLD_NEXT, "fopen"); @@ -664,6 +702,7 @@ struct nl_socket { unsigned references; int type; int cap_ack; + uint64_t groups; struct nl_socket *next; }; @@ -685,13 +724,14 @@ struct nl_fd_page { struct nl_metadata { uint64_t nonce; + uint64_t groups; uint32_t port; uint32_t type; uint32_t cap_ack; char magic[12]; }; -_Static_assert(sizeof(struct nl_metadata) == 32, "netlink socket metadata ABI"); +_Static_assert(sizeof(struct nl_metadata) == 40, "netlink socket metadata ABI"); struct nl_packet { struct nl_packet *next; @@ -705,9 +745,9 @@ struct nl_reply { int overflow; }; -static const char nl_client_magic[12] = "dd-nl-c-v1"; -static const char nl_peer_magic[12] = "dd-nl-p-v1"; -static const char nl_reservation_magic[12] = "dd-nl-r-v1"; +static const char nl_client_magic[12] = "dd-nl-c-v2"; +static const char nl_peer_magic[12] = "dd-nl-p-v2"; +static const char nl_reservation_magic[12] = "dd-nl-r-v2"; static struct nl_socket *nl_sockets; static struct nl_fd *nl_fds; static struct nl_fd_page *nl_fd_pages[NL_FD_BUCKETS]; @@ -910,13 +950,13 @@ static int nl_save_packets(int fd, struct nl_packet **packets) { } } -static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int capped) { +static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int capped, uint64_t groups) { static int (*real_socket)(int, int, int); static int (*real_close)(int); if (real_socket == NULL) real_socket = (int (*)(int, int, int)) dlsym(RTLD_NEXT, "socket"); if (real_close == NULL) real_close = (int (*)(int)) dlsym(RTLD_NEXT, "close"); struct sockaddr_un client_addr, peer_addr; - struct nl_metadata client, peer = { .port = port, .type = socket->type, .cap_ack = capped }; + struct nl_metadata client, peer = { .groups = groups, .port = port, .type = socket->type, .cap_ack = capped }; if (!nl_address(fd, 0, &client_addr, &client, nl_client_magic)) { errno = EINVAL; return -1; @@ -955,6 +995,7 @@ static int nl_replace_peer(int fd, struct nl_socket *socket, unsigned port, int socket->peer_inode = status.st_ino; socket->port = port; socket->cap_ack = capped; + socket->groups = groups; errno = saved; return replayed; failed: { @@ -1025,7 +1066,7 @@ static struct nl_fd *nl_restore(int fd) { socket->device = status.st_dev; socket->inode = status.st_ino; socket->type = peer.type; - if (nl_replace_peer(fd, socket, peer.port, peer.cap_ack) != 0) { + if (nl_replace_peer(fd, socket, peer.port, peer.cap_ack, peer.groups) != 0) { free(socket); free(entry); return NULL; @@ -1159,7 +1200,7 @@ static int nl_peer_of(int fd) { if (nl_address(fd, 1, &addr, &metadata, nl_peer_magic)) { if ((metadata.nonce == socket->peer_inode && nl_identity(socket->peer, socket->device, socket->peer_inode)) - || nl_replace_peer(fd, socket, metadata.port, metadata.cap_ack) == 0) { + || nl_replace_peer(fd, socket, metadata.port, metadata.cap_ack, metadata.groups) == 0) { if (socket->port != 0 && (socket->reservation < 0 || !nl_identity(socket->reservation, socket->device, socket->reservation_inode))) nl_reserve_port(socket, socket->port); @@ -1317,7 +1358,7 @@ static int nl_bind_port(int fd, unsigned requested, int automatic) { } if (other == NULL) { if (nl_reserve_port(socket, port) == 0) { - result = nl_replace_peer(fd, socket, port, socket->cap_ack); + result = nl_replace_peer(fd, socket, port, socket->cap_ack, socket->groups); if (result != 0) nl_close_reservation(socket); break; } @@ -1342,6 +1383,23 @@ static int nl_autobind(int fd) { return nl_bind_port(fd, 0, 1); } +static int nl_set_groups(int fd, uint64_t keep, uint64_t add) { + int result = 0; + pthread_mutex_lock(&nl_sockets_lock); + struct nl_fd *entry = nl_find(fd); + if (entry) { + struct nl_socket *socket = entry->socket; + struct sockaddr_un addr; + struct nl_metadata metadata; + uint64_t current = nl_address(fd, 1, &addr, &metadata, nl_peer_magic) ? metadata.groups : socket->groups; + uint64_t groups = (current & keep) | add; + if (groups != current || groups != socket->groups) + result = nl_replace_peer(fd, socket, socket->port, socket->cap_ack, groups); + } + pthread_mutex_unlock(&nl_sockets_lock); + return result; +} + int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { const struct sockaddr_nl *nl; if (addr && len >= sizeof(sa_family_t) && addr->sa_family == AF_NETLINK) nl_discover(fd); @@ -1352,15 +1410,39 @@ int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { return 1; } nl = (const struct sockaddr_nl *) addr; - if (nl->nl_groups != 0) { - errno = EACCES; - *rc = -1; - return 1; - } *rc = nl_bind_port(fd, nl->nl_pid, 0); + if (*rc == 0) *rc = nl_set_groups(fd, ~(uint64_t) UINT32_MAX, nl->nl_groups); return 1; } +static unsigned nl_groups_of(int fd) { + struct sockaddr_un addr; + struct nl_metadata metadata; + if (nl_address(fd, 1, &addr, &metadata, nl_peer_magic)) return (unsigned) metadata.groups; + unsigned groups = 0; + pthread_mutex_lock(&nl_sockets_lock); + struct nl_fd *entry = nl_find(fd); + if (entry) groups = (unsigned) entry->socket->groups; + pthread_mutex_unlock(&nl_sockets_lock); + return groups; +} + +static int nl_membership(int fd, int option, const void *value, socklen_t len) { + unsigned group; + if (value == NULL || len < sizeof(group)) { + errno = value == NULL ? EFAULT : EINVAL; + return -1; + } + memcpy(&group, value, sizeof(group)); + if (group == 0 || group > RTNLGRP_MAX) { + errno = EINVAL; + return -1; + } + if (group > 64) return 0; + uint64_t bit = (uint64_t) 1 << (group - 1); + return nl_set_groups(fd, ~bit, option == NETLINK_ADD_MEMBERSHIP ? bit : 0); +} + int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { struct sockaddr_nl nl; socklen_t size; @@ -1373,6 +1455,7 @@ int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { memset(&nl, 0, sizeof(nl)); nl.nl_family = AF_NETLINK; nl.nl_pid = nl_port_of(fd); + nl.nl_groups = nl_groups_of(fd); size = *len < sizeof(nl) ? *len : (socklen_t) sizeof(nl); memcpy(addr, &nl, size); *len = sizeof(nl); @@ -1517,9 +1600,10 @@ int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t *rc = real(peer, level, option, value, len); return 1; } - if (option != NETLINK_CAP_ACK && option != NETLINK_EXT_ACK) { - errno = option == NETLINK_ADD_MEMBERSHIP || option == NETLINK_DROP_MEMBERSHIP - ? EACCES : ENOPROTOOPT; + if (option == NETLINK_ADD_MEMBERSHIP || option == NETLINK_DROP_MEMBERSHIP) { + *rc = nl_membership(fd, option, value, len); + } else if (option != NETLINK_CAP_ACK && option != NETLINK_EXT_ACK) { + errno = ENOPROTOOPT; *rc = -1; } else if (value == NULL || len < sizeof(int)) { errno = value == NULL ? EFAULT : EINVAL; @@ -1530,7 +1614,7 @@ int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t memcpy(&enabled, value, sizeof(enabled)); pthread_mutex_lock(&nl_sockets_lock); struct nl_fd *entry = nl_find(fd); - if (entry && nl_replace_peer(fd, entry->socket, entry->socket->port, enabled != 0) != 0) { + if (entry && nl_replace_peer(fd, entry->socket, entry->socket->port, enabled != 0, entry->socket->groups) != 0) { pthread_mutex_unlock(&nl_sockets_lock); *rc = -1; return 1; diff --git a/tools/linuxfs/preload/opens.c b/tools/linuxfs/preload/opens.c index c9df092b40..5ab362e93f 100644 --- a/tools/linuxfs/preload/opens.c +++ b/tools/linuxfs/preload/opens.c @@ -17,6 +17,7 @@ int dd_ntsync_open(const char *path, int flags) __attribute__((visibility("hidde const char *dd_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden"))); int dd_venc_open(const char *path, int flags) __attribute__((visibility("hidden"))); int dd_vdec_open(const char *path, int flags) __attribute__((visibility("hidden"))); +int dd_net_open(const char *path, int flags, int fd) __attribute__((visibility("hidden"))); int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden"))); @@ -62,7 +63,7 @@ static int open_from(const char *path, int flags, mode_t mode, const void *calle fd = dd_dircache_create(AT_FDCWD, path, flags, mode, via_open); if (retry_without_noatime(fd, flags)) fd = real_open(path, flags & ~O_NOATIME, mode); if (fd < 0 && dd_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode); - return fd; + return dd_net_open(path, flags, fd); } static int openat_from(int dirfd, const char *path, int flags, mode_t mode, const void *caller) { @@ -85,7 +86,7 @@ static int openat_from(int dirfd, const char *path, int flags, mode_t mode, cons fd = dd_dircache_create(dirfd, path, flags, mode, via_openat); if (retry_without_noatime(fd, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode); if (fd < 0 && dd_writable_retry(dirfd, path, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode); - return fd; + return dd_net_open(path, flags, fd); } int open(const char *path, int flags, ...) { diff --git a/tools/linuxfs/preload/tracer.c b/tools/linuxfs/preload/tracer.c index ec8dd003f9..4b12a1d6a7 100644 --- a/tools/linuxfs/preload/tracer.c +++ b/tools/linuxfs/preload/tracer.c @@ -72,15 +72,12 @@ static int read_only_copy(const char *data, size_t len, int flags) { return ro; } -__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) { +static __attribute__((noinline)) int status_copy(const char *path, int flags, long pid) { char text[STATUS_MAX]; size_t len = 0; int saved = errno; int out = -1; - long pid; - if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller)) - return -1; // through the next open(): the native userland's hook gives the app's ids as root's there static int (*next_open)(const char *, int, ...) = NULL; if (!next_open) next_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open"); @@ -116,3 +113,10 @@ done: errno = saved; return out; } + +__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) { + long pid; + if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller)) + return -1; + return status_copy(path, flags, pid); +} diff --git a/tools/linuxfs/preload/udevmon.c b/tools/linuxfs/preload/udevmon.c index d3af29ef43..43b426ce30 100644 --- a/tools/linuxfs/preload/udevmon.c +++ b/tools/linuxfs/preload/udevmon.c @@ -14,6 +14,7 @@ #include <sys/stat.h> #include <endian.h> #include <stdio.h> +#include <stdlib.h> #include <unistd.h> struct stand_in { @@ -40,6 +41,19 @@ static ino_t socket_inode(int fd) { return fstat(fd, &st) == 0 ? st.st_ino : 0; } +static struct stand_in *available_stand_in(void) { + for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) { + struct stand_in *entry = &stand_ins[i]; + if (entry->fd == -1) return entry; + if (entry->inode != socket_inode(entry->fd)) { + close(entry->peer); + entry->fd = -1; + return entry; + } + } + return NULL; +} + static int is_stand_in(int fd) { int found = 0; if (fd < 0) @@ -86,14 +100,11 @@ static int make_stand_in(int type) { } fcntl(sv[1], F_SETFD, FD_CLOEXEC); pthread_mutex_lock(&lock); - for (size_t i = 0; i < sizeof(stand_ins) / sizeof(stand_ins[0]); i++) { - if (stand_ins[i].fd == -1) { - stand_ins[i].fd = sv[0]; - stand_ins[i].peer = sv[1]; - stand_ins[i].inode = socket_inode(sv[0]); - pthread_mutex_unlock(&lock); - return sv[0]; - } + struct stand_in *entry = available_stand_in(); + if (entry != NULL) { + *entry = (struct stand_in){.fd = sv[0], .peer = sv[1], .inode = socket_inode(sv[0])}; + pthread_mutex_unlock(&lock); + return sv[0]; } pthread_mutex_unlock(&lock); close(sv[0]); @@ -146,6 +157,58 @@ __attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd) { return is_stand_in(fd); } +static int subscribed(int fd) { +#ifdef UDEVMON_TEST + if (getenv("DD_UDEVMON_REFUSE") != NULL) return 0; +#endif + struct sockaddr_nl nl; + socklen_t len = sizeof(nl); + memset(&nl, 0, sizeof(nl)); + return getsockname(fd, (struct sockaddr *)&nl, &len) == 0 && nl.nl_groups != 0; +} + +/* Android lets an app open a uevent socket but not join its multicast groups, and libudev joins none + when no udev daemon runs, so a monitor bound there hears nothing. Such a socket is replaced, under + the same descriptor, by a stand-in. */ +__attribute__((visibility("hidden"))) int dd_udevmon_bind(int fd, const struct sockaddr *addr, socklen_t len, + int (*real_bind)(int, const struct sockaddr *, socklen_t), + int *rc) { + int protocol = -1; + socklen_t protocol_len = sizeof(protocol); + if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) return 0; + if (is_stand_in(fd) || is_wine_process()) return 0; + if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &protocol_len) != 0 || protocol != NETLINK_KOBJECT_UEVENT) + return 0; + *rc = real_bind(fd, addr, len); + int refused = errno; + if (subscribed(fd)) { + errno = refused; + return 1; + } + int status = fcntl(fd, F_GETFL); + int descriptor = fcntl(fd, F_GETFD); + int sv[2]; + if (status < 0 || descriptor < 0 || socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, sv) != 0) { + errno = refused; + return 1; + } + pthread_mutex_lock(&lock); + struct stand_in *entry = available_stand_in(); + if (entry == NULL || dup3(sv[0], fd, (descriptor & FD_CLOEXEC) ? O_CLOEXEC : 0) < 0) { + pthread_mutex_unlock(&lock); + close(sv[0]); + close(sv[1]); + errno = refused; + return 1; + } + close(sv[0]); + if (status & O_NONBLOCK) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); + *entry = (struct stand_in){.fd = fd, .peer = sv[1], .inode = socket_inode(fd)}; + pthread_mutex_unlock(&lock); + *rc = 0; + return 1; +} + int getsockname(int fd, struct sockaddr *addr, socklen_t *len) { static int (*real_getsockname)(int, struct sockaddr *, socklen_t *); struct sockaddr_nl nl; diff --git a/tools/linuxfs/preload/vdec.c b/tools/linuxfs/preload/vdec.c index 7d3761e290..3bd38f3bc9 100644 --- a/tools/linuxfs/preload/vdec.c +++ b/tools/linuxfs/preload/vdec.c @@ -29,6 +29,8 @@ #define VDEC_BITSTREAM_SIZE (4u << 20) #define VDEC_PADDING 64 #define VDEC_DUMB 64 +#define VDEC_CAP_MIN_WIDTH 4096u +#define VDEC_CAP_MIN_HEIGHT 2304u struct vd_dma_heap_alloc { uint64_t len; @@ -135,6 +137,8 @@ struct vdec { uint32_t n_cap_done; int out_on, cap_on; int sock, hw, hw_failed; + int resizing; + uint32_t stream_w, stream_h; int64_t pts; void *ctx, *packet, *frame; uint8_t *packet_data; @@ -318,7 +322,8 @@ static int vd_open_hardware(struct vdec *v) { if (sock < 0) return -1; struct vdec_config c = { .type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264, - .width = v->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height, + .width = v->stream_w ? v->stream_w : v->width ? v->width : v->cap_width, + .height = v->stream_h ? v->stream_h : v->height ? v->height : v->cap_height, .stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE, }; struct vdec_result r; @@ -563,8 +568,12 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) { t.fourcc = p->pixelformat; t.width = p->width; t.height = p->height; + t.stream_w = p->width; + t.stream_h = p->height; } else { uint32_t w = p->width > t.width ? p->width : t.width, h = p->height > t.height ? p->height : t.height; + if (w < VDEC_CAP_MIN_WIDTH) w = VDEC_CAP_MIN_WIDTH; + if (h < VDEC_CAP_MIN_HEIGHT) h = VDEC_CAP_MIN_HEIGHT; if (w < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL; t.cap_width = (w + 15) & ~15u; t.cap_height = (h + 15) & ~15u; @@ -574,6 +583,7 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) { if (apply) { if (t.fourcc != v->fourcc || (t.hw && (t.bpl != v->bpl || t.cap_height != v->cap_height))) vd_close_decoder(&t); *v = t; + if (v->cap_width >= v->width && v->cap_height >= v->height) v->resizing = 0; } vd_fill_format(&t, f); return 0; @@ -615,13 +625,184 @@ static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) { return 0; } +struct vd_bits { + const uint8_t *data; + size_t size, pos; +}; + +static uint32_t vd_get_bits(struct vd_bits *b, unsigned count) { + uint32_t value = 0; + while (count--) { + size_t byte = b->pos >> 3; + value = value << 1 | (byte < b->size ? (b->data[byte] >> (7 - (b->pos & 7))) & 1u : 0u); + b->pos++; + } + return value; +} + +static uint32_t vd_get_ue(struct vd_bits *b) { + unsigned zeros = 0; + while (zeros < 32 && vd_get_bits(b, 1) == 0 && (b->pos >> 3) < b->size) zeros++; + if (zeros >= 32) return 0; + return ((1u << zeros) - 1) + (zeros ? vd_get_bits(b, zeros) : 0); +} + +static int32_t vd_get_se(struct vd_bits *b) { + uint32_t k = vd_get_ue(b); + return (k & 1) ? (int32_t)((k + 1) / 2) : -(int32_t)(k / 2); +} + +static int vd_skip_scaling_list(struct vd_bits *b, unsigned size) { + int32_t last = 8, next = 8; + for (unsigned i = 0; i < size; i++) { + if (next != 0) { + int32_t delta = vd_get_se(b); + if (delta < -128 || delta > 127) return -1; + next = (last + delta + 256) % 256; + } + last = next == 0 ? last : next; + } + return 0; +} + +/* The coded size an H.264 SPS announces, rounded up to whole macroblocks, as a V4L2 decoder reports it. */ +static int vd_parse_sps_h264(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) { + uint8_t buf[512]; + size_t n = 0; + for (size_t i = 0; i < size && n < sizeof buf; i++) { + if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue; + buf[n++] = rbsp[i]; + } + struct vd_bits b = { buf, n, 0 }; + uint32_t profile = vd_get_bits(&b, 8); + vd_get_bits(&b, 16); + vd_get_ue(&b); + uint32_t chroma = 1; + if (profile == 100 || profile == 110 || profile == 122 || profile == 244 || profile == 44 || profile == 83 || + profile == 86 || profile == 118 || profile == 128 || profile == 138 || profile == 139 || profile == 134 || profile == 135) { + chroma = vd_get_ue(&b); + if (chroma == 3) vd_get_bits(&b, 1); + vd_get_ue(&b); + vd_get_ue(&b); + vd_get_bits(&b, 1); + if (vd_get_bits(&b, 1)) { + for (unsigned i = 0; i < (chroma != 3 ? 8u : 12u); i++) + if (vd_get_bits(&b, 1) && vd_skip_scaling_list(&b, i < 6 ? 16 : 64) != 0) return -1; + } + } + vd_get_ue(&b); + uint32_t poc = vd_get_ue(&b); + if (poc == 0) { + vd_get_ue(&b); + } else if (poc == 1) { + vd_get_bits(&b, 1); + vd_get_se(&b); + vd_get_se(&b); + uint32_t cycle = vd_get_ue(&b); + for (uint32_t i = 0; i < cycle && i < 256; i++) vd_get_se(&b); + } + vd_get_ue(&b); + vd_get_bits(&b, 1); + uint32_t mbs_wide = vd_get_ue(&b) + 1, map_units_high = vd_get_ue(&b) + 1; + if (b.pos > b.size * 8 || mbs_wide > 1024 || map_units_high > 1024) return -1; + uint32_t frame_mbs_only = vd_get_bits(&b, 1); + if (b.pos > b.size * 8) return -1; + *width = mbs_wide * 16; + *height = map_units_high * 16 * (2 - frame_mbs_only); + return 0; +} + +/* Finds the first SPS in an Annex B access unit; returns its size in the stream through the out parameters. */ +static int vd_stream_size_h264(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) { + for (size_t i = 0; i + 4 < size; i++) { + if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || (data[i + 3] & 0x1f) != 7) continue; + size_t start = i + 4, end = start; + while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++; + if (end + 2 >= size) end = size; + return vd_parse_sps_h264(data + start, end - start, width, height); + } + return -1; +} + +/* The same for an H.265 SPS: the luma size in samples, rounded up to 16 as the client asks for it. */ +static int vd_parse_sps_h265(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) { + uint8_t buf[512]; + size_t n = 0; + for (size_t i = 0; i < size && n < sizeof buf; i++) { + if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue; + buf[n++] = rbsp[i]; + } + struct vd_bits b = { buf, n, 0 }; + vd_get_bits(&b, 4); + uint32_t sub_layers = vd_get_bits(&b, 3); + vd_get_bits(&b, 1); + for (unsigned i = 0; i < 88; i += 8) vd_get_bits(&b, 8); + vd_get_bits(&b, 8); + uint32_t profile_present = 0, level_present = 0; + for (uint32_t i = 0; i < sub_layers && i < 8; i++) { + profile_present |= vd_get_bits(&b, 1) << i; + level_present |= vd_get_bits(&b, 1) << i; + } + if (sub_layers > 0) for (uint32_t i = sub_layers; i < 8; i++) vd_get_bits(&b, 2); + for (uint32_t i = 0; i < sub_layers && i < 8; i++) { + if (profile_present >> i & 1) for (unsigned k = 0; k < 88; k += 8) vd_get_bits(&b, 8); + if (level_present >> i & 1) vd_get_bits(&b, 8); + } + vd_get_ue(&b); + if (vd_get_ue(&b) == 3) vd_get_bits(&b, 1); + uint32_t w = vd_get_ue(&b), h = vd_get_ue(&b); + if (b.pos > b.size * 8 || w < 16 || h < 16 || w > 16384 || h > 16384) return -1; + *width = (w + 15) & ~15u; + *height = (h + 15) & ~15u; + return 0; +} + +static int vd_stream_size_h265(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) { + for (size_t i = 0; i + 5 < size; i++) { + if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || ((data[i + 3] >> 1) & 0x3f) != 33) continue; + size_t start = i + 5, end = start; + while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++; + if (end + 2 >= size) end = size; + return vd_parse_sps_h265(data + start, end - start, width, height); + } + return -1; +} + +/* + * A stream can change its picture size without telling the client: the host switches games or the window + * becomes fullscreen. A V4L2 decoder reports the new size through the format of its bitstream queue, which + * the client polls; the capture buffers it already allocated stay at the old size until it reconfigures. + */ +static int vd_follow_stream_size(struct vdec *v, const uint8_t *data, size_t size) { + uint32_t width, height; + int found = v->fourcc == V4L2_PIX_FMT_HEVC ? vd_stream_size_h265(data, size, &width, &height) + : vd_stream_size_h264(data, size, &width, &height); + if (found != 0) return 0; + uint32_t known_w = v->stream_w ? v->stream_w : v->width, known_h = v->stream_h ? v->stream_h : v->height; + if (width == known_w && height == known_h) return 0; + vd_log("the stream is now %ux%u, was %ux%u", width, height, known_w, known_h); + if (width <= v->cap_width && height <= v->cap_height) { + /* The client's capture buffers already hold the new size, so only the app decoder is reopened for it. */ + v->stream_w = width; + v->stream_h = height; + if (v->hw) vd_close_decoder(v); + return 1; + } + v->width = v->stream_w = width; + v->height = v->stream_h = height; + v->resizing = 1; + v->n_cap_done = 0; + return 1; +} + static int vd_qbuf(struct vdec *v, struct v4l2_buffer *b) { if (b->m.planes == NULL || b->length < 1) return -EINVAL; if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) { if (b->index >= v->out_count || v->n_out_done >= VDEC_BUFFERS) return -EINVAL; uint32_t bytes = b->m.planes[0].bytesused; if (bytes > VDEC_BITSTREAM_SIZE) bytes = VDEC_BITSTREAM_SIZE; - if (v->out_on && bytes) vd_decode(v, b->index, bytes, b->timestamp); + if (v->out_on && v->bitstream && bytes) vd_follow_stream_size(v, v->bitstream + (size_t)b->index * VDEC_BITSTREAM_SIZE, bytes); + if (v->out_on && bytes && !v->resizing) vd_decode(v, b->index, bytes, b->timestamp); v->out_done[v->n_out_done++] = b->index; } else if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) { if (b->index >= v->cap_count || v->cap_size == 0) return -EINVAL; @@ -652,9 +833,15 @@ static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) { return 0; } if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL; - if (v->n_cap_done == 0) return -EAGAIN; - struct vd_done d = v->cap_done[0]; - memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d); + struct vd_done d; + for (;;) { + if (v->n_cap_done == 0) return -EAGAIN; + d = v->cap_done[0]; + memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d); + struct stat st; + struct vd_capture *c = &v->cap[d.index]; + if (c->map && c->fd >= 0 && fstat(c->fd, &st) == 0 && st.st_ino == c->ino) break; + } b->index = d.index; b->memory = V4L2_MEMORY_DMABUF; b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY; diff --git a/tools/linuxfs/preload/webhelper.c b/tools/linuxfs/preload/webhelper.c index 81aba8e8a5..bbccd890b1 100644 --- a/tools/linuxfs/preload/webhelper.c +++ b/tools/linuxfs/preload/webhelper.c @@ -26,40 +26,83 @@ static char *join_features(const char *have, const char *add) { return strcat(out, add); } -static int electron_node_mode(char *const envp[]) { - static const char variable[] = "ELECTRON_RUN_AS_NODE="; +static const char *env_value(char *const envp[], const char *variable) { + size_t n = strlen(variable); for (int i = 0; envp && envp[i]; i++) - if (!strncmp(envp[i], variable, sizeof variable - 1)) - return envp[i][sizeof variable - 1] != 0; - return 0; + if (!strncmp(envp[i], variable, n) && envp[i][n] == '=') return envp[i] + n + 1; + return NULL; } -static char *const *chromium_argv(const char *path, char *const argv[]) { - const char *slash = path ? strrchr(path, '/') : NULL; - if (!slash || !argv || !argv[0]) return argv; - int argc = 0; - for (; argv[argc]; argc++) - if (argc && (!strncmp(argv[argc], "--type=", 7) || !strcmp(argv[argc], "--no-sandbox"))) return argv; - size_t dir = (size_t)(slash - path) + 1; - char *sandbox = malloc(dir + sizeof "chrome-sandbox"); - if (!sandbox) return argv; - memcpy(sandbox, path, dir); - strcpy(sandbox + dir, "chrome-sandbox"); - int chromium = access(sandbox, F_OK) == 0; - free(sandbox); - if (!chromium) return argv; - char **out = calloc((size_t)argc + 2, sizeof *out); +static int electron_node_mode(char *const envp[]) { + const char *mode = env_value(envp, "ELECTRON_RUN_AS_NODE"); + return mode && *mode; +} + +static int beside_chrome_sandbox(const char *path) { + char *real = realpath(path, NULL); + if (!real) return 0; + int found = 0; + for (int up = 0; up < 2 && !found; up++) { + char *slash = strrchr(real, '/'); + if (!slash) break; + *slash = 0; + size_t dir = strlen(real); + char *sandbox = malloc(dir + sizeof "/chrome-sandbox"); + if (!sandbox) break; + memcpy(sandbox, real, dir); + strcpy(sandbox + dir, "/chrome-sandbox"); + found = access(sandbox, F_OK) == 0; + free(sandbox); + } + free(real); + return found; +} + +static char *folder_of(const char *path) { + char *real = realpath(path, NULL); + char *slash = real ? strrchr(real, '/') : NULL; + if (slash) *slash = 0; + return real; +} + +static int started_by_its_own_app(const char *path) { + char self[4096]; + ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1); + if (n <= 0) return 0; + self[n] = 0; + char *mine = folder_of(self), *theirs = folder_of(path); + int same = mine && theirs && !strcmp(mine, theirs) && beside_chrome_sandbox(self); + free(mine); + free(theirs); + return same; +} + +static char *const *chromium_argv(const char *path, char *const argv[], char *const envp[]) { + if (!path || !argv || !argv[0]) return argv; + int argc = 0, sandbox = 1, ozone = 0; + for (; argv[argc]; argc++) { + if (!argc) continue; + if (!strncmp(argv[argc], "--type=", 7)) return argv; + if (!strcmp(argv[argc], "--no-sandbox")) sandbox = 0; + if (!strncmp(argv[argc], "--ozone-platform=", 17)) ozone = 1; + } + const char *display = env_value(envp, "DISPLAY"); + int x11 = !ozone && display && *display; + if ((!sandbox && !x11) || !beside_chrome_sandbox(path) || started_by_its_own_app(path)) return argv; + char **out = calloc((size_t)argc + 3, sizeof *out); if (!out) return argv; - out[0] = argv[0]; - out[1] = (char *)"--no-sandbox"; - for (int i = 1; i < argc; i++) out[i + 1] = argv[i]; + int n = 0; + out[n++] = argv[0]; + if (sandbox) out[n++] = (char *)"--no-sandbox"; + if (x11) out[n++] = (char *)"--ozone-platform=x11"; + for (int i = 1; i < argc; i++) out[n++] = argv[i]; return out; } __attribute__((visibility("hidden"))) char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]) { if (electron_node_mode(envp)) return argv; - if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv); + if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv, envp); const char *spec = getenv("DD_WEBHELPER_ARGS"); if (!spec || !*spec) spec = WEBHELPER_DEFAULT; if (!strcmp(spec, "stock")) return argv; diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index 551a6e148c..ad13d8258b 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -1,8 +1,9 @@ #define _GNU_SOURCE -#include <dlfcn.h> +#pragma GCC optimize("no-stack-protector", "no-tree-loop-distribute-patterns") #include <errno.h> #include <fcntl.h> #include <pthread.h> +#include <sched.h> #include <signal.h> #include <stdint.h> #include <string.h> @@ -10,6 +11,9 @@ #include <sys/prctl.h> #include <sys/syscall.h> #include <sys/uio.h> +#if defined(__i386__) +#include <asm/ldt.h> +#endif #include <unistd.h> @@ -31,13 +35,156 @@ #define ZR_INLINE_CHUNKS 512UL #define ZR_FAILED (~0UL) #define ZR_FUTEX_WAIT 0 -#define ZR_FUTEX_WAKE 1 +#define ZR_STACK (128UL << 10) +#define ZR_THREAD (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | \ + CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID) +#define ZR_TEXT(x) #x +#define ZR_NR(x) ZR_TEXT(x) +#define ZR_CALL(n, a, b, c, d, e, f, ...) \ + zr_call((long)(n), (long)(a), (long)(b), (long)(c), (long)(d), (long)(e), (long)(f)) +#define zr_sys(...) ZR_CALL(__VA_ARGS__, 0, 0, 0, 0, 0, 0, 0) + +#if defined(__aarch64__) +#define ZR_MMAP SYS_mmap +__asm__(".pushsection .text\n" + ".p2align 2\n" + ".hidden zr_call\n" + ".type zr_call, %function\n" + "zr_call:\n" + " mov x8, x0\n" + " mov x0, x1\n" + " mov x1, x2\n" + " mov x2, x3\n" + " mov x3, x4\n" + " mov x4, x5\n" + " mov x5, x6\n" + " svc #0\n" + " ret\n" + ".size zr_call, . - zr_call\n" + ".hidden zr_clone\n" + ".type zr_clone, %function\n" + "zr_clone:\n" + " mov x5, x2\n" + " mov x2, x3\n" + " mov x3, x4\n" + " mov x4, x5\n" + " mov x8, #" ZR_NR(SYS_clone) "\n" + " svc #0\n" + " cbnz x0, 1f\n" + " mov x29, xzr\n" + " mov x30, xzr\n" + " bl zr_thread\n" + " mov x0, xzr\n" + " mov x8, #" ZR_NR(SYS_exit) "\n" + " svc #0\n" + " brk #0\n" + "1:\n" + " ret\n" + ".size zr_clone, . - zr_clone\n" + ".popsection\n"); +#elif defined(__x86_64__) +#define ZR_MMAP SYS_mmap +__asm__(".pushsection .text\n" + ".p2align 4\n" + ".hidden zr_call\n" + ".type zr_call, @function\n" + "zr_call:\n" + " mov %rdi, %rax\n" + " mov %rsi, %rdi\n" + " mov %rdx, %rsi\n" + " mov %rcx, %rdx\n" + " mov %r8, %r10\n" + " mov %r9, %r8\n" + " mov 8(%rsp), %r9\n" + " syscall\n" + " ret\n" + ".size zr_call, . - zr_call\n" + ".hidden zr_clone\n" + ".type zr_clone, @function\n" + "zr_clone:\n" + " mov %rdx, %r10\n" + " mov %rcx, %rdx\n" + " mov $" ZR_NR(SYS_clone) ", %eax\n" + " syscall\n" + " test %rax, %rax\n" + " jnz 1f\n" + " xor %ebp, %ebp\n" + " call zr_thread\n" + " xor %edi, %edi\n" + " mov $" ZR_NR(SYS_exit) ", %eax\n" + " syscall\n" + " hlt\n" + "1:\n" + " ret\n" + ".size zr_clone, . - zr_clone\n" + ".popsection\n"); +#elif defined(__i386__) +#define ZR_MMAP SYS_mmap2 +__asm__(".pushsection .text\n" + ".p2align 4\n" + ".hidden zr_call\n" + ".type zr_call, @function\n" + "zr_call:\n" + " push %ebp\n" + " push %edi\n" + " push %esi\n" + " push %ebx\n" + " mov 20(%esp), %eax\n" + " mov 24(%esp), %ebx\n" + " mov 28(%esp), %ecx\n" + " mov 32(%esp), %edx\n" + " mov 36(%esp), %esi\n" + " mov 40(%esp), %edi\n" + " mov 44(%esp), %ebp\n" + " int $0x80\n" + " pop %ebx\n" + " pop %esi\n" + " pop %edi\n" + " pop %ebp\n" + " ret\n" + ".size zr_call, . - zr_call\n" + ".hidden zr_clone\n" + ".type zr_clone, @function\n" + "zr_clone:\n" + " push %ebx\n" + " push %esi\n" + " push %edi\n" + " mov 16(%esp), %ebx\n" + " mov 20(%esp), %ecx\n" + " mov 24(%esp), %edi\n" + " mov 28(%esp), %edx\n" + " mov 32(%esp), %esi\n" + " mov $" ZR_NR(SYS_clone) ", %eax\n" + " int $0x80\n" + " test %eax, %eax\n" + " jnz 1f\n" + " xor %ebp, %ebp\n" + " call zr_thread\n" + " xor %ebx, %ebx\n" + " mov $" ZR_NR(SYS_exit) ", %eax\n" + " int $0x80\n" + " hlt\n" + "1:\n" + " pop %edi\n" + " pop %esi\n" + " pop %ebx\n" + " ret\n" + ".size zr_clone, . - zr_clone\n" + ".popsection\n"); +#else +#error "zram.c needs a raw system call for this architecture" +#endif + +long zr_call(long n, long a, long b, long c, long d, long e, long f) __attribute__((visibility("hidden"))); +long zr_clone(long flags, char *stack, int *child, int *parent, void *tls) __attribute__((visibility("hidden"))); +void zr_thread(void) __attribute__((visibility("hidden"))); -static long (*zr_sys)(long, ...); static unsigned long zr_page; -static int zr_busy; -static int zr_pending; -static int zr_worker; +static unsigned zr_requests; +static int zr_stack_busy; +static int zr_tid; +static long zr_filters; +static char *zr_stack; static char zr_maps[8192]; static uint64_t zr_entries[ZR_BATCH]; static struct iovec zr_iov[ZR_BATCH]; @@ -54,6 +201,18 @@ static uint16_t zr_gen = 1; static unsigned long zr_cursor; static unsigned long zr_visits; +static int zr_prefix(const char *text, const char *prefix) { + while (*prefix) + if (*text++ != *prefix++) return 0; + return 1; +} + +static char *zr_find(char *text, char c, size_t n) { + for (; n > 0; n--, text++) + if (*text == c) return text; + return NULL; +} + static int zr_open(const char *path) { return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0); } @@ -103,7 +262,7 @@ static int zr_eligible(const char *line, int compress, unsigned long *start, uns while (*p && *p != ' ') p++; while (*p == ' ') p++; } - return *p == 0 || strncmp(p, "[heap]", 6) == 0 || strncmp(p, "[anon:", 6) == 0; + return *p == 0 || zr_prefix(p, "[heap]") || zr_prefix(p, "[anon:"); } static void zr_read_back(int pagemap, unsigned long start, unsigned long end) { @@ -137,7 +296,7 @@ static unsigned long zr_count(int pagemap, unsigned long start, unsigned long en do { if (zr_sys(SYS_lseek, pagemap, (long)(start / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return ZR_FAILED; got = zr_sys(SYS_read, pagemap, zr_entries, size); - } while (got < 0 && errno == EINTR); + } while (got == -EINTR); if (got != size) return ZR_FAILED; for (long i = 0; i < got / (long)sizeof(uint64_t); i++) if (zr_entries[i] & bit) count++; @@ -157,8 +316,7 @@ static struct zr_slot *zr_slot(unsigned long addr, int create) { } } if (!create) return NULL; - memset(&zr_slots[home], 0, sizeof(zr_slots[home])); - zr_slots[home].key = key; + zr_slots[home] = (struct zr_slot){.key = key}; return &zr_slots[home]; } @@ -228,13 +386,13 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns size_t have = 0; while (done < want && zr_visits > 0) { long n = zr_sys(SYS_read, maps, zr_maps + have, sizeof(zr_maps) - 1 - have); - if (n < 0 && errno == EINTR) continue; + if (n == -EINTR) continue; if (n <= 0) break; have += (size_t)n; zr_maps[have] = 0; char *line = zr_maps; char *nl; - while (done < want && zr_visits > 0 && (nl = memchr(line, '\n', have - (size_t)(line - zr_maps))) != NULL) { + while (done < want && zr_visits > 0 && (nl = zr_find(line, '\n', have - (size_t)(line - zr_maps))) != NULL) { *nl = 0; unsigned long s, e; if (zr_eligible(line, mode != 0, &s, &e) && e > s) { @@ -245,7 +403,7 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns line = nl + 1; } have -= (size_t)(line - zr_maps); - memmove(zr_maps, line, have); + for (size_t i = 0; i < have; i++) zr_maps[i] = line[i]; if (have == sizeof(zr_maps) - 1) have = 0; } if (pagemap >= 0) zr_sys(SYS_close, pagemap); @@ -291,15 +449,88 @@ static void zr_request(int worker) { zr_ack((long)(done * (zr_page / 1024)), 1); } -static void *zr_worker_main(void *unused) { - (void)unused; - prctl(PR_SET_NAME, "zr-worker", 0, 0, 0); - for (;;) { - while (!__atomic_exchange_n(&zr_pending, 0, __ATOMIC_SEQ_CST)) - zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAIT, 0, NULL, NULL, 0); - zr_request(1); +static void zr_drain(int worker) { + unsigned seen; + do { + seen = __atomic_load_n(&zr_requests, __ATOMIC_ACQUIRE); + zr_request(worker); + } while (!__atomic_compare_exchange_n(&zr_requests, &seen, 0, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)); +} + +void zr_thread(void) { + zr_sys(SYS_prctl, PR_SET_NAME, "zr-worker"); + zr_drain(1); +} + +static void *zr_tls(void *desc) { +#if defined(__aarch64__) + (void)desc; + return __builtin_thread_pointer(); +#elif defined(__x86_64__) + (void)desc; + void *self; + __asm__("mov %%fs:0, %0" : "=r"(self)); + return self; +#else + struct user_desc *entry = desc; + unsigned short selector; + __asm__("mov %%gs, %0" : "=r"(selector)); + entry->entry_number = selector >> 3; + return zr_sys(SYS_get_thread_area, entry) == 0 ? entry : NULL; +#endif +} + +static long zr_field(const char *text, const char *key) { + for (const char *line = text; *line; line++) { + if ((line == text || line[-1] == '\n') && zr_prefix(line, key)) { + long value = 0; + for (const char *k = key; *k; k++) line++; + while (*line == ' ' || *line == '\t') line++; + for (; *line >= '0' && *line <= '9'; line++) value = value * 10 + (*line - '0'); + return value; + } } - return NULL; + return -1; +} + +static int zr_status(long *threads, long *filters) { + int fd = zr_open("/proc/thread-self/status"); + if (fd < 0) return 0; + long have = 0, n; + while (have < (long)sizeof(zr_maps) - 1 && + ((n = zr_sys(SYS_read, fd, zr_maps + have, sizeof(zr_maps) - 1 - (size_t)have)) > 0 || n == -EINTR)) + if (n > 0) have += n; + zr_sys(SYS_close, fd); + zr_maps[have] = 0; + *threads = zr_field(zr_maps, "Threads:"); + *filters = zr_field(zr_maps, "Seccomp_filters:"); + return have > 0; +} + +static int zr_start(void) { + long threads, filters; + if (!zr_status(&threads, &filters) || threads < 2 || filters > zr_filters) return 0; + if (zr_stack == NULL) { + long base = zr_sys(ZR_MMAP, 0, ZR_STACK, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0); + if ((unsigned long)base > -4096UL) return 0; + zr_stack = (char *)base; + } + struct { long sec, nsec; } wait = {0, 5000000}; + for (int i = 0; i < 20 && __atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE); i++) + zr_sys(SYS_futex, &zr_stack_busy, ZR_FUTEX_WAIT, 1, &wait, NULL, 0); + if (__atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE)) return 0; + uint64_t desc[4] = {0}; + void *tls = zr_tls(desc); + if (tls == NULL) return 0; + uint64_t all = ~0ULL, previous; + if (zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &all, &previous, sizeof(all)) != 0) return 0; + __atomic_store_n(&zr_stack_busy, 1, __ATOMIC_RELEASE); + long tid = zr_clone(ZR_THREAD, zr_stack + ZR_STACK, &zr_stack_busy, &zr_tid, tls); + zr_sys(SYS_rt_sigprocmask, SIG_SETMASK, &previous, NULL, sizeof(previous)); + if (tid > 0) return 1; + __atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE); + return 0; } static void zr_handler(int sig, siginfo_t *info, void *context) { @@ -307,34 +538,23 @@ static void zr_handler(int sig, siginfo_t *info, void *context) { (void)context; if (info == NULL || info->si_code != SI_USER) return; int saved = errno; - __atomic_store_n(&zr_pending, 1, __ATOMIC_SEQ_CST); - if (__atomic_load_n(&zr_worker, __ATOMIC_ACQUIRE)) { - zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAKE, 1, NULL, NULL, 0); - } else while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST) - && !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) { - __atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST); - zr_request(0); - __atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST); - } + if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0); errno = saved; } static void zr_child(void) { - __atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST); - __atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST); - __atomic_store_n(&zr_worker, 0, __ATOMIC_RELEASE); + __atomic_store_n(&zr_requests, 0, __ATOMIC_RELEASE); + __atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE); } __attribute__((constructor)) static void zr_init(void) { - void *libc = dlopen("libc.so.6", RTLD_LAZY | RTLD_NOLOAD); - if (libc == NULL) return; - zr_sys = (long (*)(long, ...))dlsym(libc, "syscall"); - if (zr_sys == NULL) return; int fd = zr_open(ZR_CTL); if (fd < 0) return; zr_sys(SYS_close, fd); long page = sysconf(_SC_PAGESIZE); zr_page = page > 0 ? (unsigned long)page : 4096UL; + long threads; + if (!zr_status(&threads, &zr_filters)) zr_filters = -1; struct sigaction old; if (sigaction(SIGURG, NULL, &old) != 0) return; if ((old.sa_flags & SA_SIGINFO) || old.sa_handler != SIG_DFL) return; @@ -343,21 +563,5 @@ __attribute__((constructor)) static void zr_init(void) { sa.sa_sigaction = zr_handler; sa.sa_flags = SA_SIGINFO | SA_RESTART; sigemptyset(&sa.sa_mask); - if (sigaction(SIGURG, &sa, NULL) == 0) { - pthread_atfork(NULL, NULL, zr_child); - pthread_attr_t attr; - if (pthread_attr_init(&attr) == 0) { - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - pthread_t thread; - sigset_t blocked; - sigset_t previous; - if (sigfillset(&blocked) == 0 && - pthread_sigmask(SIG_SETMASK, &blocked, &previous) == 0) { - if (pthread_create(&thread, &attr, zr_worker_main, NULL) == 0) - __atomic_store_n(&zr_worker, 1, __ATOMIC_RELEASE); - pthread_sigmask(SIG_SETMASK, &previous, NULL); - } - pthread_attr_destroy(&attr); - } - } + if (sigaction(SIGURG, &sa, NULL) == 0) pthread_atfork(NULL, NULL, zr_child); } diff --git a/tools/linuxfs/unwrap-dwarfs.sh b/tools/linuxfs/unwrap-dwarfs.sh new file mode 100755 index 0000000000..2956967667 --- /dev/null +++ b/tools/linuxfs/unwrap-dwarfs.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +wrapper=${1:?usage: unwrap-dwarfs.sh WRAPPER OUTPUT} +output=${2:?usage: unwrap-dwarfs.sh WRAPPER OUTPUT} +[ "$(tail -c 32 "$wrapper" | head -c 8)" = "SQUEEZE!" ] || { echo "unwrap-dwarfs.sh: $wrapper has no SQUEEZE! trailer" >&2; exit 1; } +packed=$(tail -c 16 "$wrapper" | od -An -tu8 -N8 | tr -d ' ') +[ "$packed" -gt 0 ] && [ "$packed" -le $(( $(wc -c < "$wrapper") - 32 )) ] || { echo "unwrap-dwarfs.sh: bad payload size in $wrapper" >&2; exit 1; } +tail -c $((packed + 32)) "$wrapper" | head -c "$packed" | zstd -dcq > "$output" diff --git a/tools/linuxfs/uruntime.env b/tools/linuxfs/uruntime.env index f1b445d860..55e73d3eff 100644 --- a/tools/linuxfs/uruntime.env +++ b/tools/linuxfs/uruntime.env @@ -1,3 +1,7 @@ URUNTIME_VERSION=v0.8.1 URUNTIME_ASSET=uruntime-appimage-lite-aarch64 URUNTIME_SHA256=8485ae20eb0bfd4eaeac38d7fd7f78e153b391c718cf33ff07879605683be1ea +DWARFS_VERSION=v0.15.7 +DWARFS_ASSET=dwarfs-fuse-extract-0.15.7-Linux-aarch64 +DWARFS_SHA256=edb698186db6b162c755770ffabfcc05482bb7105a716fd943548e64244b0fd2 +DWARFS_PAYLOAD_SHA256=cc3b3e342ca6537139d8c90d3c0a00236cf786bb61bdccf019e5ed0ca5917a7a diff --git a/tools/memory_guard_ab.py b/tools/memory_guard_ab.py index 0bcd81d6d6..9aa2fa21a7 100755 --- a/tools/memory_guard_ab.py +++ b/tools/memory_guard_ab.py @@ -26,30 +26,52 @@ PACKAGE = "com.droiddeck.launcher" SESSION = f"{PACKAGE}/.SessionActivity" HOG_PATH = "/data/local/tmp/dd-memory-hog.sh" HOG_MOUNT = "/dev/dd-memory-hog" +SEED_PATH = "/data/local/tmp/dd-memory-burst.bin" +# oom_score_adj is read without su: under pressure lmkd kills the root manager app, and each su call +# can then open its request screen on top of the game. # Incompressible data in a private tmpfs: zram cannot shrink it and no app owns it, so lmkd keeps # killing by oom_score_adj while it is held. HOG = f"""#!/system/bin/sh -stop_mb=$1; hold=$2 -cleanup() {{ rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }} +stop_mb=$1; hold=$2; mode=$3 +cleanup() {{ kill $(jobs -p) 2>/dev/null; rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }} trap 'cleanup; exit 1' HUP INT TERM mkdir -p {HOG_MOUNT} grep -q ' {HOG_MOUNT} ' /proc/mounts || mount -t tmpfs -o size=16g tmpfs {HOG_MOUNT} -i=0 +i=0; failed=0 +if [ "$mode" = burst ]; then + [ "$(stat -c %s {SEED_PATH} 2>/dev/null)" = 268435456 ] || + {{ head -c 268435456 /dev/urandom > {SEED_PATH}.tmp && mv {SEED_PATH}.tmp {SEED_PATH}; }} || + {{ rm -f {SEED_PATH}.tmp; cleanup; exit 1; }} + cat {SEED_PATH} > /dev/null + avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo) + echo "avail=$avail" + take=$((avail - stop_mb)) + [ "$take" -gt 0 ] || {{ echo "nothing to take"; cleanup; exit 2; }} + n=$((take / 256)); rest=$((take % 256)); pids="" + echo "burst_mb=$take start=$(date +%s%N)" + while [ $i -lt $n ]; do cat {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; i=$((i+1)); done + [ "$rest" -gt 0 ] && {{ head -c $((rest * 1048576)) {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; }} + for pid in $pids; do wait "$pid" || failed=1; done + echo "burst_done=$(date +%s%N)" + echo "avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)" + i=512 +fi while [ $i -lt 512 ]; do avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo) echo "avail=$avail" [ "$avail" -le "$stop_mb" ] && break - head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || break + head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || {{ failed=1; break; }} i=$((i+1)) done +[ "$failed" = 0 ] || {{ echo "write failed"; cleanup; exit 1; }} sleep "$hold" cleanup echo released """ # Stops a writer left by an interrupted run before its files go, so the unmount does not fail. The # bracketed patterns keep pkill from matching the shell that runs this line. -HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; sleep 1; rm -f {HOG_MOUNT}/f*; " +HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; pkill -f '[d]d-memory-burst.bin'; sleep 1; rm -f {HOG_MOUNT}/f*; " f"umount {HOG_MOUNT} 2>/dev/null; true") def focused_display(input_dump: str) -> int | None: @@ -58,7 +80,7 @@ def focused_display(input_dump: str) -> int | None: def activity_count(activities_dump: str, activity: str) -> int: - return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r" ", activities_dump)) + return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r"[ }]", activities_dump)) def guard_count(activities_dump: str) -> int: @@ -85,7 +107,8 @@ def panel_windows(windows_dump: str, display: int) -> int: def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | None: - display = None + """The visible home on another display, else the visible app on top of it.""" + display, top = None, None for line in activities_dump.splitlines(): section = re.match(r"Display #(\d+) \(activities", line) if section: @@ -96,7 +119,10 @@ def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | home = re.search(r"type=home A=\d+:(\S+) .*visible=true", line) if home: return display, home.group(1) - return None + app = re.search(r"type=standard A=\d+:([\w.]+) .*visible=true", line) + if app and top is None and not app.group(1).startswith(PACKAGE): + top = display, app.group(1) + return top def logical_size(displays_dump: str, display: int) -> tuple[int, int] | None: @@ -151,8 +177,11 @@ class Device: return self.sh(f"su -c {shlex.quote(command)}", timeout=timeout) def ctl(self, *args: str, timeout: int = 300) -> subprocess.CompletedProcess[str]: - return subprocess.run([str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args], - capture_output=True, text=True, timeout=timeout) + command = [str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args] + try: + return subprocess.run(command, capture_output=True, text=True, timeout=timeout) + except subprocess.TimeoutExpired: + return subprocess.CompletedProcess(command, -1, "", f"timed out after {timeout} s") def phase(self) -> str | None: match = re.search(r'"phase":\s*"(\w+)"', self.ctl("state").stdout) @@ -208,7 +237,8 @@ class Bench: def prepare(self, apk: str | None): self.d.sh("input keyevent KEYCODE_WAKEUP") - self.d.ctl("stop") + if self.d.ctl("stop", timeout=120).returncode != 0: + self.d.sh(f"am force-stop {PACKAGE}") if apk: env = dict(os.environ, ADB_SERIAL=self.d.serial) subprocess.run([str(TOOLS / "deploy_local.sh"), apk], env=env, check=True, capture_output=True) @@ -234,7 +264,7 @@ class Bench: "guards": guard_count(activities), "sessions": session_count(activities), "panel": panel_windows(self.d.sh("dumpsys window windows"), display), - "adj": int(self.d.su(f"cat /proc/{pid}/oom_score_adj").strip() or -9999), + "adj": int(self.d.sh(f"cat /proc/{pid}/oom_score_adj").strip() or -9999), "pid": pid, } @@ -251,7 +281,8 @@ class Bench: before = self.snapshot() _, home = self.bottom() self.d.run("logcat", "-b", "events", "-c") - samples = self.d.su(f"kill -9 $(pidof {home}); for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj" + self.d.su(f"kill -9 $(pidof {home})") + samples = self.d.sh(f"for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj" " 2>/dev/null || echo DEAD; sleep 0.1; done").split() events = self.d.run("logcat", "-b", "events", "-d") (self.out / f"{self.label}-{state}-events.txt").write_text(events) @@ -297,7 +328,7 @@ class Bench: self.probe("using_bottom_now") self.game_front() - def pressure(self, run: str, stop_mb: int, hold: int): + def pressure(self, run: str, stop_mb: int, hold: int, burst: bool = False) -> bool: with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as script: script.write(HOG) try: @@ -305,16 +336,18 @@ class Bench: finally: os.unlink(script.name) self.d.sh(f"chmod 755 {HOG_PATH}") - self.game_front() self.close_panel() + self.game_front() + self.tap(self.session_display, (0.36, 0.11)) + time.sleep(2) before = self.snapshot() self.d.run("logcat", "-b", "events", "-c") - hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)}'"], + hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)} {'burst' if burst else 'fill'}'"], stdout=subprocess.PIPE, text=True) samples = [] try: while hog.poll() is None: - samples.append(self.d.su(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip()) + samples.append(self.d.sh(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip()) time.sleep(0.5) output = hog.stdout.read() if hog.stdout else "" finally: @@ -324,12 +357,19 @@ class Bench: time.sleep(3) events = self.d.run("logcat", "-b", "events", "-d") (self.out / f"{self.label}-{run}-events.txt").write_text(events) + workload_ok = hog.returncode == 0 and "released" in output.splitlines() + if not workload_ok: + print(f"memory-guard-ab: {run}: the memory hog failed (exit {hog.returncode}): " + f"{output.strip().splitlines()[-1] if output.strip() else 'no output'}", file=sys.stderr) available = [int(value) for value in re.findall(r"avail=(\d+)", output)] + took = re.search(r"start=(\d+).*?burst_done=(\d+)", output, re.S) self.write("pressure", { - "run": run, "stop_mb": stop_mb, "hold_s": hold, **{k: v for k, v in before.items() if k != "pid"}, + "run": run, "workload_ok": workload_ok, "mode": "burst" if burst else "fill", "stop_mb": stop_mb, "hold_s": hold, + "burst_ms": (int(took.group(2)) - int(took.group(1))) // 1_000_000 if took else None, **{k: v for k, v in before.items() if k != "pid"}, "min_available_mb": min(available) if available else None, "adj_max": max_adj(samples), "droiddeck_alive": self.d.pid() == before["pid"], "phase": self.d.phase(), **summarize_events(events), }) + return workload_ok def fraction_pair(text: str) -> tuple[float, float]: @@ -355,6 +395,8 @@ def main() -> int: pressure.add_argument("--stop-mb", type=int, default=650, help="stop filling at this MemAvailable") pressure.add_argument("--hold", type=int, default=30) pressure.add_argument("--runs", type=int, default=1) + pressure.add_argument("--burst", action="store_true", + help="take everything above --stop-mb at once instead of filling 32 MiB at a time") summarize = commands.add_parser("summarize", help="summarize a saved events log") summarize.add_argument("events", type=Path) args = parser.parse_args() @@ -376,9 +418,19 @@ def main() -> int: bench.prepare(args.apk) bench.states() else: + completed = 0 for run in range(args.runs): - bench.prepare(args.apk if run == 0 else None) - bench.pressure(f"stop{args.stop_mb}-{run + 1}", args.stop_mb, args.hold) + try: + bench.prepare(args.apk if run == 0 else None) + except RuntimeError as exc: + print(f"memory-guard-ab: run {run + 1} skipped: {exc}", file=sys.stderr) + continue + if bench.pressure(f"{'burst' if args.burst else 'stop'}{args.stop_mb}-{run + 1}", args.stop_mb, + args.hold, args.burst): + completed += 1 + if completed == 0: + print("memory-guard-ab: no pressure run completed", file=sys.stderr) + return 1 except RuntimeError as exc: print(f"memory-guard-ab: {exc}", file=sys.stderr) return 1 diff --git a/tools/nativeguest/ddnatv-hook.c b/tools/nativeguest/ddnatv-hook.c index 58f688da4c..4070f55c85 100644 --- a/tools/nativeguest/ddnatv-hook.c +++ b/tools/nativeguest/ddnatv-hook.c @@ -41,6 +41,7 @@ #include <elf.h> #include <sys/sendfile.h> #include <sys/mman.h> +#include <semaphore.h> #include <sched.h> #include <time.h> #include <sys/xattr.h> diff --git a/tools/nativeguest/gosys/gosys.c b/tools/nativeguest/gosys/gosys.c index fb8230ce4a..4a38cf4364 100644 --- a/tools/nativeguest/gosys/gosys.c +++ b/tools/nativeguest/gosys/gosys.c @@ -37,7 +37,10 @@ enum { NR_CHDIR = 49, NR_CHROOT = 51, NR_FCHMODAT = 53, NR_FCHOWNAT = 54, NR_OPENAT = 56, NR_READLINKAT = 78, NR_NEWFSTATAT = 79, NR_UTIMENSAT = 88, NR_BIND = 200, NR_CONNECT = 203, NR_EXECVE = 221, NR_NAME_TO_HANDLE_AT = 264, NR_RENAMEAT2 = 276, NR_STATX = 291, - NR_OPENAT2 = 437, NR_FACCESSAT2 = 439, NR_FCHMODAT2 = 452, + NR_OPENAT2 = 437, NR_FACCESSAT2 = 439, NR_FCHMODAT2 = 452, NR_SETREGID = 143, NR_SETGID = 144, + NR_SETREUID = 145, NR_SETUID = 146, NR_SETRESUID = 147, NR_GETRESUID = 148, NR_SETRESGID = 149, + NR_GETRESGID = 150, NR_SETGROUPS = 159, NR_GETUID = 174, NR_GETEUID = 175, NR_GETGID = 176, + NR_GETEGID = 177, }; __attribute__((section(".hdr"), used)) @@ -459,6 +462,9 @@ static i64 handle(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i64 a1, case NR_SETXATTR: case NR_LSETXATTR: case NR_GETXATTR: case NR_LGETXATTR: case NR_LISTXATTR: case NR_LLISTXATTR: case NR_REMOVEXATTR: case NR_LREMOVEXATTR: case NR_RENAMEAT: case NR_RENAMEAT2: case NR_LINKAT: case NR_SYMLINKAT: case NR_GETCWD: case NR_BIND: case NR_CONNECT: case NR_EXECVE: + case NR_GETUID: case NR_GETEUID: case NR_GETGID: case NR_GETEGID: case NR_GETRESUID: case NR_GETRESGID: + case NR_SETUID: case NR_SETGID: case NR_SETREUID: case NR_SETREGID: case NR_SETRESUID: case NR_SETRESGID: + case NR_SETGROUPS: // The calls that carry paths: not mapped where the rootfs is not in its own place (above) if (!rewriting(h)) return sc(nr, a0, a1, a2, a3, a4, a5); break; @@ -483,6 +489,14 @@ static i64 handle(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i64 a1, i64 r = sc(nr, a0, a1, 0, 0, 0, 0); return r > 0 ? unmap_prefix(h, (char *)a0, r, 1) : r; } + case NR_GETUID: case NR_GETEUID: case NR_GETGID: case NR_GETEGID: case NR_SETUID: case NR_SETGID: + case NR_SETREUID: case NR_SETREGID: case NR_SETRESUID: case NR_SETRESGID: case NR_SETGROUPS: + return 0; + case NR_GETRESUID: case NR_GETRESGID: { + i64 r = sc(nr, a0, a1, a2, 0, 0, 0); + if (r == 0) *(u32 *)a0 = *(u32 *)a1 = *(u32 *)a2 = 0; + return r; + } case NR_BIND: case NR_CONNECT: return with_sockaddr(h, held, nr, a0, a1, a2); case NR_EXECVE: { diff --git a/tools/nativeguest/gosys/gosys_abi.h b/tools/nativeguest/gosys/gosys_abi.h index e0c4807d34..d06a4f5c8b 100644 --- a/tools/nativeguest/gosys/gosys_abi.h +++ b/tools/nativeguest/gosys/gosys_abi.h @@ -15,7 +15,7 @@ #include <stdint.h> #ifndef GOSYS_VERSION -#define GOSYS_VERSION 3u // raised when the code or its header changes: patched programs are patched again +#define GOSYS_VERSION 4u // raised when the code or its header changes: patched programs are patched again #endif // The scratch memory for rewritten paths: a small state area and 64 slots, in zero-filled memory the diff --git a/tools/nativeguest/hook/env.c b/tools/nativeguest/hook/env.c index e881ba1f71..fd6824d3b7 100644 --- a/tools/nativeguest/hook/env.c +++ b/tools/nativeguest/hook/env.c @@ -72,11 +72,10 @@ static char *map_preload_paths(const char *value) { return out; } -static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { +static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) { init_ddnatv_hook(); int count = 0; int has_preload = 0; - int has_ld_library_path = 0; int has_root = 0; int has_tunables = 0; int has_path = 0; @@ -104,7 +103,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { switch (e[0]) { case 'L': if (strncmp(e, "LD_PRELOAD=", 11) == 0) { has_preload = 1; preload_value = e + 11; } - else if (strncmp(e, "LD_LIBRARY_PATH=", 16) == 0) has_ld_library_path = 1; break; case 'G': if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1; @@ -164,6 +162,9 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) { continue; } + if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) { + continue; + } new_env[dst++] = envp[i]; } @@ -178,6 +179,15 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { new_env[dst++] = str; } } + if (chosen_real_exe && lib_path && lib_path[0] != '\0') { + size_t len = strlen(lib_path); + char *str = malloc(20 + len + 1); + if (str) { + memcpy(str, "DDNATV_LIBRARY_PATH=", 20); + memcpy(str + 20, lib_path, len + 1); + new_env[dst++] = str; + } + } char hook_buf[PATH_MAX]; const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL; @@ -205,19 +215,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { new_env[dst++] = str; } } - if (!has_ld_library_path && g_ddnatv_root[0] != '\0') { - size_t size = 16 + 1; - for (size_t i = 0; i < sizeof(k_rootfs_lib_dirs) / sizeof(k_rootfs_lib_dirs[0]); i++) { - char dir[PATH_MAX]; - size += 1 + strlen(rewrite_path_in_root(k_rootfs_lib_dirs[i], dir, sizeof(dir))); - } - char *str = malloc(size); - if (str) { - size_t n = ddnatv_append(str, size, 0, "LD_LIBRARY_PATH=", 16); - append_rootfs_lib_dirs(str, size, n, 0); - new_env[dst++] = str; - } - } if (!has_root && g_ddnatv_root[0] != '\0') { char *str = malloc(PATH_MAX + 16); if (str) { diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index ce91b699b5..8d18c2d394 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -9,17 +9,73 @@ // Runs before every exec, mostly in a child a shell has just forked: the copies write only the // string (ddnatv_copy_cstr), not the whole PATH_MAX buffer, since each page written there is a // copy-on-write fault. +static int follow_link(const char *path, char *target, size_t size) { + ssize_t len = readlink(path, target, size - 1); + if (len < 0) return 0; + target[len] = '\0'; + // proot's link2symlink leaves hard links as ".l2s.*" files that programs must not see by name + const char *base = strrchr(target, '/'); + return strncmp(base ? base + 1 : target, ".l2s.", 5) != 0; +} + static void resolve_symlinks(const char *path, char *out, size_t out_size, int depth) { if (!path || !out || out_size == 0) return; ddnatv_copy_cstr(out, out_size, path); if (depth > 8) return; - char link_target[PATH_MAX]; - ssize_t len = readlink(path, link_target, sizeof(link_target) - 1); - if (len < 0) return; - link_target[len] = '\0'; - char next_path[PATH_MAX]; + if (g_ddnatv_root_len > 0 && strncmp(path, g_ddnatv_root, g_ddnatv_root_len) == 0 && path[g_ddnatv_root_len] == '/') { + char done[PATH_MAX]; + char todo[PATH_MAX]; + size_t used = ddnatv_append(done, sizeof(done), 0, g_ddnatv_root, g_ddnatv_root_len); + ddnatv_copy_cstr(todo, sizeof(todo), path + g_ddnatv_root_len); + int links = 0; + char *rest = todo; + while (*rest) { + while (*rest == '/') rest++; + if (!*rest) break; + char *end = strchr(rest, '/'); + size_t n = end ? (size_t)(end - rest) : strlen(rest); + if (n == 1 && rest[0] == '.') { + rest += n; + continue; + } + if (n == 2 && rest[0] == '.' && rest[1] == '.') { + char *slash = strrchr(done + g_ddnatv_root_len, '/'); + if (slash) used = (size_t)(slash - done); + done[used] = '\0'; + rest += n; + continue; + } + size_t before = used; + used = ddnatv_append(done, sizeof(done), used, "/", 1); + used = ddnatv_append(done, sizeof(done), used, rest, n); + rest += n; + if (used >= sizeof(done) - 1) return; + if (!follow_link(done, link_target, sizeof(link_target))) { + struct stat st; + if (rest[strspn(rest, "/")] && (syscall(SYS_newfstatat, AT_FDCWD, done, &st, 0) != 0 || !S_ISDIR(st.st_mode))) return; + continue; + } + if (++links > 40) return; + size_t m = ddnatv_append(next_path, sizeof(next_path), 0, link_target, strlen(link_target)); + m = ddnatv_append(next_path, sizeof(next_path), m, "/", 1); + m = ddnatv_append(next_path, sizeof(next_path), m, rest, strlen(rest)); + if (m >= sizeof(next_path) - 1) return; + if (link_target[0] == '/') { + char rw_buf[PATH_MAX]; + resolve_symlinks(rewrite_path(next_path, rw_buf, sizeof(rw_buf)), out, out_size, depth + 1); + return; + } + used = before; + done[used] = '\0'; + ddnatv_copy_cstr(todo, sizeof(todo), next_path); + rest = todo; + } + if (used > g_ddnatv_root_len) ddnatv_copy_cstr(out, out_size, done); + return; + } + if (!follow_link(path, link_target, sizeof(link_target))) return; if (link_target[0] == '/') { char rw_buf[PATH_MAX]; const char *rewritten = rewrite_path(link_target, rw_buf, sizeof(rw_buf)); @@ -32,20 +88,16 @@ static void resolve_symlinks(const char *path, char *out, size_t out_size, int d memcpy(next_path, path, dir_len); next_path[dir_len] = '\0'; size_t n = ddnatv_append(next_path, sizeof(next_path), dir_len, "/", 1); - ddnatv_append(next_path, sizeof(next_path), n, link_target, (size_t)len); + ddnatv_append(next_path, sizeof(next_path), n, link_target, strlen(link_target)); } else { ddnatv_copy_cstr(next_path, sizeof(next_path), link_target); } } - // proot's link2symlink leaves hard links as ".l2s.*" files that programs must not see by name - const char *next_base = strrchr(next_path, '/'); - next_base = next_base ? next_base + 1 : next_path; - if (strncmp(next_base, ".l2s.", 5) == 0) return; resolve_symlinks(next_path, out, out_size, depth + 1); } -static char **ensure_hook_in_envp(char *const envp[], const char *real_exe) { - return prepare_ddnatv_env(envp, real_exe); +static char **ensure_hook_in_envp(char *const envp[], const char *real_exe, const char *lib_path) { + return prepare_ddnatv_env(envp, real_exe, lib_path); } // The file whose header decides how to start `target`: the symlink-resolved ELF (so ld.so and @@ -162,7 +214,7 @@ static int exec_interp_missing(int fd) { syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz) return ENOEXEC; interp[ph.p_filesz] = 0; - int ifd = (int)syscall(SYS_openat, AT_FDCWD, interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + int ifd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (ifd < 0) return errno; syscall(SYS_close, ifd); return 0; @@ -174,7 +226,7 @@ static int exec_interp_missing(int fd) { // a shell walking $PATH moves on at ENOENT and EACCES, and runs a file without "#!" as a script at // ENOEXEC. static int exec_preflight(const char *path) { - int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + int fd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (fd < 0) return errno; struct stat st; int err = 0; @@ -263,6 +315,60 @@ static int is_ldconfig_name(const char *name) { return strcmp(name, "ldconfig") == 0 || strcmp(name, "ldconfig.real") == 0; } +struct ldso_direct { + char prog[PATH_MAX]; + char lib_path[PATH_MAX * 6]; +}; + +// ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads +// gets the --library-path a start of its own gets, or ldd reports its libraries as not found, +// and its path mapped into the rootfs, since ld.so opens it without the hook +static char **ldso_direct_argv(char *const argv[], char *const envp[], struct ldso_direct *buf, int *err) { + *err = 0; + int caller_lib_path = 0; + int pi = ldso_program_index(argv, &caller_lib_path); + if (pi <= 0) return NULL; + int argc = 0; + while (argv[argc]) argc++; + const char *prog = argv[pi]; + if (caller_lib_path) { + // the caller's own --library-path stays as it is; only the program is mapped (when it is + // in the rootfs: a caller can also name a file by its real path) + if (prog[0] == '/') { + const char *mapped = rewrite_path(prog, buf->prog, sizeof(buf->prog)); + int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1; + if (fd >= 0) { + syscall(SYS_close, fd); + prog = mapped; + } + } + char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 1)); + if (!out) { + *err = ENOMEM; + return NULL; + } + for (int i = 0; i <= argc; i++) out[i] = argv[i]; + out[pi] = (char *)prog; + return out; + } + if (prog[0] == '/') prog = rewrite_path(prog, buf->prog, sizeof(buf->prog)); + struct exec_probe prog_probe; + probe_exec_file(prog, &prog_probe); + build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath, + prog[0] == '/' ? prog : NULL, buf->lib_path, sizeof(buf->lib_path)); + char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); + if (!out) { + *err = ENOMEM; + return NULL; + } + out[0] = argv[0]; + out[1] = (char *)"--library-path"; + out[2] = buf->lib_path; + for (int i = 1; i <= argc; i++) out[i + 2] = argv[i]; + out[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well + return out; +} + static int ddnatv_execve(const char *filename, char *const argv[], char *const envp[], int depth) { orig_execve_f_type orig_execve = real_execve(); if (!orig_execve) { @@ -353,7 +459,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e if (probe.is_elf && !probe.is_dynamic) static_elf = elf_target; // A Go program built for Android asks for Android's linker, so it is started like the dynamic // ones, but it makes its own system calls: it gets the code of the static Go programs (#42) - if (probe.is_dynamic && probe.android_interp) prepare_static_program_ex(elf_target, 1); + if (probe.is_dynamic) prepare_static_program_ex(elf_target, 1); // 1. Transparently route dynamically linked glibc ELF binaries through ld.so // Note: Statically linked binaries (PT_INTERP absent, e.g. Meta Muse Code) must execute directly! @@ -374,7 +480,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ENOMEM; return -1; } - char **new_env = ensure_hook_in_envp(envp, elf_target); + char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path); int ret = run_execve(orig_execve, ld_so, new_argv, new_env); if (errno == EACCES && chmod(ld_so, 0755) == 0) { // ld.so without its exec bit (an unusual restore): fix it once and retry @@ -388,65 +494,17 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } } - // ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads - // gets the --library-path a start of its own gets, or ldd reports its libraries as not found, - // and its path mapped into the rootfs, since ld.so opens it without the hook if (probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) { - int caller_lib_path = 0; - int pi = ldso_program_index(argv, &caller_lib_path); - if (pi > 0 && caller_lib_path) { - // the caller's own --library-path stays as it is; only the program is mapped (when it is - // in the rootfs: a caller can also name a file by its real path) - char prog_buf[PATH_MAX]; - const char *prog = argv[pi]; - if (prog[0] == '/') { - const char *mapped = rewrite_path(prog, prog_buf, sizeof(prog_buf)); - int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1; - if (fd >= 0) { - syscall(SYS_close, fd); - prog = mapped; - } - } - int argc = 0; - while (argv[argc]) argc++; - char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(argc + 1)); - if (!new_argv) { - errno = ENOMEM; - return -1; - } - for (int i = 0; i <= argc; i++) new_argv[i] = argv[i]; - new_argv[pi] = (char *)prog; - prepare_static_program(static_elf); // ld.so is a static program itself - char **ddnatv_env = prepare_ddnatv_env(envp, target); - int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); - int saved_errno = errno; - free_modified_env(ddnatv_env, envp); - free(new_argv); - errno = saved_errno; - return ret; + struct ldso_direct direct; + int err; + char **new_argv = ldso_direct_argv(argv, envp, &direct, &err); + if (err) { + errno = err; + return -1; } - if (pi > 0) { - char prog_buf[PATH_MAX]; - const char *prog = argv[pi][0] == '/' ? rewrite_path(argv[pi], prog_buf, sizeof(prog_buf)) : argv[pi]; - struct exec_probe prog_probe; - probe_exec_file(prog, &prog_probe); - char ld_lib_path[PATH_MAX * 6]; - build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath, - prog[0] == '/' ? prog : NULL, ld_lib_path, sizeof(ld_lib_path)); - int argc = 0; - while (argv[argc]) argc++; - char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); - if (!new_argv) { - errno = ENOMEM; - return -1; - } - new_argv[0] = argv[0]; - new_argv[1] = (char *)"--library-path"; - new_argv[2] = ld_lib_path; - for (int i = 1; i <= argc; i++) new_argv[i + 2] = argv[i]; - new_argv[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well + if (new_argv) { prepare_static_program(static_elf); // ld.so is a static program itself - char **ddnatv_env = prepare_ddnatv_env(envp, target); + char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -470,7 +528,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e return -1; } int ret; - if (is_host_interpreter(rewritten_interp)) { + if (is_host_interpreter(interp, rewritten_interp)) { char **sys_env = clean_env_for_system(envp); ret = run_execve(orig_execve, rewritten_interp, new_argv, sys_env); int saved_errno = errno; @@ -480,7 +538,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ELOOP; ret = -1; } else { - char **ddnatv_env = prepare_ddnatv_env(envp, NULL); + char **ddnatv_env = prepare_ddnatv_env(envp, NULL, NULL); ret = ddnatv_execve(rewritten_interp, new_argv, ddnatv_env, depth + 1); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -500,7 +558,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } if (static_elf) prepare_static_program(static_elf); - char **ddnatv_env = prepare_ddnatv_env(envp, target); + char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); int ret = run_execve(orig_execve, target, argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -706,81 +764,82 @@ int execle(const char *path, const char *arg0, ...) { return ret; } -int execvp(const char *file, char *const argv[]) { +static int exec_or_script(const char *path, char *const argv[], char *const envp[]) { + execve(path, argv, envp); + if (errno != ENOEXEC) return -1; + int argc = 0; + while (argv && argv[argc]) argc++; + char **script = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); + if (!script) { + errno = ENOMEM; + return -1; + } + script[0] = (char *)"/bin/sh"; + script[1] = (char *)path; + int n = 2; + for (int i = 1; i < argc; i++) script[n++] = argv[i]; + script[n] = NULL; + execve(script[0], script, envp); + int saved_errno = errno; + free(script); + errno = saved_errno; + return -1; +} + +static int exec_search_dir(const char *dir, size_t len, const char *file, char *const argv[], char *const envp[], int *denied) { + char candidate[PATH_MAX]; + int n = len ? snprintf(candidate, sizeof(candidate), "%.*s/%s", (int)len, dir, file) + : snprintf(candidate, sizeof(candidate), "%s", file); + if (n < 0 || n >= (int)sizeof(candidate)) { + errno = ENAMETOOLONG; + return 0; + } + exec_or_script(candidate, argv, envp); + switch (errno) { + case EACCES: + *denied = 1; + return 0; + case ENOENT: case ENOTDIR: case ESTALE: case ENODEV: case ETIMEDOUT: case ENAMETOOLONG: + return 0; + default: + return 1; + } +} + +static int exec_search(const char *file, char *const argv[], char *const envp[], const char *path_env) { if (!file || !*file) { errno = ENOENT; return -1; } - if (strchr(file, '/')) { - return execve(file, argv, environ); - } - const char *path_env = getenv("PATH"); + if (strchr(file, '/')) return exec_or_script(file, argv, envp); if (!path_env) path_env = "/usr/bin:/bin"; - char path_copy[4096]; - strncpy(path_copy, path_env, sizeof(path_copy) - 1); - path_copy[sizeof(path_copy) - 1] = '\0'; - char *saveptr = NULL; - char *token = strtok_r(path_copy, ":", &saveptr); - while (token) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", token, file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, environ); - } - token = strtok_r(NULL, ":", &saveptr); + int denied = 0; + for (const char *p = path_env;; ) { + const char *end = strchrnul(p, ':'); + if (exec_search_dir(p, (size_t)(end - p), file, argv, envp, &denied)) return -1; + if (!*end) break; + p = end + 1; } - const char *standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin", NULL}; - for (int i = 0; standard_paths[i] != NULL; i++) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", standard_paths[i], file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, environ); - } - } - return execve(file, argv, environ); + static const char *const standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin"}; + for (size_t i = 0; i < sizeof(standard_paths) / sizeof(standard_paths[0]); i++) + if (exec_search_dir(standard_paths[i], strlen(standard_paths[i]), file, argv, envp, &denied)) return -1; + errno = denied ? EACCES : ENOENT; + return -1; +} + +int execvp(const char *file, char *const argv[]) { + return exec_search(file, argv, environ, getenv("PATH")); } int execvpe(const char *file, char *const argv[], char *const envp[]) { - if (!file || !*file) { - errno = ENOENT; - return -1; - } - if (strchr(file, '/')) { - return execve(file, argv, envp); - } const char *path_env = NULL; - if (envp) { - for (char *const *ep = envp; *ep; ep++) { - if (strncmp(*ep, "PATH=", 5) == 0) { - path_env = *ep + 5; - break; - } + for (char *const *ep = envp; ep && *ep; ep++) { + if (strncmp(*ep, "PATH=", 5) == 0) { + path_env = *ep + 5; + break; } } - if (!path_env) path_env = getenv("PATH"); - if (!path_env) path_env = "/usr/bin:/bin"; - char path_copy[4096]; - strncpy(path_copy, path_env, sizeof(path_copy) - 1); - path_copy[sizeof(path_copy) - 1] = '\0'; - char *saveptr = NULL; - char *token = strtok_r(path_copy, ":", &saveptr); - while (token) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", token, file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, envp); - } - token = strtok_r(NULL, ":", &saveptr); - } - const char *standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin", NULL}; - for (int i = 0; standard_paths[i] != NULL; i++) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", standard_paths[i], file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, envp); - } - } - return execve(file, argv, envp); + return exec_search(file, argv, envp, path_env ? path_env : getenv("PATH")); } typedef int (*orig_posix_spawn_f_type)(pid_t *, const char *, const posix_spawn_file_actions_t *, @@ -823,7 +882,7 @@ static int spawn_script(pid_t *pid, const char *script, struct exec_probe *probe char **new_argv = build_script_argv(rewritten_interp, interp_arg, script, argv); if (!new_argv) return ENOMEM; int ret; - if (is_host_interpreter(rewritten_interp)) { + if (is_host_interpreter(interp, rewritten_interp)) { orig_posix_spawn_f_type orig_posix_spawn = real_posix_spawn(); char **sys_env = clean_env_for_system(envp); ret = orig_posix_spawn ? orig_posix_spawn(pid, rewritten_interp, file_actions, attrp, new_argv, sys_env) : ENOSYS; @@ -942,17 +1001,21 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, // Android programs get Android's environment, as execve() gives them: the glibc hook in // LD_PRELOAD crashes them. - char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target) : clean_env_for_system(orig_ep); + int via_ld_so = has_ld_so && strcmp(elf_target, ld_so) != 0; + char ld_lib_path[PATH_MAX * 6]; + ld_lib_path[0] = '\0'; + if (via_ld_so) + build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); + char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target, via_ld_so ? ld_lib_path : NULL) + : clean_env_for_system(orig_ep); int ret = -1; - if (has_ld_so && strcmp(elf_target, ld_so) != 0) { + if (via_ld_so) { ensure_exec_bit(elf_target, probe.mode); - if (probe.android_interp) prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42) + prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42) char hook_buf[PATH_MAX]; const char *hook_so = ddnatv_hook_library(hook_buf, sizeof(hook_buf)); - char ld_lib_path[PATH_MAX * 6]; - build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); char **new_argv = build_ldso_argv(ld_so, hook_so, ld_lib_path, elf_target, prog_name, argv); if (!new_argv) { ret = ENOMEM; @@ -968,9 +1031,19 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, } } else { if (in_root && probe.is_elf && !probe.is_dynamic) prepare_static_program(elf_target); - if (orig_posix_spawn) { - ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, argv, new_envp); + char **spawn_argv = (char **)argv; + int err = 0; + struct ldso_direct direct; + if (in_root && probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) { + char **direct_argv = ldso_direct_argv(argv, orig_ep, &direct, &err); + if (direct_argv) spawn_argv = direct_argv; } + if (err) { + ret = err; + } else if (orig_posix_spawn) { + ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, spawn_argv, new_envp); + } + if (spawn_argv != argv) free(spawn_argv); } if (!orig_posix_spawn) { diff --git a/tools/nativeguest/hook/exec_probe.c b/tools/nativeguest/hook/exec_probe.c index f877175e58..be708e9158 100644 --- a/tools/nativeguest/hook/exec_probe.c +++ b/tools/nativeguest/hook/exec_probe.c @@ -10,6 +10,13 @@ // PT_INTERP) literally and failed with "bad interpreter: No such file or directory". // getcwd() is not virtualised, so cwd + path is a real path that starts with DDNATV_ROOT. static const char *absolutize_exec_path(const char *path, char *buffer, size_t bufsize) { + if (is_proc_self_exe(path)) { + ssize_t n = handle_proc_self_exe(buffer, bufsize - 1); + if (n > 0 && buffer[0] == '/') { + buffer[n] = '\0'; + return buffer; + } + } if (!path || path[0] == '\0' || path[0] == '/') return path; char cwd[PATH_MAX]; static char *(*real_getcwd)(char *, size_t) = NULL; @@ -966,10 +973,14 @@ static void parse_shebang(char *hdr, char **interp, char **interp_arg) { *interp_arg = arg; } -// Interpreters outside the rootfs (Android's /system/bin/sh) run with Android's environment. -static int is_host_interpreter(const char *interp) { - return strncmp(interp, "/system", 7) == 0 || - (g_ddnatv_root[0] != '\0' && strncmp(interp, g_ddnatv_root, g_ddnatv_root_len) != 0); +// Interpreters outside the rootfs and its binds (Android's /system/bin/sh) run with Android's environment. +static int is_host_interpreter(const char *interp, const char *rewritten) { + if (strncmp(rewritten, "/system", 7) == 0) return 1; + if (g_ddnatv_root[0] == '\0' || get_rootfs_subpath(rewritten)) return 0; + if (!is_mapped_guest_path(interp)) return 1; + struct exec_probe probe; + probe_exec_file(rewritten, &probe); + return probe.android_interp; } // argv for running `script` with its interpreter: interp [arg] script args... (the script's own diff --git a/tools/nativeguest/hook/fileops.c b/tools/nativeguest/hook/fileops.c index 2632f0eefb..b20c07f814 100644 --- a/tools/nativeguest/hook/fileops.c +++ b/tools/nativeguest/hook/fileops.c @@ -418,6 +418,13 @@ int renameat2(int olddirfd, const char *oldpath, int newdirfd, const char *newpa return ret; } +static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, ssize_t ret) { + if (ret <= 0 || out == buf) return ret; + size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz; + memcpy(buf, out, n); + return (ssize_t)n; +} + // Hook readlink ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { if (is_proc_self_exe(pathname)) { @@ -431,13 +438,16 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { if (!orig_readlink) orig_readlink = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink"); char pbuf[PATH_MAX]; const char *target = rewrite_path(pathname, pbuf, sizeof(pbuf)); - ssize_t ret = orig_readlink ? orig_readlink(target, buf, bufsiz) : -1; + char whole[PATH_MAX]; + char *out = bufsiz && bufsiz < sizeof(whole) ? whole : buf; + size_t outsiz = out == whole ? sizeof(whole) : bufsiz; + ssize_t ret = orig_readlink ? orig_readlink(target, out, outsiz) : -1; if (ret < 0 && errno == ENOENT) { char alt[PATH_MAX]; const char *retry = usrmerge_retry_path(target, alt, sizeof(alt)); - if (retry) ret = orig_readlink(retry, buf, bufsiz); + if (retry) ret = orig_readlink(retry, out, outsiz); } - return postprocess_readlink(pathname, buf, ret, bufsiz); + return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz)); } // Hook readlinkat @@ -459,13 +469,16 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { } char pbuf[PATH_MAX]; const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, pbuf, sizeof(pbuf)) : pathname; - ssize_t ret = orig_readlinkat ? orig_readlinkat(dirfd, target, buf, bufsiz) : -1; + char whole[PATH_MAX]; + char *out = bufsiz && bufsiz < sizeof(whole) ? whole : buf; + size_t outsiz = out == whole ? sizeof(whole) : bufsiz; + ssize_t ret = orig_readlinkat ? orig_readlinkat(dirfd, target, out, outsiz) : -1; if (ret < 0 && errno == ENOENT && pathname && pathname[0] == '/') { char alt[PATH_MAX]; const char *retry = usrmerge_retry_path(target, alt, sizeof(alt)); - if (retry) ret = orig_readlinkat(dirfd, retry, buf, bufsiz); + if (retry) ret = orig_readlinkat(dirfd, retry, out, outsiz); } - return postprocess_readlink(pathname, buf, ret, bufsiz); + return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz)); } // Fortified readlink variants used by dpkg / update-alternatives diff --git a/tools/nativeguest/hook/go_programs.c b/tools/nativeguest/hook/go_programs.c index 987d0132ee..5bb6f627f6 100644 --- a/tools/nativeguest/hook/go_programs.c +++ b/tools/nativeguest/hook/go_programs.c @@ -70,14 +70,20 @@ static int go_read_phdrs(int fd, struct go_ph *ph, uint16_t *etype, uint16_t *ma static const uint32_t k_go_syscall6[7] = { 0xf94007e8u, 0xf9400be0u, 0xf9400fe1u, 0xf94013e2u, 0xf94017e3u, 0xf9401be4u, 0xf9401fe5u, }; +static const uint32_t k_go_raw_no_error[7] = { + 0xf9400be0u, 0xf9400fe1u, 0xf94013e2u, 0xaa1f03e3u, 0xaa1f03e4u, 0xaa1f03e5u, 0xf94007e8u, +}; #define GO_SVC 0xd4000001u #define GO_CMN_X0_4095 0xb13ffc1fu +#define GO_STR_X0_SP40 0xf90017e0u +#define GO_THUNK_STRIDE 32u +#define GO_QUIET_MAX 4 +_Static_assert(GO_THUNK_STRIDE * (GO_QUIET_MAX + 1) <= GOSYS_THUNK_BYTES, "the thunks fit"); // Where Syscall6 makes its call: the file offset of the instruction after the seven loads (the // "svc #0", or the branch that replaced it). *found counts the places; the first is returned. -static int64_t go_find_syscall6(int fd, const struct go_ph *ph, int n, int *found) { - int64_t first = -1; - *found = 0; +static int go_find_calls(int fd, const struct go_ph *ph, int n, const uint32_t *code, uint32_t after, int64_t *at, int max) { + int found = 0; enum { CHUNK = 1 << 20, KEEP = 36 }; unsigned char *buf = (unsigned char *)malloc(CHUNK + KEEP); if (!buf) return -1; @@ -90,19 +96,19 @@ static int64_t go_find_syscall6(int fd, const struct go_ph *ph, int n, int *foun ssize_t got = pread(fd, buf, (size_t)want, (off_t)(ph[i].offset + pos)); if (got <= KEEP) break; for (ssize_t o = 0; o + 36 <= got; o += 4) { - if (rd32(buf + o) != k_go_syscall6[0]) continue; + if (rd32(buf + o) != code[0]) continue; int same = 1; - for (int k = 1; k < 7 && same; k++) same = rd32(buf + o + 4 * k) == k_go_syscall6[k]; - if (!same || rd32(buf + o + 32) != GO_CMN_X0_4095) continue; - if (*found == 0) first = (int64_t)(ph[i].offset + pos + (uint64_t)o + 28); - (*found)++; + for (int k = 1; k < 7 && same; k++) same = rd32(buf + o + 4 * k) == code[k]; + if (!same || rd32(buf + o + 32) != after) continue; + if (found < max) at[found] = (int64_t)(ph[i].offset + pos + (uint64_t)o + 28); + found++; } if (pos + (uint64_t)got >= ph[i].filesz) break; pos += (uint64_t)got - (KEEP - 4); // the next chunk starts where the last place of this could begin, no place is split or counted twice } } free(buf); - return first; + return found; } // "b <delta>" / "bl <delta>" for a distance in bytes, or 0 when it does not fit @@ -179,13 +185,7 @@ static int go_open_for_write(int fd, const struct stat *st, const char *path, in // The bytes of the added code for a given place: the code with its header (the strings, and where // the scratch memory is), the instructions that connect the call site to it, and the trailer that // says what was changed to put it there. -static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, uint64_t cave_v, uint64_t scratch_v, - uint32_t to_entry, uint32_t back, const struct gosys_trailer *info) { - memcpy(img, gosys_blob, GOSYS_BLOB_SIZE); - struct gosys_hdr h = *strings; - h.scratch_rel = (int64_t)scratch_v - (int64_t)cave_v; - memcpy(img, &h, sizeof(h)); - unsigned char *th = img + GOSYS_THUNKS_OFF; +static void go_write_thunk(unsigned char *th, uint32_t to_entry, uint32_t back) { wr32(th + 0, 0xd10043ffu); // sub sp, sp, #16 wr32(th + 4, 0xf90003feu); // str x30, [sp] wr32(th + 8, 0xaa0803e7u); // mov x7, x8 (the number is the eighth argument) @@ -193,6 +193,15 @@ static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, wr32(th + 16, 0xf94003feu); // ldr x30, [sp] wr32(th + 20, 0x910043ffu); // add sp, sp, #16 wr32(th + 24, back); // b <the instruction after the call> +} + +static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, uint64_t cave_v, uint64_t scratch_v, + const uint32_t *to_entry, const uint32_t *back, int sites, const struct gosys_trailer *info) { + memcpy(img, gosys_blob, GOSYS_BLOB_SIZE); + struct gosys_hdr h = *strings; + h.scratch_rel = (int64_t)scratch_v - (int64_t)cave_v; + memcpy(img, &h, sizeof(h)); + for (int k = 0; k < sites; k++) go_write_thunk(img + GOSYS_THUNKS_OFF + GO_THUNK_STRIDE * (uint64_t)k, to_entry[k], back[k]); struct gosys_trailer t; memcpy(&t, img + GOSYS_BLOB_SIZE - sizeof(t), sizeof(t)); t.version = GOSYS_VERSION; @@ -220,11 +229,12 @@ static uint32_t go_blob_fingerprint(void) { // Gives the program its old segments and call back: the added code is zeroed, the data segment // is shortened, the instruction is a "svc #0" again. -static int go_undo(int wfd, struct go_ph *ph, int cave_seg, const struct gosys_trailer *tr, int64_t site_off) { +static int go_undo(int wfd, struct go_ph *ph, int cave_seg, const struct gosys_trailer *tr, const int64_t *site_off, int sites) { uint64_t cave_off = ph[cave_seg].offset + ph[cave_seg].filesz - tr->total_size; unsigned char word[4]; wr32(word, GO_SVC); - if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off) != 0) return -1; + for (int k = sites - 1; k >= 0; k--) + if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off[k]) != 0) return -1; unsigned char sz[16]; go_wr64(sz, tr->text_orig_filesz); go_wr64(sz + 8, tr->text_orig_filesz); @@ -253,14 +263,30 @@ static int go_disabled(void) { // The three branches that connect the call site and the code: site -> thunk, thunk -> entry (bl), // thunk -> the instruction after the site. 0 when one of them is too far. -static int go_branches(uint64_t cave_v, uint64_t site_v, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) { - uint64_t thunk_v = cave_v + GOSYS_THUNKS_OFF; +static int go_branches(uint64_t cave_v, uint64_t site_v, int k, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) { + uint64_t thunk_v = cave_v + GOSYS_THUNKS_OFF + GO_THUNK_STRIDE * (uint64_t)k; *to_thunk = go_branch(0x14000000u, (int64_t)thunk_v - (int64_t)site_v); *to_entry = go_branch(0x94000000u, (int64_t)(cave_v + GOSYS_ENTRY_OFF) - (int64_t)(thunk_v + 12)); *back = go_branch(0x14000000u, (int64_t)(site_v + 4) - (int64_t)(thunk_v + 24)); return *to_thunk && *to_entry && *back; } +static int go_links(uint64_t cave_v, const uint64_t *site_v, int sites, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) { + if (!go_branches(cave_v, site_v[0], 0, &to_thunk[0], &to_entry[0], &back[0])) return 0; + for (int k = 1; k < sites; k++) + if (!go_branches(cave_v, site_v[k], k, &to_thunk[k], &to_entry[k], &back[k])) return 1; + return sites; +} + +static int go_write_sites(int wfd, const int64_t *site_off, const uint32_t *to_thunk, int sites) { + unsigned char word[4]; + for (int k = sites - 1; k >= 0; k--) { + wr32(word, to_thunk[k]); + if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off[k]) != 0) return -1; + } + return 0; +} + // Adds the code to the program, or brings it up to date. Returns 1 when it changed the file, 0 when // there was nothing to do (not a Go program of a kind the code can serve, or already done), -1 when // the file could not be changed (it is started as it is). @@ -271,9 +297,11 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (n < 0) return -1; if (machine != EM_AARCH64 || (etype != GO_ET_EXEC && etype != GO_ET_DYN)) return 0; - int found = 0; - int64_t site_off = go_find_syscall6(fd, ph, n, &found); - if (found != 1) return 0; // not a Go of 1.19 or newer (or its function is not there once) + int64_t site_off[GO_QUIET_MAX + 1]; + if (go_find_calls(fd, ph, n, k_go_syscall6, GO_CMN_X0_4095, site_off, 1) != 1) return 0; // not a Go of 1.19 or newer (or its function is not there once) + int quiet = go_find_calls(fd, ph, n, k_go_raw_no_error, GO_STR_X0_SP40, site_off + 1, GO_QUIET_MAX); + if (quiet < 0) return -1; + int sites = 1 + (quiet <= GO_QUIET_MAX ? quiet : 0); // The loadable segments, by address int order[GO_MAX_PH], nl = 0; @@ -289,13 +317,16 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (nl < 2) return 0; // The call site must be in a segment that is mapped as code - uint64_t site_v = 0; - for (int i = 0; i < nl; i++) { - const struct go_ph *s = &ph[order[i]]; - if ((s->flags & GO_PF_X) && (uint64_t)site_off >= s->offset && (uint64_t)site_off < s->offset + s->filesz) - site_v = s->vaddr + ((uint64_t)site_off - s->offset); + uint64_t site_v[GO_QUIET_MAX + 1] = { 0 }; + for (int k = 0; k < sites; k++) { + for (int i = 0; i < nl; i++) { + const struct go_ph *s = &ph[order[i]]; + if ((s->flags & GO_PF_X) && (uint64_t)site_off[k] >= s->offset && (uint64_t)site_off[k] < s->offset + s->filesz) + site_v[k] = s->vaddr + ((uint64_t)site_off[k] - s->offset); + } + if (site_v[k] == 0) sites = k; } - if (site_v == 0) return 0; + if (sites == 0) return 0; struct gosys_hdr strings; memset(&strings, 0, sizeof(strings)); @@ -333,7 +364,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (wfd < 0) { rc = -1; } else { - rc = go_undo(wfd, ph, cave_seg, &tr, site_off); + rc = go_undo(wfd, ph, cave_seg, &tr, site_off, sites); changed = rc == 0; } } @@ -343,19 +374,20 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (cave_seg >= 0) { uint64_t cave_off = ph[cave_seg].offset + ph[cave_seg].filesz - tr.total_size; uint64_t cave_v = ph[cave_seg].vaddr + (cave_off - ph[cave_seg].offset); - int same = 0, site_ok = 0; - uint32_t to_thunk = 0, to_entry = 0, back = 0; + int same = 0, site_ok = 0, linked = 0; + uint32_t to_thunk[GO_QUIET_MAX + 1], to_entry[GO_QUIET_MAX + 1], back[GO_QUIET_MAX + 1]; // Is it what would be put there now? (the code of an older The native userland differs) if (tr.total_size == GOSYS_BLOB_SIZE && tr.rw_index < (uint32_t)n && ph[tr.rw_index].type == 1 && - go_branches(cave_v, site_v, &to_thunk, &to_entry, &back)) { + (linked = go_links(cave_v, site_v, sites, to_thunk, to_entry, back)) > 0) { uint64_t scratch_v = go_align_up(ph[tr.rw_index].vaddr + tr.rw_orig_memsz, 64); - go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, &tr); + go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, linked, &tr); same = pread(fd, have, GOSYS_BLOB_SIZE, (off_t)cave_off) == (ssize_t)GOSYS_BLOB_SIZE && memcmp(have, img, GOSYS_BLOB_SIZE) == 0 && ph[tr.rw_index].memsz == scratch_v - ph[tr.rw_index].vaddr + GOSYS_SCRATCH_SIZE; } unsigned char cur[4]; - site_ok = same && pread(fd, cur, 4, (off_t)site_off) == 4 && rd32(cur) == to_thunk; + site_ok = same; + for (int k = 0; k < linked && site_ok; k++) site_ok = pread(fd, cur, 4, (off_t)site_off[k]) == 4 && rd32(cur) == to_thunk[k]; if (same && site_ok) goto done; wfd = go_open_for_write(fd, st, path, &made_writable); @@ -365,13 +397,12 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { } if (same) { // The code is there, only the branch is not (a patch that was cut short) - wr32(word, to_thunk); - rc = go_pwrite_all(wfd, word, 4, (uint64_t)site_off); + rc = go_write_sites(wfd, site_off, to_thunk, linked); changed = rc == 0; goto done; } // An older code, or other strings: back to the plain program, then patch again - if (go_undo(wfd, ph, cave_seg, &tr, site_off) != 0) { + if (go_undo(wfd, ph, cave_seg, &tr, site_off, sites) != 0) { rc = -1; goto done; } @@ -394,7 +425,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { if (s->memsz != s->filesz || s->filesz == 0) continue; uint64_t v = go_align_up(s->vaddr + s->filesz, 64); uint64_t off = s->offset + (v - s->vaddr); - if (v + total > nx->vaddr || (nx->vaddr & 0x3fff) != 0) continue; + if (v + total > (nx->vaddr & ~0x3fffull)) continue; if (off + total > nx->offset || off + total > (uint64_t)st->st_size) continue; // Only padding may be written over uint64_t pad_from = s->offset + s->filesz, pad_len = off + total - pad_from; @@ -410,8 +441,9 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { } } int rw = order[nl - 1]; - uint32_t to_thunk = 0, to_entry = 0, back = 0; - if (text < 0 || !(ph[rw].flags & GO_PF_W) || rw == text || !go_branches(cave_v, site_v, &to_thunk, &to_entry, &back)) goto done; + uint32_t to_thunk[GO_QUIET_MAX + 1], to_entry[GO_QUIET_MAX + 1], back[GO_QUIET_MAX + 1]; + int linked = text < 0 ? 0 : go_links(cave_v, site_v, sites, to_thunk, to_entry, back); + if (text < 0 || !(ph[rw].flags & GO_PF_W) || rw == text || linked == 0) goto done; uint64_t scratch_v = go_align_up(ph[rw].vaddr + ph[rw].memsz, 64); struct gosys_trailer info; @@ -421,8 +453,8 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { info.rw_orig_memsz = ph[rw].memsz; info.text_index = (uint32_t)text; info.rw_index = (uint32_t)rw; - info.site_file_off = (uint64_t)site_off; - go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, &info); + info.site_file_off = (uint64_t)site_off[0]; + go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, linked, &info); wfd = go_open_for_write(fd, st, path, &made_writable); if (wfd < 0) { @@ -442,10 +474,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) { wr32(word, ph[text].flags | GO_PF_X); rc = go_pwrite_all(wfd, word, 4, ph[text].pos + 4); } - if (rc == 0) { - wr32(word, to_thunk); - rc = go_pwrite_all(wfd, word, 4, (uint64_t)site_off); - } + if (rc == 0) rc = go_write_sites(wfd, site_off, to_thunk, linked); changed = rc == 0; done: diff --git a/tools/nativeguest/hook/identity.c b/tools/nativeguest/hook/identity.c index 9599d7e0b2..ab48039d9d 100644 --- a/tools/nativeguest/hook/identity.c +++ b/tools/nativeguest/hook/identity.c @@ -21,7 +21,7 @@ int setresuid(uid_t ruid, uid_t euid, uid_t suid) { (void)ruid; (void)euid; (voi int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { (void)rgid; (void)egid; (void)sgid; return 0; } int getgroups(int size, gid_t list[]) { - if (size > 0 && list != NULL) list[0] = 0; + if (size > 0 && list != NULL && syscall(__NR_getresgid, list, list, list) != 0) return -1; return 1; } // What programs built with _FORTIFY_SOURCE call when the buffer's size is known (the check is diff --git a/tools/nativeguest/hook/paths.c b/tools/nativeguest/hook/paths.c index fc6c49e507..6e347b3296 100644 --- a/tools/nativeguest/hook/paths.c +++ b/tools/nativeguest/hook/paths.c @@ -82,7 +82,7 @@ static void ddnatv_load_binds(const char *spec) { char kernel_src[PATH_MAX]; if (strcmp(src, dst) != 0) { ddnatv_kernel_path(src, strlen(src), kernel_src, sizeof(kernel_src)); - src = kernel_src; + if (strncmp(kernel_src, "/proc/", 6) != 0 || kernel_src[6] < '0' || kernel_src[6] > '9') src = kernel_src; } b->src = strdup(src); b->dst = strdup(dst); @@ -188,6 +188,25 @@ static __thread int t_bind_link_depth = 0; static void normalize_path(char *path); +static int climbs_past_root(const char *dir, const char *target) { + long depth = 0; + for (const char *p = dir; *p; p++) + if (*p != '/' && (p == dir || p[-1] == '/')) depth++; + for (const char *p = target; *p;) { + while (*p == '/') p++; + const char *end = p; + while (*end && *end != '/') end++; + size_t len = (size_t)(end - p); + if (len == 2 && p[0] == '.' && p[1] == '.') { + if (--depth < 0) return 1; + } else if (len > 0 && !(len == 1 && p[0] == '.')) { + depth++; + } + p = end; + } + return 0; +} + #if defined(__aarch64__) static long raw_link_dir(const char *link, char *out, size_t size) { const char *slash = strrchr(link, '/'); @@ -215,25 +234,6 @@ static long raw_link_dir(const char *link, char *out, size_t size) { return n; } -static int climbs_past_root(const char *dir, const char *target) { - long depth = 0; - for (const char *p = dir; *p; p++) - if (*p != '/' && (p == dir || p[-1] == '/')) depth++; - for (const char *p = target; *p;) { - while (*p == '/') p++; - const char *end = p; - while (*end && *end != '/') end++; - size_t len = (size_t)(end - p); - if (len == 2 && p[0] == '.' && p[1] == '.') { - if (--depth < 0) return 1; - } else if (len > 0 && !(len == 1 && p[0] == '.')) { - depth++; - } - p = end; - } - return 0; -} - static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int *converted); static const char *guest_path_of_host_dir(const char *dir, char *out, size_t size) { @@ -335,6 +335,15 @@ static const char *resolve_drive_links(const char *host, char *buffer, size_t bu // Maps an absolute Ubuntu path into the rootfs. Returns `path` (possibly advanced past // redundant leading "/" and "/." components) when it needs no change, else `buffer`. +static const char *rewrite_normalized_in_root(const char *path, char *buffer, size_t bufsize) { + char normalized[PATH_MAX]; + ddnatv_copy_cstr(normalized, sizeof(normalized), path); + normalize_path(normalized); + const char *mapped = rewrite_path_in_root(normalized, buffer, bufsize); + if (mapped != buffer) ddnatv_copy_cstr(buffer, bufsize, mapped); + return buffer; +} + static const char *rewrite_path_in_root(const char *path, char *buffer, size_t bufsize) { if (!path) return NULL; if (path[0] != '/' || g_ddnatv_root_len == 0) return path; @@ -354,6 +363,8 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b } } + if (strstr(path, "/..") && climbs_past_root("", path)) return rewrite_normalized_in_root(path, buffer, bufsize); + // Root directory if (path[1] == '\0') { ddnatv_append(buffer, bufsize, 0, g_ddnatv_root, g_ddnatv_root_len); @@ -364,6 +375,8 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b const struct ddnatv_bind *b = &g_binds[i]; if (path[1] == b->dst[1] && is_path_prefix(path, b->dst, b->dst_len)) { if (b->identity) return path; + if (strstr(path + b->dst_len, "/..") && climbs_past_root("", path + b->dst_len)) + return rewrite_normalized_in_root(path, buffer, bufsize); size_t n = ddnatv_append(buffer, bufsize, 0, b->src, b->src_len); ddnatv_append(buffer, bufsize, n, path + b->dst_len, strlen(path + b->dst_len)); return resolve_bind_links(buffer, b->src_len, buffer, bufsize); @@ -742,11 +755,6 @@ static size_t append_rootfs_lib_dirs_missing_from(char *out, size_t outsz, size_ return used; } -// All of them. -static size_t append_rootfs_lib_dirs(char *out, size_t outsz, size_t used, int separate) { - return append_rootfs_lib_dirs_missing_from(out, outsz, used, separate, NULL); -} - #ifndef DDNATV_HOST_TEST // Relative *at() calls. A program that walks a path one component at a time (systemd's chase(), used // by libudev; fts) opens "/" and then "sys", "class", ... relative to the last descriptor, and those @@ -806,10 +814,36 @@ static void ddnatv_build_at_dirs(void) { } } +#if defined(__aarch64__) +static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t size) { + char link[32], host[PATH_MAX], dir_buf[PATH_MAX], guest[PATH_MAX]; + if (dirfd == AT_FDCWD) ddnatv_copy_cstr(link, sizeof(link), "/proc/self/cwd"); + else snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd); + long n = raw_readlinkat(AT_FDCWD, link, host, sizeof(host) - 1); + if (n <= 0 || host[0] != '/') return NULL; + host[n] = '\0'; + const char *dir = guest_path_of_host_dir(host, dir_buf, sizeof(dir_buf)); + if (!dir || strcmp(dir, host) == 0) return NULL; + if (get_rootfs_subpath(host) && !climbs_past_root(dir, rel)) return NULL; + size_t used = ddnatv_append(guest, sizeof(guest), 0, dir, strlen(dir)); + used = ddnatv_append(guest, sizeof(guest), used, "/", 1); + used = ddnatv_append(guest, sizeof(guest), used, rel, strlen(rel)); + if (used + 1 >= sizeof(guest)) return NULL; + const char *mapped = rewrite_path_in_root(guest, buf, size); + if (mapped != buf) ddnatv_copy_cstr(buf, size, mapped); + return buf; +} +#endif + // The absolute host path for `rel` given relative to `dirfd`, or NULL when the call needs no change. static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) { #if defined(__aarch64__) - if (dirfd == AT_FDCWD || !rel || rel[0] == '\0' || rel[0] == '/' || g_nbinds == 0) return NULL; + if (!rel || rel[0] == '\0' || rel[0] == '/') return NULL; + if (strstr(rel, "..")) { + const char *walked = map_parent_walk(dirfd, rel, buf, size); + if (walked || dirfd == AT_FDCWD) return walked; + } + if (dirfd == AT_FDCWD || g_nbinds == 0) return NULL; pthread_once(&g_at_once, ddnatv_build_at_dirs); if (g_n_at_dirs == 0) return NULL; struct stat st; @@ -818,6 +852,7 @@ static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) { if (g_at_dirs[i].ino != (unsigned long)st.st_ino || g_at_dirs[i].dev != (unsigned long)st.st_dev) continue; char guest[PATH_MAX]; const char *base = g_at_dirs[i].guest; + if (base[1] && climbs_past_root(base, rel)) return NULL; size_t used = ddnatv_append(guest, sizeof(guest), 0, base, strlen(base)); if (used > 1) used = ddnatv_append(guest, sizeof(guest), used, "/", 1); ddnatv_append(guest, sizeof(guest), used, rel, strlen(rel)); diff --git a/tools/nativeguest/hook/posix_shm.c b/tools/nativeguest/hook/posix_shm.c index afd8a6f655..95ac489157 100644 --- a/tools/nativeguest/hook/posix_shm.c +++ b/tools/nativeguest/hook/posix_shm.c @@ -1,32 +1,148 @@ // Part of libddnatv-hook.so, included by ddnatv-hook.c. // -// shm_open() and shm_unlink() of glibc open /dev/shm/NAME with a system call of their own, which -// the path hooks never see and Android has no /dev/shm for. They go through open() and unlink() -// here, which map /dev/shm. +// shm_open(), shm_unlink() and the named semaphores of glibc open /dev/shm/NAME with system calls +// of their own, which the path hooks never see and Android has no /dev/shm for. They go through +// open(), renameat2() and unlink() here, which map /dev/shm. #ifndef DDNATV_HOST_TEST -static int posix_shm_path(const char *name, char *path, size_t size) { +static int posix_shm_path(const char *name, const char *prefix, char *path, size_t size) { if (!name) { errno = EINVAL; return -1; } while (*name == '/') name++; - size_t len = strlen(name); - if (len == 0 || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) { + size_t len = strlen(name) + strlen(prefix); + if (len == strlen(prefix) || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) { errno = len > NAME_MAX ? ENAMETOOLONG : EINVAL; return -1; } - if (snprintf(path, size, "/dev/shm/%s", name) >= (int)size) { errno = ENAMETOOLONG; return -1; } + if (snprintf(path, size, "/dev/shm/%s%s", prefix, name) >= (int)size) { errno = ENAMETOOLONG; return -1; } return 0; } int shm_open(const char *name, int oflag, mode_t mode) { char path[PATH_MAX]; - if (posix_shm_path(name, path, sizeof(path)) < 0) return -1; + if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1; return open(path, (oflag & (O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) | O_NOFOLLOW | O_CLOEXEC, mode); } int shm_unlink(const char *name) { char path[PATH_MAX]; - if (posix_shm_path(name, path, sizeof(path)) < 0) return -1; + if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1; + return unlink(path); +} + +struct posix_sem { + dev_t dev; + ino_t ino; + sem_t *addr; + unsigned int refs; + struct posix_sem *next; +}; +static struct posix_sem *g_posix_sems; +static pthread_mutex_t g_posix_sems_lock = PTHREAD_MUTEX_INITIALIZER; + +static void posix_sems_unlock(void) { pthread_mutex_unlock(&g_posix_sems_lock); } + +static void posix_sems_hold(void) { pthread_mutex_lock(&g_posix_sems_lock); } + +__attribute__((constructor)) static void posix_sems_across_fork(void) { + pthread_atfork(posix_sems_hold, posix_sems_unlock, posix_sems_unlock); +} + +static void close_keeping_errno(int fd) { + int saved = errno; + close(fd); + errno = saved; +} + +static sem_t *posix_sem_map(int fd) { + struct stat st; + if (fstat(fd, &st) < 0) return SEM_FAILED; + sem_t *sem = SEM_FAILED; + posix_sems_hold(); + struct posix_sem *e = g_posix_sems; + while (e && (e->dev != st.st_dev || e->ino != st.st_ino)) e = e->next; + if (e) { + e->refs++; + sem = e->addr; + } else { + void *addr = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + e = addr == MAP_FAILED ? NULL : malloc(sizeof(*e)); + if (e) { + *e = (struct posix_sem){st.st_dev, st.st_ino, addr, 1, g_posix_sems}; + g_posix_sems = e; + sem = addr; + } else if (addr != MAP_FAILED) { + munmap(addr, sizeof(sem_t)); + errno = ENOMEM; + } + } + posix_sems_unlock(); + return sem; +} + +static sem_t *posix_sem_open_fd(int fd) { + if (fd < 0) return SEM_FAILED; + sem_t *sem = posix_sem_map(fd); + close_keeping_errno(fd); + return sem; +} + +sem_t *sem_open(const char *name, int oflag, ...) { + char path[PATH_MAX]; + if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return SEM_FAILED; + if (!(oflag & O_CREAT)) return posix_sem_open_fd(open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC)); + va_list args; + va_start(args, oflag); + mode_t mode = va_arg(args, mode_t); + unsigned int value = va_arg(args, unsigned int); + va_end(args); + static unsigned int serial; + for (;;) { + if (!(oflag & O_EXCL)) { + int fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC); + if (fd >= 0 || errno != ENOENT) return posix_sem_open_fd(fd); + } + if (value > SEM_VALUE_MAX) { errno = EINVAL; return SEM_FAILED; } + sem_t initial; + memset(&initial, 0, sizeof(initial)); + sem_init(&initial, 1, value); + char temp[PATH_MAX]; + int fd; + do { + snprintf(temp, sizeof(temp), "/dev/shm/.sem-%d-%u", (int)getpid(), __atomic_fetch_add(&serial, 1, __ATOMIC_RELAXED)); + fd = open(temp, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode); + } while (fd < 0 && errno == EEXIST); + if (fd < 0) return SEM_FAILED; + errno = EIO; + sem_t *sem = write(fd, &initial, sizeof(initial)) == (ssize_t)sizeof(initial) ? posix_sem_map(fd) : SEM_FAILED; + close_keeping_errno(fd); + if (sem != SEM_FAILED && renameat2(AT_FDCWD, temp, AT_FDCWD, path, RENAME_NOREPLACE) == 0) return sem; + int saved = errno; + if (sem != SEM_FAILED) sem_close(sem); + unlink(temp); + errno = saved; + if (errno != EEXIST || (oflag & O_EXCL)) return SEM_FAILED; + } +} + +int sem_close(sem_t *sem) { + posix_sems_hold(); + struct posix_sem **link = &g_posix_sems; + while (*link && (*link)->addr != sem) link = &(*link)->next; + struct posix_sem *e = *link; + if (e && --e->refs == 0) { + *link = e->next; + munmap(e->addr, sizeof(sem_t)); + free(e); + } + posix_sems_unlock(); + if (!e) { errno = EINVAL; return -1; } + return 0; +} + +int sem_unlink(const char *name) { + char path[PATH_MAX]; + if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return -1; return unlink(path); } diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 7bf0a8b692..d2a84c7a23 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -519,6 +519,19 @@ static int close_range_all(unsigned int first, unsigned int last, int flags) { static __thread int t_syscall_redirect = 0; +static long nested_path_syscall(long number, unsigned long dirfd, unsigned long pathname, unsigned long arg3, unsigned long arg4) { + char nested_buf[PATH_MAX]; + const char *path = (const char *)pathname; + if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); + return call_orig_syscall(number, dirfd, (unsigned long)path, arg3, arg4, 0, 0); +} + +static long fake_root_ids(long number, unsigned int *real, unsigned int *effective, unsigned int *saved) { + long rc = call_orig_syscall(number, (unsigned long)real, (unsigned long)effective, (unsigned long)saved, 0, 0, 0); + if (rc == 0) *real = *effective = *saved = 0; + return rc; +} + long syscall(long number, ...) { va_list ap; va_start(ap, number); @@ -563,6 +576,38 @@ long syscall(long number, ...) { } #endif +#ifdef __NR_rt_sigprocmask + if (number == __NR_rt_sigprocmask && arg2 && (arg1 == SIG_BLOCK || arg1 == SIG_SETMASK) && arg4 == sizeof(uint64_t)) { + uint64_t mask; + memcpy(&mask, (const void *)arg2, sizeof(mask)); + mask &= ~(1ULL << (SIGSYS - 1)); + return call_orig_syscall(number, arg1, (unsigned long)&mask, arg3, arg4, 0, 0); + } +#endif + +#ifdef __NR_rt_sigaction + if (number == __NR_rt_sigaction && arg1 == SIGSYS && arg4 == sizeof(uint64_t)) { + struct { void *handler; unsigned long flags; void *restorer; uint64_t mask; } kact, kold; + struct sigaction act, old; + memset(&act, 0, sizeof(act)); + if (arg2) { + memcpy(&kact, (const void *)arg2, sizeof(kact)); + act.sa_sigaction = (void (*)(int, siginfo_t *, void *))kact.handler; + act.sa_flags = (int)kact.flags; + memcpy(&act.sa_mask, &kact.mask, sizeof(kact.mask)); + } + remember_app_sigsys(arg2 ? &act : NULL, arg3 ? &old : NULL); + if (arg3) { + memset(&kold, 0, sizeof(kold)); + kold.handler = (void *)old.sa_sigaction; + kold.flags = (unsigned long)(unsigned int)old.sa_flags; + memcpy(&kold.mask, &old.sa_mask, sizeof(kold.mask)); + memcpy((void *)arg3, &kold, sizeof(kold)); + } + return 0; + } +#endif + #ifdef __NR_seccomp if (number == __NR_seccomp) { return (long)seccomp((unsigned int)arg1, (unsigned int)arg2, (void *)arg3); @@ -618,16 +663,109 @@ long syscall(long number, ...) { } #endif + if (g_initialized) { +#ifdef __NR_openat + if (number == __NR_openat) { + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4); + t_syscall_redirect++; + long ret = (long)openat((int)arg1, (const char *)arg2, (int)arg3, (mode_t)arg4); + t_syscall_redirect--; + return ret; + } +#endif +#if defined(__NR_mkdirat) + if (number == __NR_mkdirat) { + return (long)mkdirat((int)arg1, (const char *)arg2, (mode_t)arg3); + } +#endif +#if defined(__NR_unlinkat) + if (number == __NR_unlinkat) { + return (long)unlinkat((int)arg1, (const char *)arg2, (int)arg3); + } +#endif +#if defined(__NR_renameat) + if (number == __NR_renameat) { + return (long)renameat((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4); + } +#endif +#if defined(__NR_renameat2) + if (number == __NR_renameat2) { + return (long)renameat2((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4, (unsigned int)arg5); + } +#endif +#if defined(__NR_symlinkat) + if (number == __NR_symlinkat) { + return (long)symlinkat((const char *)arg1, (int)arg2, (const char *)arg3); + } +#endif +#if defined(__NR_fchmodat) + if (number == __NR_fchmodat) { + return (long)fchmodat((int)arg1, (const char *)arg2, (mode_t)arg3, 0); + } +#endif +#if defined(__NR_fchownat) + if (number == __NR_fchownat) { + return (long)fchownat((int)arg1, (const char *)arg2, (uid_t)arg3, (gid_t)arg4, (int)arg5); + } +#endif +#if defined(__NR_utimensat) + if (number == __NR_utimensat) { + if (!arg2) return call_orig_syscall(number, arg1, arg2, arg3, arg4, 0, 0); + return (long)utimensat((int)arg1, (const char *)arg2, (const struct timespec *)arg3, (int)arg4); + } +#endif +#if defined(__NR_connect) + if (number == __NR_connect) { + return (long)connect((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3); + } +#endif +#if defined(__NR_bind) + if (number == __NR_bind) { + return (long)bind((int)arg1, (const struct sockaddr *)arg2, (socklen_t)arg3); + } +#endif +#if defined(__NR_sendmsg) + if (number == __NR_sendmsg) { + return (long)sendmsg((int)arg1, (const struct msghdr *)arg2, (int)arg3); + } +#endif +#if defined(__NR_recvmsg) + if (number == __NR_recvmsg) { + return (long)recvmsg((int)arg1, (struct msghdr *)arg2, (int)arg3); + } +#endif +#if defined(__NR_getsockopt) + if (number == __NR_getsockopt) { + return (long)getsockopt((int)arg1, (int)arg2, (int)arg3, (void *)arg4, (socklen_t *)arg5); + } +#endif +#if defined(__NR_truncate) + if (number == __NR_truncate) { + return (long)truncate((const char *)arg1, (off_t)arg2); + } +#endif +#if defined(__NR_chdir) + if (number == __NR_chdir) { + return (long)chdir((const char *)arg1); + } +#endif +#if defined(__NR_chroot) + if (number == __NR_chroot) { + return (long)chroot((const char *)arg1); + } +#endif +#if defined(__NR_inotify_add_watch) + if (number == __NR_inotify_add_watch) { + return (long)inotify_add_watch((int)arg1, (const char *)arg2, (uint32_t)arg3); + } +#endif + } + #ifdef __NR_openat2 if (number == __NR_openat2) { // libddsession's openat2() calls syscall() again (an endless loop until the stack ran out): the nested // call maps the path and goes straight to the kernel - if (t_syscall_redirect) { - char nested_buf[PATH_MAX]; - const char *path = (const char *)arg2; - if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); - return call_orig_syscall(number, arg1, (unsigned long)path, arg3, arg4, 0, 0); - } + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4); t_syscall_redirect++; long ret = (long)openat2((int)arg1, (const char *)arg2, (struct ddnatv_open_how *)arg3, (size_t)arg4); t_syscall_redirect--; @@ -649,12 +787,7 @@ long syscall(long number, ...) { #if defined(__NR_faccessat) if (number == __NR_faccessat) { - if (t_syscall_redirect) { - char nested_buf[PATH_MAX]; - const char *path = (const char *)arg2; - if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); - return call_orig_syscall(number, arg1, (unsigned long)path, arg3, 0, 0, 0); - } + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, 0); t_syscall_redirect++; long ret = (long)faccessat((int)arg1, (const char *)arg2, (int)arg3, 0); t_syscall_redirect--; @@ -765,48 +898,22 @@ long syscall(long number, ...) { if (number == __NR_getegid32) return 0; #endif #if defined(__NR_getresuid) - if (number == __NR_getresuid) { - uid_t *ruid = (uid_t *)arg1; - uid_t *euid = (uid_t *)arg2; - uid_t *suid = (uid_t *)arg3; - if (ruid) *ruid = 0; - if (euid) *euid = 0; - if (suid) *suid = 0; - return 0; - } + if (number == __NR_getresuid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); #endif #if defined(__NR_getresuid32) - if (number == __NR_getresuid32) { - uid_t *ruid = (uid_t *)arg1; - uid_t *euid = (uid_t *)arg2; - uid_t *suid = (uid_t *)arg3; - if (ruid) *ruid = 0; - if (euid) *euid = 0; - if (suid) *suid = 0; - return 0; - } + if (number == __NR_getresuid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); #endif #if defined(__NR_getresgid) - if (number == __NR_getresgid) { - gid_t *rgid = (gid_t *)arg1; - gid_t *egid = (gid_t *)arg2; - gid_t *sgid = (gid_t *)arg3; - if (rgid) *rgid = 0; - if (egid) *egid = 0; - if (sgid) *sgid = 0; - return 0; - } + if (number == __NR_getresgid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); #endif #if defined(__NR_getresgid32) - if (number == __NR_getresgid32) { - gid_t *rgid = (gid_t *)arg1; - gid_t *egid = (gid_t *)arg2; - gid_t *sgid = (gid_t *)arg3; - if (rgid) *rgid = 0; - if (egid) *egid = 0; - if (sgid) *sgid = 0; - return 0; - } + if (number == __NR_getresgid32) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3); +#endif +#if defined(__NR_getgroups) + if (number == __NR_getgroups) return (long)getgroups((int)arg1, (gid_t *)arg2); +#endif +#if defined(__NR_fchown) + if (number == __NR_fchown) return (long)fchown((int)arg1, (uid_t)arg2, (gid_t)arg3); #endif return call_orig_syscall(number, arg1, arg2, arg3, arg4, arg5, arg6); diff --git a/tools/nativeguest/hook/setup.c b/tools/nativeguest/hook/setup.c index 24f8a81317..5cf5ccb217 100644 --- a/tools/nativeguest/hook/setup.c +++ b/tools/nativeguest/hook/setup.c @@ -84,6 +84,19 @@ static void init_ddnatv_hook(void) { setenv("TZDIR", tzdir_buf, 0); } + const char *curr_locpath = getenv("LOCPATH"); + if (!curr_locpath || curr_locpath[0] == '\0') { + char locpath_buf[PATH_MAX]; + snprintf(locpath_buf, sizeof(locpath_buf), "%s/usr/lib/locale", g_ddnatv_root); + setenv("LOCPATH", locpath_buf, 1); + } + + if (!getenv("GCONV_PATH")) { + char gconv_buf[PATH_MAX]; + snprintf(gconv_buf, sizeof(gconv_buf), "%s/usr/lib/aarch64-linux-gnu/gconv", g_ddnatv_root); + setenv("GCONV_PATH", gconv_buf, 0); + } + const char *curr_cert = getenv("SSL_CERT_FILE"); if (!curr_cert || curr_cert[0] == '\0' || strcmp(curr_cert, "/etc/ssl/certs/ca-certificates.crt") == 0) { char cert_buf[PATH_MAX]; @@ -121,8 +134,11 @@ static void init_ddnatv_hook(void) { // environment is kept in. A program that had changed its environment (putenv, setenv) and passed it // to execv() before its first call into the hook handed the exec code a block that was freed by the // time it was read. -__attribute__((constructor(103))) static void init_ddnatv_hook_early(void) { +static void compact_loader_args(int argc, char **argv); + +__attribute__((constructor(103))) static void init_ddnatv_hook_early(int argc, char **argv) { init_ddnatv_hook(); + compact_loader_args(argc, argv); // The kernel names the process after what it executed, the rootfs ld.so: process monitors, and // the app's own checks of /proc/<pid>/comm (steam, wineserver), saw only "ld-linux-aarch64.so.1" const char *name = program_invocation_short_name; @@ -190,15 +206,10 @@ static void exe_from_cmdline(const char *cmdline_path, char *out, size_t outsz) } static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) { - const char *out_path = real_exe; - if (g_ddnatv_root[0] != '\0') { - size_t rlen = g_ddnatv_root_len; - if (strncmp(real_exe, g_ddnatv_root, rlen) == 0 && - (real_exe[rlen] == '/' || real_exe[rlen] == '\0')) { - out_path = real_exe + rlen; - if (out_path[0] == '\0') out_path = "/"; - } - } + char guest[PATH_MAX]; + char back[PATH_MAX]; + const char *out_path = guest_path_of_host_dir(real_exe, guest, sizeof(guest)); + if (!out_path || strcmp(rewrite_path_in_root(out_path, back, sizeof(back)), real_exe) != 0) out_path = real_exe; size_t len = strlen(out_path); size_t copy_len = (len < bufsiz) ? len : bufsiz; memcpy(buf, out_path, copy_len); @@ -224,27 +235,39 @@ static ssize_t (*real_readlinkat_fn(void))(int, const char *, char *, size_t) { return fn; } -static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) { - char path[64]; - snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid); - int fd = open(path, O_RDONLY | O_CLOEXEC); - if (fd < 0) return 0; - size_t cap = 65536, used = 0, keylen = strlen(key); - char *env = malloc(cap + 1); - ssize_t got; - while (env && (got = read(fd, env + used, cap - used)) > 0) { +static char *read_proc_file(const char *path, size_t *len, int *whole) { + *len = 0; + *whole = 0; + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return NULL; + size_t cap = 65536, used = 0; + char *text = malloc(cap + 1); + ssize_t got = 0; + while (text && (got = (ssize_t)syscall(SYS_read, fd, text + used, cap - used)) > 0) { used += (size_t)got; if (used == cap) { - char *bigger = cap < (8u << 20) ? realloc(env, cap * 2 + 1) : NULL; + char *bigger = cap < (8u << 20) ? realloc(text, cap * 2 + 1) : NULL; if (!bigger) break; - env = bigger; + text = bigger; cap *= 2; } } - close(fd); + syscall(SYS_close, fd); + if (!text) return NULL; + text[used] = '\0'; + *len = used; + *whole = got == 0; + return text; +} + +static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) { + char path[64]; + snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid); + size_t used, keylen = strlen(key); + int whole; + char *env = read_proc_file(path, &used, &whole); int found = 0; if (env) { - env[used] = '\0'; for (char *e = env; e < env + used; e += strlen(e) + 1) { if (strncmp(e, key, keylen) == 0 && e[keylen] == '=' && e[keylen + 1] != '\0') { ddnatv_copy_cstr(out, outsz, e + keylen + 1); @@ -257,6 +280,94 @@ static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) { return found; } +static int is_loader_option(const char *arg) { + return strcmp(arg, "--preload") == 0 || strcmp(arg, "--library-path") == 0 || strcmp(arg, "--argv0") == 0; +} + +static int is_exec_loader(const char *path) { + const char *base = strrchr(path, '/'); + return strcmp(base ? base + 1 : path, "libddexec.so") == 0; +} + +static size_t next_arg(const char *text, size_t pos) { + return pos + strlen(text + pos) + 1; +} + +static uintptr_t *execfn_entry(int argc, char **argv) { + if (argv[argc]) return NULL; + char **env = argv + argc + 1; + while (*env) env++; + for (uintptr_t *aux = (uintptr_t *)(env + 1); aux[0] != AT_NULL; aux += 2) { + if (aux[0] == AT_EXECFN) return aux + 1; + } + return NULL; +} + +static void compact_loader_args(int argc, char **argv) { + if (g_ddnatv_root[0] == '\0' || argc < 1 || !argv || !argv[0]) return; + size_t len; + int whole; + char *text = read_proc_file("/proc/self/cmdline", &len, &whole); + size_t *at = text && whole && len > 0 && text[len - 1] == '\0' ? malloc(sizeof(size_t) * (size_t)argc) : NULL; + size_t pos = 0, program = 0; + if (at && is_exec_loader(text)) { + pos = next_arg(text, pos); + if (pos < len) pos = next_arg(text, pos); + } + int ok = at && pos < len && is_ld_linux(text + pos), named = 0; + if (ok) pos = next_arg(text, pos); + while (ok && pos < len && is_loader_option(text + pos)) { + size_t value = next_arg(text, pos); + ok = value < len; + if (ok && strcmp(text + pos, "--argv0") == 0) { + at[0] = value; + named = 1; + } + if (ok) pos = next_arg(text, value); + } + int count = 0; + if (ok && named && pos < len) { + program = pos; + pos = next_arg(text, pos); + for (count = 1; pos < len && count < argc; count++) { + at[count] = pos; + pos = next_arg(text, pos); + } + } + char *base = count == argc && pos == len ? argv[0] - at[0] : NULL; + for (int i = 1; base && i < argc; i++) { + if (argv[i] != base + at[i]) base = NULL; + } + if (base && memcmp(base, text, len) != 0) base = NULL; + uintptr_t *execfn = base ? execfn_entry(argc, argv) : NULL; + char *execfn_text = NULL; + if (execfn && *execfn >= (uintptr_t)base && *execfn < (uintptr_t)base + len) { + execfn_text = strdup(text + (*execfn - (uintptr_t)base)); + if (!execfn_text) base = NULL; + } + if (base) { + char *old_name = argv[0]; + size_t name_len = strlen(old_name); + char *name = program_invocation_name, *short_name = program_invocation_short_name; + size_t used = 0; + for (int i = 0; i < argc; i++) { + size_t n = strlen(text + at[i]) + 1; + memcpy(base + used, text + at[i], n); + argv[i] = base + used; + used += n; + } + memset(base + used, 0, len - used); + if (name >= old_name && name <= old_name + name_len) program_invocation_name = argv[0] + (name - old_name); + if (short_name >= old_name && short_name <= old_name + name_len) { + program_invocation_short_name = argv[0] + (short_name - old_name); + } + if (g_real_exe[0] == '\0') ddnatv_copy_cstr(g_real_exe, sizeof(g_real_exe), text + program); + if (execfn_text) *execfn = (uintptr_t)execfn_text; + } + free(at); + free(text); +} + // Overlay filesystems report a different device to stat() than in /proc/<pid>/maps; the path, as the // kernel resolved it, then stands in for the device. static int proc_maps_file(pid_t pid, dev_t dev, ino_t ino, const char *resolved) { @@ -312,9 +423,7 @@ static ssize_t handle_proc_other_exe(const char *path, char *buf, size_t bufsiz) ssize_t n = real_readlinkat(AT_FDCWD, path, loader, sizeof(loader) - 1); if (n <= 0) return -1; loader[n] = '\0'; - const char *base = strrchr(loader, '/'); - base = base ? base + 1 : loader; - if (strcmp(base, "libddexec.so") != 0 && !is_ld_linux(loader)) return -1; + if (!is_exec_loader(loader) && !is_ld_linux(loader)) return -1; char real_exe[PATH_MAX] = ""; if (!proc_env_value(pid, "DDNATV_REAL_EXE", real_exe, sizeof(real_exe))) { @@ -350,8 +459,11 @@ static ssize_t handle_proc_exe_at(int dirfd, const char *pathname, char *buf, si static const char *rewrite_path(const char *path, char *buffer, size_t bufsize) { if (!path) return NULL; // Relative paths must NEVER be rewritten to rootfs root - if (path[0] != '/') return path; init_ddnatv_hook(); + if (path[0] != '/') { + const char *walked = map_at(AT_FDCWD, path, buffer, bufsize); + return walked ? walked : path; + } return rewrite_path_in_root(path, buffer, bufsize); } @@ -361,7 +473,7 @@ static const char *rewrite_path(const char *path, char *buffer, size_t bufsize) // followed in the guest's view first. The rootfs's own links were made relative already. static const char *rewrite_path_follow(const char *path, char *buffer, size_t bufsize) { if (!path) return NULL; - if (path[0] != '/') return path; + if (path[0] != '/') return rewrite_path(path, buffer, bufsize); init_ddnatv_hook(); int moved = 0; for (int i = 0; i < g_nbinds; i++) { diff --git a/tools/nativeguest/hook/sockets.c b/tools/nativeguest/hook/sockets.c index 2903505f9b..b4b12f8005 100644 --- a/tools/nativeguest/hook/sockets.c +++ b/tools/nativeguest/hook/sockets.c @@ -94,6 +94,13 @@ int listen(int sockfd, int backlog) { return ret; } +static void copy_unix_path(const struct sockaddr_un *sun, socklen_t addrlen, char *out) { + size_t max = addrlen - offsetof(struct sockaddr_un, sun_path); + if (max > sizeof(sun->sun_path)) max = sizeof(sun->sun_path); + memcpy(out, sun->sun_path, max); + out[max] = '\0'; +} + int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { static int (*orig_bind)(int, const struct sockaddr *, socklen_t) = NULL; if (!orig_bind) orig_bind = (int (*)(int, const struct sockaddr *, socklen_t))dlsym(RTLD_NEXT, "bind"); @@ -104,7 +111,9 @@ int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { struct sockaddr_un mod_sun; memset(&mod_sun, 0, sizeof(mod_sun)); mod_sun.sun_family = AF_UNIX; - rewrite_unix_socket_path(sun->sun_path, mod_sun.sun_path, sizeof(mod_sun.sun_path)); + char guest[sizeof(sun->sun_path) + 1]; + copy_unix_path(sun, addrlen, guest); + rewrite_unix_socket_path(guest, mod_sun.sun_path, sizeof(mod_sun.sun_path)); return orig_bind ? orig_bind(sockfd, (struct sockaddr *)&mod_sun, sizeof(mod_sun)) : -1; } } @@ -133,10 +142,7 @@ int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { memset(&mod_sun, 0, sizeof(mod_sun)); mod_sun.sun_family = AF_UNIX; char guest[sizeof(sun->sun_path) + 1]; - size_t max = addrlen - offsetof(struct sockaddr_un, sun_path); - if (max > sizeof(sun->sun_path)) max = sizeof(sun->sun_path); - memcpy(guest, sun->sun_path, max); - guest[max] = '\0'; + copy_unix_path(sun, addrlen, guest); char followed[PATH_MAX]; const char *path = guest[0] == '/' ? follow_guest_link(guest, followed, sizeof(followed)) : guest; rewrite_unix_socket_path(path, mod_sun.sun_path, sizeof(mod_sun.sun_path)); diff --git a/tools/nativeguest/hook/static_programs.c b/tools/nativeguest/hook/static_programs.c index 406fca0da9..0e10cd6ad7 100644 --- a/tools/nativeguest/hook/static_programs.c +++ b/tools/nativeguest/hook/static_programs.c @@ -212,9 +212,15 @@ static int read_elf_phdrs(int fd, uint16_t *machine, struct ddnatv_phdr *ph, int static int elf_is_go(int fd, const struct ddnatv_phdr *ph, int n) { for (int i = 0; i < n; i++) { if (ph[i].type != 4 /* PT_NOTE */ || ph[i].filesz < 16) continue; - unsigned char note[16]; - if (pread(fd, note, sizeof(note), (off_t)ph[i].offset) != sizeof(note)) continue; - if (rd32(note) == 4 && memcmp(note + 12, "Go\0\0", 4) == 0) return 1; + for (uint64_t at = 0; at + 16 <= ph[i].filesz;) { + unsigned char note[16]; + if (pread(fd, note, sizeof(note), (off_t)(ph[i].offset + at)) != (ssize_t)sizeof(note)) break; + uint32_t namesz = rd32(note), descsz = rd32(note + 4); + if (namesz == 4 && memcmp(note + 12, "Go\0\0", 4) == 0) return 1; + uint64_t next = at + 12 + (((uint64_t)namesz + 3) & ~3ull) + (((uint64_t)descsz + 3) & ~3ull); + if (next <= at || next > ph[i].filesz) break; + at = next; + } } return 0; } diff --git a/tools/packs/build.sh b/tools/packs/build.sh index 2b34c7fc6f..062fbd5270 100755 --- a/tools/packs/build.sh +++ b/tools/packs/build.sh @@ -11,6 +11,8 @@ linuxfs="$repo/app/src/main/assets/linuxfs/usr/local/lib" source "$here/tracking/release.env" # shellcheck source=butler/release.env source "$here/butler/release.env" +# shellcheck source=zstd/release.env +source "$here/zstd/release.env" work=$(mktemp -d) trap 'rm -rf "$work"' EXIT @@ -21,6 +23,22 @@ fetch() { bash "$here/fetch-verified.sh" "$@" } +zstd_version() { "$1" -V 2>/dev/null | sed -n 's/.* v\([0-9][0-9.]*\),.*/\1/p'; } +zstd=$(command -v zstd || true) +if [ -z "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then + zstd="${DROIDDECK_PACK_CACHE:-"$HOME/.cache/droiddeck-pack-inputs"}/zstd-$ZSTD_VERSION/zstd" + if [ ! -x "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then + fetch "https://github.com/facebook/zstd/releases/download/v$ZSTD_VERSION/zstd-$ZSTD_VERSION.tar.gz" \ + "$ZSTD_SHA256" "$work/zstd.tar.gz" + tar -xzf "$work/zstd.tar.gz" -C "$work" + make -s -C "$work/zstd-$ZSTD_VERSION" -j"$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)" zstd-release >/dev/null + mkdir -p "$(dirname "$zstd")" + install -m755 "$work/zstd-$ZSTD_VERSION/programs/zstd" "$zstd.part.$$" + mv -f "$zstd.part.$$" "$zstd" + fi +fi +[ "$(zstd_version "$zstd")" = "$ZSTD_VERSION" ] || { echo "packs need zstd $ZSTD_VERSION, $zstd is not it" >&2; exit 1; } + pack() { local name=$1 src=$2 shift 2 @@ -47,7 +65,7 @@ with tarfile.open(dest, "w", format=tarfile.USTAR_FORMAT) as tar: with open(path, "rb") as f: tar.addfile(info, f) EOF - zstd -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst" + "$zstd" -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst" echo "$name $(sha256 "$out/$name.tar.zst") $(wc -c < "$out/$name.tar.zst" | tr -d ' ')" } @@ -80,6 +98,7 @@ pack powervr "$repo/app/src/main/assets/hybris" runtime.tzst version.txt [ ! -f "$linuxfs/droiddeck-ubisoft/droiddeck-upc.exe" ] || pack ubisoft "$linuxfs/droiddeck-ubisoft" droiddeck-upc.exe [ ! -f "$linuxfs/droiddeck-rockstar/Launcher64.exe" ] || pack rockstar "$linuxfs/droiddeck-rockstar" Launcher32.exe Launcher64.exe [ ! -f "$linuxfs/droiddeck-dirt/ws2_32.dll" ] || pack dirt "$linuxfs/droiddeck-dirt" ws2_32.dll +[ ! -f "$linuxfs/droiddeck-epic/EpicGamesLauncher.exe" ] || pack epic "$linuxfs/droiddeck-epic" EpicGamesLauncher.exe mkdir "$work/butler" fetch "https://broth.itch.zone/butler/linux-arm64/${BUTLER_VERSION}/archive/default" \ diff --git a/tools/packs/zstd/release.env b/tools/packs/zstd/release.env new file mode 100644 index 0000000000..4f69b092bf --- /dev/null +++ b/tools/packs/zstd/release.env @@ -0,0 +1,2 @@ +ZSTD_VERSION=1.5.5 +ZSTD_SHA256=9c4396cc829cfae319a6e2615202e82aad41372073482fce286fac78646d3ee4 diff --git a/tools/pre_pr.sh b/tools/pre_pr.sh new file mode 100755 index 0000000000..dc493f7aac --- /dev/null +++ b/tools/pre_pr.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Runs the CI checks the fast deploy loop skips, limited to what this branch changes. +set -euo pipefail +repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +cd "${repo_root}" +base_ref=${1:-origin/main} + +git fetch -q origin main 2>/dev/null || echo "Could not fetch origin/main; comparing with the local copy." >&2 +base=$(git merge-base "${base_ref}" HEAD) +changed=() +while IFS= read -r path; do changed+=("${path}"); done \ + < <({ git diff --name-only "${base}"; git ls-files --others --exclude-standard; } | sort -u) +failed=() +run() { + local name=$1 + shift + echo "== ${name}" + if "$@"; then echo "ok: ${name}"; else failed+=("${name}"); echo "FAILED: ${name}"; fi +} + +run "human authorship" python3 tools/release/check_authorship.py "${base}..HEAD" +if [[ ${#changed[@]} -eq 0 ]]; then + [[ ${#failed[@]} -eq 0 ]] || exit 1 + echo "No files differ from ${base_ref}." + exit 0 +fi + +behind=$(git rev-list --count "HEAD..${base_ref}") +if [[ "${behind}" != 0 ]]; then + echo "== merge onto ${base_ref}" + if git merge-tree --write-tree HEAD "${base_ref}" >/dev/null 2>&1; then + echo "${behind} commits behind ${base_ref}. CI compiles the merge, so rebase before pushing if they touch code you use." + else + failed+=("merge onto ${base_ref}") + echo "FAILED: the branch conflicts with ${base_ref}; CI cannot merge it." + fi +fi + +app=0 settings=0 +tests=() python_tests=() +for path in "${changed[@]}"; do + case "${path}" in + app/src/main/*|app/build.gradle|gradle.properties|gradle/*) app=1 ;; + app/src/test/*Test.kt) app=1; [[ ! -f "${path}" ]] || tests+=("$(basename "${path}" .kt)") ;; + esac + case "${path}" in + */SettingsIndex.kt) settings=1 ;; + esac + if [[ "${path}" == app/src/main/java/*.kt && -f "${path}" ]]; then + while IFS= read -r test; do tests+=("$(basename "${test}" .kt)"); done \ + < <(find app/src/test -name "$(basename "${path}" .kt)*Test.kt") + fi + if [[ "${path}" == tools/tests/test_*.py ]]; then + [[ ! -f "${path}" ]] || python_tests+=("${path}") + elif [[ "${path}" == tools/* && "${path}" != tools/tests/* ]]; then + while IFS= read -r test; do python_tests+=("${test}"); done \ + < <(grep -lF "${path#tools/}" tools/tests/test_*.py 2>/dev/null || true) + fi +done +[[ "${settings}" == 0 ]] || tests+=(SettingsMapTest) + +if [[ "${app}" == 1 ]]; then + gradle_tasks=(:app:compileReleaseKotlin :app:lintVitalRelease) + test_args=() + if [[ ${#tests[@]} -gt 0 ]]; then + gradle_tasks+=(:app:testReleaseUnitTest) + for test in $(printf '%s\n' "${tests[@]}" | sort -u); do test_args+=(--tests "*.${test}"); done + fi + run "Kotlin, lint and $((${#test_args[@]} / 2)) unit test classes" \ + ./gradlew -q -PskipRust=true -PallowStaleRuntime=true "${gradle_tasks[@]}" ${test_args[@]+"${test_args[@]}"} +fi + +if [[ ${#python_tests[@]} -gt 0 ]]; then + modules=() + while IFS= read -r test; do modules+=("tools.tests.$(basename "${test}" .py)"); done \ + < <(printf '%s\n' "${python_tests[@]}" | sort -u) + run "${#modules[@]} Python test modules" python3 -m unittest "${modules[@]}" +fi + +if [[ ${#failed[@]} -gt 0 ]]; then + printf 'Failed: %s\n' "${failed[@]}" >&2 + exit 1 +fi +echo "Pre-PR checks passed. CI still runs the full suites." diff --git a/tools/quick_deploy.sh b/tools/quick_deploy.sh index 1166feaa6b..559670ce99 100755 --- a/tools/quick_deploy.sh +++ b/tools/quick_deploy.sh @@ -23,7 +23,8 @@ while IFS= read -r dir; do done < <(ls -d "${sdk_dir}"/build-tools/* 2>/dev/null | sort -rV) [[ -n "${build_tools}" ]] || { echo "No build-tools with aapt, zipalign and apksigner under ${sdk_dir}." >&2; exit 1; } -./gradlew -q -PallowStaleRuntime=true :app:assembleRelease +# Lint vital is most of an incremental build and CI runs it. +./gradlew -q -PallowStaleRuntime=true :app:assembleRelease -x lintVitalAnalyzeRelease ( cd "$(dirname "${signing_env}")" set -a; . "${signing_env}"; set +a diff --git a/tools/release/check_session_assets.py b/tools/release/check_session_assets.py index 940e722481..8a87e1af9d 100644 --- a/tools/release/check_session_assets.py +++ b/tools/release/check_session_assets.py @@ -1,6 +1,7 @@ from pathlib import Path import importlib.util import re +import shutil import sys from zipfile import ZipFile @@ -34,6 +35,14 @@ def source_assets(overlay=OVERLAY): return result +def stage(target=OVERLAY.parents[2] / 'app/src/main', overlay=OVERLAY): + for source, asset in source_assets(overlay).items(): + path = target / asset + if not path.is_file() or path.read_bytes() != source.read_bytes(): + path.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, path) + + def check(apk, overlay=OVERLAY): errors = check_extraction(overlay, SESSION_FILES.read_text()) if overlay == OVERLAY else [] with ZipFile(apk) as package: @@ -60,6 +69,9 @@ def check(apk, overlay=OVERLAY): if __name__ == '__main__': + if sys.argv[1:] == ['--stage']: + stage() + sys.exit() errors = check(sys.argv[1]) if errors: sys.exit('\n'.join(errors)) diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py index 4b02d29c26..4b2da89133 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -15,18 +15,18 @@ MANIFEST = Path('app/build/runtime-inputs.json') PACKS = Path('app/build/packs') PACKED = {'assets/linuxfs/usr/local/lib/droiddeck-xbox/': 'xbox', 'assets/linuxfs/usr/local/lib/droiddeck-comet/': 'comet', 'assets/linuxfs/usr/local/lib/droiddeck-ubisoft/': 'ubisoft', 'assets/linuxfs/usr/local/lib/droiddeck-rockstar/': 'rockstar', - 'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt', + 'assets/linuxfs/usr/local/lib/droiddeck-dirt/': 'dirt', 'assets/linuxfs/usr/local/lib/droiddeck-epic/': 'epic', 'assets/directaudio/': 'directaudio', 'assets/hybris/': 'powervr'} # DrWeb flags proot itself as Tool.Linux.Proot; the app runs the pack's copy through Android's linker. PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so')} # The loader is execve'd, which targetSdk 29+ allows only from the APK's native library directory. PROOT_LOADER = {'lib/arm64-v8a/libproot-loader.so': 'libproot-loader.so'} PACKED_LIBRARIES = ['lib/arm64-v8a/libopencv_java4.so', 'lib/arm64-v8a/libmediapipe_tasks_jni.so'] -PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt'] +PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'] SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst', 'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs', 'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env', - 'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh', + 'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/ubisoft-launcher', 'tools/rockstar-launcher', 'tools/epic-launcher', 'tools/components', 'tools/ci', 'tools/build_local.sh', 'tools/powervr', 'tools/hybris', 'tools/dxvk', 'tools/vulkan-wsi', 'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal', 'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh', @@ -48,20 +48,38 @@ def digest(path): return result.hexdigest() +def copied(root): + # Helper scripts are staged verbatim on every Gradle build and checked against the APK by + # check_session_assets.py, so they are neither preparation inputs nor prepared outputs. + if str(Path(__file__).resolve().parent) not in sys.path: + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from check_session_assets import OVERLAY, source_assets + found = source_assets() if root == ROOT else source_assets(root / OVERLAY.relative_to(ROOT)) + return {source.relative_to(root).as_posix(): 'app/src/main/' + asset for source, asset in found.items()} + + def sources(root): - files = [] + files, builds = [], set() + skipped = set(copied(root)) for name in SOURCE_PATHS: path = root / name files.extend(path.rglob('*') if path.is_dir() else [path]) + if path.is_dir(): + builds.update(manifest.parent / 'target' for manifest in path.rglob('Cargo.toml')) return {path.relative_to(root).as_posix(): digest(path) for path in sorted(set(files)) - if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc'} + if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc' + and path.relative_to(root).as_posix() not in skipped + and not any(build in path.parents for build in builds)} def outputs(root): result = {} + skipped = set(copied(root).values()) for tree in ['linuxfs', 'directaudio', 'droiddeck-esync', 'desktop-removal', 'hybris']: base = root / 'app/src/main/assets' / tree for path in base.rglob('*'): + if path.relative_to(root).as_posix() in skipped: + continue if path.is_file() and not any(part.startswith('.') for part in path.relative_to(base).parts): result['assets/' + tree + '/' + path.relative_to(base).as_posix()] = path.relative_to(root).as_posix() for library in ['libproot.so', 'libproot-loader.so', 'libdirectaudiorelay.so']: @@ -81,8 +99,7 @@ def required(): for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']] paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libddsession.so', 'libddfastpath.so', 'libddnatv-hook.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard', - 'usr/local/bin/droiddeck-gog-maintenance', - 'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime', + 'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime', 'usr/local/lib/droiddeck/dwarfsextract', 'usr/local/lib/droiddeck-pipewire.tzst']] for arch in ['x86_64', 'i386']: paths += ['assets/linuxfs/' + arch + '/' + lib for lib in ['libfakeinput.so', 'libddsession.so']] @@ -175,6 +192,10 @@ def verify(root=ROOT, stale_sources_ok=False): raise ValueError('Runtime inputs have not been prepared. Run tools/build_local.sh.') if data.get('version') != 1: raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.') + copies = copied(root) + data['sources'] = {name: value for name, value in (data.get('sources') or {}).items() if name not in copies} + data['outputs'] = {name: output for name, output in (data.get('outputs') or {}).items() + if output.get('path') not in copies.values()} current = sources(root) if data.get('sources') != current: if not stale_sources_ok: @@ -192,6 +213,11 @@ def verify(root=ROOT, stale_sources_ok=False): raise ValueError('Missing or changed runtime input: ' + name + '. Run tools/build_local.sh.') if outputs(root) != {name: output['path'] for name, output in data['outputs'].items()}: raise ValueError('Runtime file set changed. Run tools/build_local.sh.') + for source, asset in copies.items(): + path = root / asset + if not path.is_file() or path.read_bytes() != (root / source).read_bytes(): + raise ValueError(asset + ' is not a current copy of ' + source + + '. Run python3 tools/release/check_session_assets.py --stage.') return data @@ -227,7 +253,7 @@ def windows_binaries(package): def check_apk(apk, root=ROOT): data = verify(root) packs = {name: pack_digests(root, name) for name in PACK_NAMES - if name not in ('ubisoft', 'rockstar', 'dirt') or (root / PACKS / (name + '.tar.zst')).is_file()} + if name not in ('ubisoft', 'rockstar', 'dirt', 'epic') or (root / PACKS / (name + '.tar.zst')).is_file()} for name, rel in PROOT_LOADER.items(): if packs['proot'].get(rel) != data['outputs'][name]['sha256']: raise ValueError('Add-on pack proot is missing or has a stale ' + rel) diff --git a/tools/rockstar-launcher/build-container.sh b/tools/rockstar-launcher/build-container.sh new file mode 100755 index 0000000000..bee7c48774 --- /dev/null +++ b/tools/rockstar-launcher/build-container.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Builds the Rockstar launcher in a container, on the host's own architecture. Rust's +# i686-pc-windows-gnu target needs a DWARF2 mingw; Homebrew's i686 mingw uses SJLJ and fails to link. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +repo=$(cd "$here/../.." && pwd) +out=${1:?usage: build-container.sh <output directory>} +. "$repo/tools/docker_platform.sh" +cache=${DROIDDECK_BUILD_CACHE:-$HOME/.cache/droiddeck-build}/rockstar-container +mkdir -p "$out" "$cache/cargo" "$cache/target" +out=$(cd "$out" && pwd) +image=droiddeck-rockstar-build:v2-${docker_platform#linux/} + +if ! docker image inspect "$image" >/dev/null 2>&1; then + docker build --platform "$docker_platform" -t "$image" - <<'EOF' +FROM public.ecr.aws/docker/library/ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive RUSTUP_HOME=/opt/rustup CARGO_HOME=/opt/cargo PATH=/opt/cargo/bin:$PATH +RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates curl gcc libc6-dev \ + gcc-mingw-w64-i686-posix gcc-mingw-w64-x86-64-posix >/dev/null +RUN curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --default-toolchain stable \ + -t i686-pc-windows-gnu -t x86_64-pc-windows-gnu && chmod -R a+rX /opt/rustup /opt/cargo +EOF +fi + +docker run --rm --platform "$docker_platform" --user "$(id -u):$(id -g)" \ + -e CARGO_HOME=/cache/cargo -e CARGO_TARGET_DIR=/cache/target -e HOME=/tmp \ + -v "$repo:/src" -v "$out:/out" -v "$cache:/cache" -w /src "$image" \ + bash tools/rockstar-launcher/build.sh /out diff --git a/tools/seed_worktree.sh b/tools/seed_worktree.sh index e5079e7111..45bbc56bed 100755 --- a/tools/seed_worktree.sh +++ b/tools/seed_worktree.sh @@ -10,14 +10,19 @@ paths=( app/build/packs app/build/localPackAssets app/build/packs-local-aside app/build/quest-inputs app/build/rustJniLibs app/build/vkbridgeJniLibs app/src/main/assets/directaudio app/src/main/assets/droiddeck-esync app/src/main/assets/linuxfs - app/src/main/assets/desktop-removal + app/src/main/assets/desktop-removal app/src/main/assets/hybris app/src/main/jniLibs/arm64-v8a app/src/main/rust/stores/target ) for path in "${paths[@]}"; do [[ -e "${main_root}/${path}" ]] || continue if [[ -d "${main_root}/${path}" ]]; then - [[ -z "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]] || continue + if [[ -n "$(ls -A "${repo_root}/${path}" 2>/dev/null)" ]]; then + # A directory holding only tracked files (jniLibs) still lacks every built library. + [[ -z "$(git -C "${repo_root}" ls-files --others -- "${path}")" ]] || continue + cp -Rn "${main_root}/${path}/." "${repo_root}/${path}/" + continue + fi mkdir -p "$(dirname "${repo_root}/${path}")" staged=$(mktemp -d "${repo_root}/${path}.seed.XXXXXX") trap 'rm -rf "${staged}"' EXIT diff --git a/tools/tests/mali_compat_layer_test.c b/tools/tests/mali_compat_layer_test.c index 640460685c..9b29e5c734 100644 --- a/tools/tests/mali_compat_layer_test.c +++ b/tools/tests/mali_compat_layer_test.c @@ -21,6 +21,8 @@ static VkPipelineColorBlendAttachmentState driver_attachments[4]; static uint32_t driver_attachment_count; static VkColorBlendEquationEXT driver_equations[4]; static uint32_t driver_equation_count; +static VkCompareOp driver_depth_op, driver_pipeline_depth_op; +static VkBool32 driver_depth_test; #define MAIN 1 #define VOID 2 @@ -182,6 +184,25 @@ static void test_spirv(const char *directory) assert(!spirv_strip_dual_source(truncated, 5, &out)); } +static void test_handle_map_null_key(void) +{ + struct handle_map map = {0}; + int first, second; + map_put(&map, 0x1000, &first); + map_put(&map, 0x2000, &second); + for (int i = 0; i < 1000; i++) + assert(!map_remove(&map, 0)); + map_put(&map, 0, &first); + assert(map.count == 2 && !map_get(&map, 0)); + for (uint64_t key = 1; key <= 30; key++) { + map_put(&map, 0x100000 + key, &first); + assert(map_remove(&map, 0x100000 + key) == &first); + } + assert(map.count == 2 && map.capacity == 64); + assert(map_get(&map, 0x1000) == &first && map_get(&map, 0x2000) == &second); + map_free(&map); +} + static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator, VkInstance *instance) { @@ -286,10 +307,27 @@ static VkResult VKAPI_CALL mock_create_graphics_pipelines(VkDevice device, VkPip const VkShaderModuleCreateInfo *module = infos[0].pStages[0].pNext; assert(module && module->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO); capture_code(module->pCode, module->codeSize); + if (infos[0].pDepthStencilState) + driver_pipeline_depth_op = infos[0].pDepthStencilState->depthCompareOp; pipelines[0] = (VkPipeline)0x2000; return VK_SUCCESS; } +static VkResult VKAPI_CALL mock_begin_command_buffer(VkCommandBuffer cmd, const VkCommandBufferBeginInfo *info) +{ + return VK_SUCCESS; +} + +static void VKAPI_CALL mock_set_depth_test(VkCommandBuffer cmd, VkBool32 enable) +{ + driver_depth_test = enable; +} + +static void VKAPI_CALL mock_set_depth_op(VkCommandBuffer cmd, VkCompareOp op) +{ + driver_depth_op = op; +} + static void VKAPI_CALL mock_set_blend_equation(VkCommandBuffer cmd, uint32_t first, uint32_t count, const VkColorBlendEquationEXT *equations) { @@ -323,6 +361,9 @@ static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gdpa(VkDevice device, const MOCK("vkDestroyShaderModule", mock_destroy_shader_module); MOCK("vkCreateGraphicsPipelines", mock_create_graphics_pipelines); MOCK("vkCmdSetColorBlendEquationEXT", mock_set_blend_equation); + MOCK("vkBeginCommandBuffer", mock_begin_command_buffer); + MOCK("vkCmdSetDepthTestEnable", mock_set_depth_test); + MOCK("vkCmdSetDepthCompareOp", mock_set_depth_op); return NULL; } @@ -461,9 +502,75 @@ static void test_capable_device(void) destroy_device(device); } +static void create_depth_pipeline(VkDevice device, const VkPipelineDepthStencilStateCreateInfo *depth, + const VkDynamicState *dynamic, uint32_t dynamic_count) +{ + struct spirv plain; + fragment_shader(&plain, 0x00010000, false); + VkShaderModuleCreateInfo module = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, + plain.n * sizeof(uint32_t), plain.w}; + VkPipelineShaderStageCreateInfo stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, &module, 0, + VK_SHADER_STAGE_FRAGMENT_BIT, VK_NULL_HANDLE, "main", NULL}; + VkPipelineColorBlendStateCreateInfo blend = {VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0, + VK_FALSE, VK_LOGIC_OP_COPY, 1, &plain_attachment, {0}}; + VkPipelineDynamicStateCreateInfo states = {VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, NULL, 0, + dynamic_count, dynamic}; + VkGraphicsPipelineCreateInfo info = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 1, + .pStages = &stage, .pDepthStencilState = depth, .pColorBlendState = &blend, + .pDynamicState = dynamic_count ? &states : NULL}; + VkPipeline pipeline; + driver_pipeline_depth_op = VK_COMPARE_OP_MAX_ENUM; + PFN_vkCreateGraphicsPipelines create = + (PFN_vkCreateGraphicsPipelines)layer_gdpa(device, "vkCreateGraphicsPipelines"); + assert(create(device, VK_NULL_HANDLE, 1, &info, NULL, &pipeline) == VK_SUCCESS); +} + +static void test_depth_compare_op(void) +{ + VkDevice device; + VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE}; + assert(create_device((VkPhysicalDevice)&mock_lacking, NULL, &enabled, &device) == VK_SUCCESS); + PFN_vkBeginCommandBuffer begin = (PFN_vkBeginCommandBuffer)layer_gdpa(device, "vkBeginCommandBuffer"); + PFN_vkCmdSetDepthTestEnable set_test = + (PFN_vkCmdSetDepthTestEnable)layer_gdpa(device, "vkCmdSetDepthTestEnable"); + PFN_vkCmdSetDepthCompareOp set_op = (PFN_vkCmdSetDepthCompareOp)layer_gdpa(device, "vkCmdSetDepthCompareOp"); + assert((PFN_vkVoidFunction)set_test != (PFN_vkVoidFunction)mock_set_depth_test); + assert((PFN_vkVoidFunction)set_op != (PFN_vkVoidFunction)mock_set_depth_op); + + VkCommandBuffer cmd = (VkCommandBuffer)&mock_command_buffer; + VkCommandBufferBeginInfo begin_info = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + assert(begin(cmd, &begin_info) == VK_SUCCESS); + set_op(cmd, VK_COMPARE_OP_LESS); + assert(driver_depth_op == VK_COMPARE_OP_LESS); + set_test(cmd, VK_FALSE); + assert(!driver_depth_test && driver_depth_op == VK_COMPARE_OP_ALWAYS); + set_op(cmd, VK_COMPARE_OP_NEVER); + assert(driver_depth_op == VK_COMPARE_OP_ALWAYS); + set_test(cmd, VK_TRUE); + assert(driver_depth_test && driver_depth_op == VK_COMPARE_OP_NEVER); + set_test(cmd, VK_FALSE); + assert(begin(cmd, &begin_info) == VK_SUCCESS); + set_op(cmd, VK_COMPARE_OP_GREATER); + assert(driver_depth_op == VK_COMPARE_OP_GREATER); + + VkPipelineDepthStencilStateCreateInfo depth = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, + .depthCompareOp = VK_COMPARE_OP_NEVER}; + create_depth_pipeline(device, &depth, NULL, 0); + assert(driver_pipeline_depth_op == VK_COMPARE_OP_ALWAYS && depth.depthCompareOp == VK_COMPARE_OP_NEVER); + const VkDynamicState dynamic[] = {VK_DYNAMIC_STATE_DEPTH_COMPARE_OP}; + create_depth_pipeline(device, &depth, dynamic, 1); + assert(driver_pipeline_depth_op == VK_COMPARE_OP_NEVER); + depth.depthTestEnable = VK_TRUE; + depth.depthCompareOp = VK_COMPARE_OP_LESS; + create_depth_pipeline(device, &depth, NULL, 0); + assert(driver_pipeline_depth_op == VK_COMPARE_OP_LESS); + destroy_device(device); +} + int main(int argc, char **argv) { test_spirv(argc > 1 ? argv[1] : NULL); + test_handle_map_null_key(); setenv("WINEPREFIX", "/nonexistent", 1); unsetenv("DROIDDECK_MALI_COMPAT"); @@ -482,6 +589,7 @@ int main(int argc, char **argv) test_lacking_device(); test_capable_device(); + test_depth_compare_op(); ((PFN_vkDestroyInstance)layer_gipa(instance, "vkDestroyInstance"))(instance, NULL); free(driver_code); diff --git a/tools/tests/mali_compat_spirv_test.c b/tools/tests/mali_compat_spirv_test.c new file mode 100644 index 0000000000..732251f1fe --- /dev/null +++ b/tools/tests/mali_compat_spirv_test.c @@ -0,0 +1,548 @@ +#include "mali_compat.h" + +#include <spirv/unified1/spirv.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define OPCODE(word) ((word) & 0xffffu) +#define LENGTH(word) ((word) >> 16) + +static const uint32_t newer[] = { + 0x07230203, 0x00010600, 0x00070000, 0x0000000a, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, + 0x00000000, 0x00000001, 0x0007000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, + 0x00000003, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, + 0x00020013, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040020, 0x00000006, 0x00000003, + 0x00000005, 0x0004003b, 0x00000006, 0x00000002, 0x00000003, 0x00040020, 0x00000007, 0x00000006, + 0x00000005, 0x0004003b, 0x00000007, 0x00000003, 0x00000006, 0x00030021, 0x00000008, 0x00000004, + 0x00050036, 0x00000004, 0x00000001, 0x00000000, 0x00000008, 0x000200f8, 0x00000009, 0x00011140, + 0x00010038, +}; +static const size_t newer_count = sizeof(newer) / sizeof(uint32_t); + +static const uint32_t readonly_parameter[] = { + SpvMagicNumber, 0x00010600, 0, 13, 0, + (2u << 16) | SpvOpCapability, SpvCapabilityShader, + (3u << 16) | SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, + (5u << 16) | SpvOpEntryPoint, SpvExecutionModelFragment, 7, 0x6e69616d, 0, + (3u << 16) | SpvOpExecutionMode, 7, SpvExecutionModeOriginUpperLeft, + (3u << 16) | SpvOpDecorate, 3, SpvDecorationBlock, + (5u << 16) | SpvOpMemberDecorate, 3, 0, SpvDecorationOffset, 0, + (3u << 16) | SpvOpDecorate, 10, SpvDecorationNonWritable, + (4u << 16) | SpvOpDecorate, 12, SpvDecorationDescriptorSet, 0, + (4u << 16) | SpvOpDecorate, 12, SpvDecorationBinding, 0, + (2u << 16) | SpvOpTypeVoid, 1, + (3u << 16) | SpvOpTypeFloat, 2, 32, + (3u << 16) | SpvOpTypeStruct, 3, 2, + (4u << 16) | SpvOpTypePointer, 4, SpvStorageClassStorageBuffer, 3, + (4u << 16) | SpvOpVariable, 4, 12, SpvStorageClassStorageBuffer, + (3u << 16) | SpvOpTypeFunction, 5, 1, + (4u << 16) | SpvOpTypeFunction, 6, 1, 4, + (5u << 16) | SpvOpFunction, 1, 7, 0, 5, + (2u << 16) | SpvOpLabel, 8, + (1u << 16) | SpvOpReturn, + (1u << 16) | SpvOpFunctionEnd, + (5u << 16) | SpvOpFunction, 1, 9, 0, 6, + (3u << 16) | SpvOpFunctionParameter, 4, 10, + (2u << 16) | SpvOpLabel, 11, + (1u << 16) | SpvOpReturn, + (1u << 16) | SpvOpFunctionEnd, +}; + +static const uint32_t older[] = { + 0x07230203, 0x00010300, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, + 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013, + 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, 0x00000003, 0x00000004, + 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006, 0x00000003, 0x00050036, + 0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007, 0x000100fd, 0x00010038, +}; +static const size_t older_count = sizeof(older) / sizeof(uint32_t); + +static const uint32_t capability[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x00000046, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, + 0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, + 0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, + 0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006, + 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007, + 0x000100fd, 0x00010038, +}; +static const size_t capability_count = sizeof(capability) / sizeof(uint32_t); + +static const uint32_t memory[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000008, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x000014e1, 0x0003000e, 0x00000000, 0x00000003, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, + 0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, + 0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, + 0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x00030021, 0x00000006, + 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x00000006, 0x000200f8, 0x00000007, + 0x000100fd, 0x00010038, +}; +static const size_t memory_count = sizeof(memory) / sizeof(uint32_t); + +static const uint32_t zinklike[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000017, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, + 0x00000000, 0x00000001, 0x0007000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, + 0x00000003, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, + 0x00020013, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040015, 0x00000006, 0x00000020, + 0x00000001, 0x00040017, 0x00000007, 0x00000005, 0x00000004, 0x0003001e, 0x00000008, 0x00000007, + 0x00040020, 0x00000009, 0x00000003, 0x00000005, 0x0004003b, 0x00000009, 0x00000002, 0x00000003, + 0x00040020, 0x0000000a, 0x00000006, 0x00000008, 0x00040020, 0x0000000b, 0x00000007, 0x00000008, + 0x0004003b, 0x0000000a, 0x00000003, 0x00000006, 0x00040020, 0x0000000c, 0x00000006, 0x00000005, + 0x00040020, 0x0000000d, 0x00000007, 0x00000005, 0x0004002b, 0x00000005, 0x0000000e, 0x3f800000, + 0x0004002b, 0x00000006, 0x0000000f, 0x00000000, 0x00030021, 0x00000010, 0x00000004, 0x00050036, + 0x00000004, 0x00000001, 0x00000000, 0x00000010, 0x000200f8, 0x00000011, 0x0004003b, 0x0000000b, + 0x00000012, 0x00000007, 0x00060041, 0x0000000d, 0x00000013, 0x00000012, 0x0000000f, 0x0000000f, + 0x0003003e, 0x00000013, 0x0000000e, 0x0004003d, 0x00000005, 0x00000014, 0x00000013, 0x00070050, + 0x00000007, 0x00000015, 0x00000014, 0x00000014, 0x00000014, 0x00000014, 0x00040041, 0x00000009, + 0x00000016, 0x00000002, 0x0003003e, 0x00000016, 0x00000014, 0x000100fd, 0x00010038, +}; +static const size_t zinklike_count = sizeof(zinklike) / sizeof(uint32_t); + +static const uint32_t nonuniform[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000009, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x000014b5, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, + 0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, + 0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, + 0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x0004002b, 0x00000004, + 0x00000006, 0x3f800000, 0x00030021, 0x00000007, 0x00000003, 0x00050036, 0x00000003, 0x00000001, + 0x00000000, 0x00000007, 0x000200f8, 0x00000008, 0x0003003e, 0x00000002, 0x00000006, 0x000100fd, + 0x00010038, +}; +static const size_t nonuniform_count = sizeof(nonuniform) / sizeof(uint32_t); + +static const uint32_t nonuniform_extension[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000009, 0x00000000, 0x00020011, 0x00000001, 0x00020011, + 0x000014b5, 0x0008000a, 0x5f565053, 0x5f545845, 0x63736564, 0x74706972, 0x695f726f, 0x7865646e, + 0x00676e69, 0x0003000e, 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, + 0x00000000, 0x00000002, 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, + 0x00000000, 0x00020013, 0x00000003, 0x00030016, 0x00000004, 0x00000020, 0x00040020, 0x00000005, + 0x00000003, 0x00000004, 0x0004003b, 0x00000005, 0x00000002, 0x00000003, 0x0004002b, 0x00000004, + 0x00000006, 0x3f800000, 0x00030021, 0x00000007, 0x00000003, 0x00050036, 0x00000003, 0x00000001, + 0x00000000, 0x00000007, 0x000200f8, 0x00000008, 0x0003003e, 0x00000002, 0x00000006, 0x000100fd, + 0x00010038, +}; +static const size_t nonuniform_extension_count = sizeof(nonuniform_extension) / sizeof(uint32_t); + +static const uint32_t select_struct[] = { + 0x07230203, 0x00010600, 0x00070000, 0x00000011, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, + 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013, + 0x00000003, 0x00020014, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x0004001e, 0x00000006, + 0x00000005, 0x00000005, 0x00040020, 0x00000007, 0x00000003, 0x00000005, 0x0004003b, 0x00000007, + 0x00000002, 0x00000003, 0x0004002b, 0x00000005, 0x00000008, 0x3f800000, 0x0004002b, 0x00000005, + 0x00000009, 0x00000000, 0x00030029, 0x00000004, 0x0000000a, 0x0005002c, 0x00000006, 0x0000000b, + 0x00000008, 0x00000009, 0x0005002c, 0x00000006, 0x0000000c, 0x00000009, 0x00000008, 0x00030021, + 0x0000000d, 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, 0x0000000d, 0x000200f8, + 0x0000000e, 0x000600a9, 0x00000006, 0x0000000f, 0x0000000a, 0x0000000b, 0x0000000c, 0x00050051, + 0x00000005, 0x00000010, 0x0000000f, 0x00000000, 0x0003003e, 0x00000002, 0x00000010, 0x000100fd, + 0x00010038, +}; +static const size_t select_struct_count = sizeof(select_struct) / sizeof(uint32_t); + +static const uint32_t select_scalar[] = { + 0x07230203, 0x00010600, 0x00070000, 0x0000000d, 0x00000000, 0x00020011, 0x00000001, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000001, 0x6e69616d, 0x00000000, 0x00000002, + 0x00030010, 0x00000001, 0x00000007, 0x00040047, 0x00000002, 0x0000001e, 0x00000000, 0x00020013, + 0x00000003, 0x00020014, 0x00000004, 0x00030016, 0x00000005, 0x00000020, 0x00040020, 0x00000006, + 0x00000003, 0x00000005, 0x0004003b, 0x00000006, 0x00000002, 0x00000003, 0x0004002b, 0x00000005, + 0x00000007, 0x3f800000, 0x0004002b, 0x00000005, 0x00000008, 0x00000000, 0x00030029, 0x00000004, + 0x00000009, 0x00030021, 0x0000000a, 0x00000003, 0x00050036, 0x00000003, 0x00000001, 0x00000000, + 0x0000000a, 0x000200f8, 0x0000000b, 0x000600a9, 0x00000005, 0x0000000c, 0x00000009, 0x00000007, + 0x00000008, 0x0003003e, 0x00000002, 0x0000000c, 0x000100fd, 0x00010038, +}; +static const size_t select_scalar_count = sizeof(select_scalar) / sizeof(uint32_t); + +static const uint32_t nonsemantic[] = { + 0x07230203, 0x00010600, 0x00070000, 0x0000000c, 0x00000000, 0x00020011, 0x00000001, 0x0008000b, + 0x00000001, 0x536e6f4e, 0x6e616d65, 0x2e636974, 0x75626544, 0x69725067, 0x0066746e, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000002, 0x6e69616d, 0x00000000, 0x00000003, + 0x00030010, 0x00000002, 0x00000007, 0x00030007, 0x00000004, 0x00000078, 0x00040047, 0x00000003, + 0x0000001e, 0x00000000, 0x00020013, 0x00000005, 0x00030016, 0x00000006, 0x00000020, 0x00040020, + 0x00000007, 0x00000003, 0x00000006, 0x0004003b, 0x00000007, 0x00000003, 0x00000003, 0x0004002b, + 0x00000006, 0x00000008, 0x3f800000, 0x00030021, 0x00000009, 0x00000005, 0x00050036, 0x00000005, + 0x00000002, 0x00000000, 0x00000009, 0x000200f8, 0x0000000a, 0x0006000c, 0x00000005, 0x0000000b, + 0x00000001, 0x00000001, 0x00000004, 0x0003003e, 0x00000003, 0x00000008, 0x000100fd, 0x00010038, +}; +static const size_t nonsemantic_count = sizeof(nonsemantic) / sizeof(uint32_t); + +static const uint32_t nonsemantic_extension[] = { + 0x07230203, 0x00010600, 0x00070000, 0x0000000c, 0x00000000, 0x00020011, 0x00000001, 0x0008000a, + 0x5f565053, 0x5f52484b, 0x5f6e6f6e, 0x616d6573, 0x6369746e, 0x666e695f, 0x0000006f, 0x0008000b, + 0x00000001, 0x536e6f4e, 0x6e616d65, 0x2e636974, 0x75626544, 0x69725067, 0x0066746e, 0x0003000e, + 0x00000000, 0x00000001, 0x0006000f, 0x00000004, 0x00000002, 0x6e69616d, 0x00000000, 0x00000003, + 0x00030010, 0x00000002, 0x00000007, 0x00030007, 0x00000004, 0x00000078, 0x00040047, 0x00000003, + 0x0000001e, 0x00000000, 0x00020013, 0x00000005, 0x00030016, 0x00000006, 0x00000020, 0x00040020, + 0x00000007, 0x00000003, 0x00000006, 0x0004003b, 0x00000007, 0x00000003, 0x00000003, 0x0004002b, + 0x00000006, 0x00000008, 0x3f800000, 0x00030021, 0x00000009, 0x00000005, 0x00050036, 0x00000005, + 0x00000002, 0x00000000, 0x00000009, 0x000200f8, 0x0000000a, 0x0006000c, 0x00000005, 0x0000000b, + 0x00000001, 0x00000001, 0x00000004, 0x0003003e, 0x00000003, 0x00000008, 0x000100fd, 0x00010038, +}; +static const size_t nonsemantic_extension_count = sizeof(nonsemantic_extension) / sizeof(uint32_t); + +static int failures; + +static void check(int condition, const char *what) +{ + if (!condition) { + printf("FAIL: %s\n", what); + failures++; + } +} + +static size_t count_opcodes(const uint32_t *words, size_t count, uint32_t opcode) +{ + size_t found = 0; + for (size_t i = 5; i < count; i += LENGTH(words[i])) { + if (OPCODE(words[i]) == opcode) + found++; + } + return found; +} + +static size_t interface_size(const uint32_t *words, size_t count) +{ + for (size_t i = 5; i < count; i += LENGTH(words[i])) { + if (OPCODE(words[i]) != SpvOpEntryPoint) + continue; + size_t length = LENGTH(words[i]); + size_t name = 3; + while (name < length) { + uint32_t word = words[i + name]; + if (!(word & 0xff) || !(word & 0xff00) || !(word & 0xff0000) || !(word & 0xff000000)) + break; + name++; + } + return length - (name + 1); + } + return 0; +} + +static void write_module(const char *path, const struct spirv_code *code) +{ + FILE *out = fopen(path, "wb"); + if (!out) { + printf("FAIL: %s cannot be written\n", path); + failures++; + return; + } + fwrite(code->words, sizeof(uint32_t), code->count, out); + fclose(out); +} + +static struct device test_device; +static int failed_allocations; +static bool fail_allocations; +static int driver_calls; +static bool chain_was_layer_owned; +static VkStructureType first_link; +static uint32_t driver_version; +static uint32_t driver_subgroup_size; + +void *test_calloc(size_t count, size_t size) +{ + if (fail_allocations) { + failed_allocations++; + return NULL; + } + if (size && count > SIZE_MAX / size) + return NULL; + size_t bytes = count * size; + void *memory = malloc(bytes > 0 ? bytes : 1); + if (memory) + memset(memory, 0, bytes); + return memory; +} + +struct device *device_from_handle(const void *dispatchable) +{ + return &test_device; +} + +void layer_log(const char *format, ...) +{ +} + +void *map_get(const struct handle_map *map, uint64_t key) +{ + return NULL; +} + +void map_put(struct handle_map *map, uint64_t key, void *value) +{ +} + +void *map_remove(struct handle_map *map, uint64_t key) +{ + return NULL; +} + +static void read_stage(const VkPipelineShaderStageCreateInfo *stage, const void *app_chain) +{ + driver_calls++; + chain_was_layer_owned = stage->pNext != app_chain; + first_link = stage->pNext ? ((const VkBaseInStructure *)stage->pNext)->sType : VK_STRUCTURE_TYPE_MAX_ENUM; + driver_version = 0; + driver_subgroup_size = 0; + for (const VkBaseInStructure *s = stage->pNext; s; s = s->pNext) { + if (s->sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO) + driver_subgroup_size = ((const VkPipelineShaderStageRequiredSubgroupSizeCreateInfo *)s)->requiredSubgroupSize; + if (s->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) { + const VkShaderModuleCreateInfo *info = (const VkShaderModuleCreateInfo *)s; + driver_version = spirv_version(info->pCode, info->codeSize / sizeof(uint32_t)); + } + } +} + +static const void *expected_chain; + +static VkResult VKAPI_CALL driver_compute(VkDevice device, VkPipelineCache cache, uint32_t count, + const VkComputePipelineCreateInfo *infos, + const VkAllocationCallbacks *allocator, VkPipeline *pipelines) +{ + read_stage(&infos[0].stage, expected_chain); + return VK_SUCCESS; +} + +static VkResult VKAPI_CALL driver_graphics(VkDevice device, VkPipelineCache cache, uint32_t count, + const VkGraphicsPipelineCreateInfo *infos, + const VkAllocationCallbacks *allocator, VkPipeline *pipelines) +{ + read_stage(&infos[0].pStages[0], expected_chain); + return VK_SUCCESS; +} + +static const VkShaderModuleCreateInfo app_module = { + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = sizeof(newer), + .pCode = newer, +}; + +static const VkPipelineShaderStageRequiredSubgroupSizeCreateInfo app_subgroup = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO, + .pNext = &app_module, + .requiredSubgroupSize = 16, +}; + +static const VkApplicationInfo app_unknown = { + .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .pNext = &app_module, +}; + +static const VkPipelineShaderStageCreateInfo app_fragment = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .pNext = &app_subgroup, + .stage = VK_SHADER_STAGE_FRAGMENT_BIT, + .pName = "main", +}; + +static void check_pipelines(void) +{ + VkDevice device = (VkDevice)&test_device; + VkPipeline pipeline = VK_NULL_HANDLE; + pthread_mutex_init(&test_device.lock, NULL); + test_device.CreateComputePipelines = driver_compute; + test_device.CreateGraphicsPipelines = driver_graphics; + + VkComputePipelineCreateInfo compute = { + .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, + .stage = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .pNext = &app_subgroup, + .stage = VK_SHADER_STAGE_COMPUTE_BIT, + .pName = "main"}, + }; + expected_chain = &app_subgroup; + check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS, + "a compute pipeline with inline code behind another structure is created"); + check(chain_was_layer_owned, "the compute stage gets the layer's own chain"); + check(first_link == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO, + "the compute stage keeps its chain order"); + check(driver_subgroup_size == 16, "the compute stage keeps its required subgroup size"); + check(driver_version == 0x00010300u, "the compute stage's inline code reaches the driver as SPIR-V 1.3"); + check(app_module.pCode == newer && app_module.codeSize == sizeof(newer), + "the application's shader module create info is untouched"); + check(compute.stage.pNext == &app_subgroup, "the application's compute stage is untouched"); + + compute.stage.pNext = &app_module; + expected_chain = &app_module; + check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS, + "a compute pipeline with inline code first in its chain is created"); + check(chain_was_layer_owned && driver_version == 0x00010300u, + "inline code first in the chain reaches the driver as SPIR-V 1.3"); + + compute.stage.pNext = &app_unknown; + expected_chain = &app_unknown; + check(CreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute, NULL, &pipeline) == VK_SUCCESS, + "a compute pipeline behind an unknown structure is created"); + check(!chain_was_layer_owned && driver_version == 0x00010600u, + "a chain the layer cannot copy reaches the driver as the application wrote it"); + + VkGraphicsPipelineCreateInfo graphics = { + .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, + .stageCount = 1, + .pStages = &app_fragment, + }; + expected_chain = &app_subgroup; + check(CreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphics, NULL, &pipeline) == VK_SUCCESS, + "a graphics pipeline with inline code behind another structure is created"); + check(chain_was_layer_owned && driver_subgroup_size == 16 && driver_version == 0x00010300u, + "the graphics stage reaches the driver capped with its chain intact"); + check(app_fragment.pNext == &app_subgroup && graphics.pStages == &app_fragment, + "the application's graphics stages are untouched"); + + driver_calls = 0; + failed_allocations = 0; + fail_allocations = true; + VkPipeline compute_outputs[2] = {(VkPipeline)(uintptr_t)1, (VkPipeline)(uintptr_t)2}; + VkPipeline graphics_outputs[2] = {(VkPipeline)(uintptr_t)1, (VkPipeline)(uintptr_t)2}; + VkResult compute_result = CreateComputePipelines(device, VK_NULL_HANDLE, 2, &compute, NULL, compute_outputs); + VkResult graphics_result = CreateGraphicsPipelines(device, VK_NULL_HANDLE, 2, &graphics, NULL, graphics_outputs); + fail_allocations = false; + check(failed_allocations > 0, "the allocations were made to fail"); + check(compute_result == VK_ERROR_OUT_OF_HOST_MEMORY, "a compute pipeline without memory reports it"); + check(graphics_result == VK_ERROR_OUT_OF_HOST_MEMORY, "a graphics pipeline without memory reports it"); + check(compute_outputs[0] == VK_NULL_HANDLE && compute_outputs[1] == VK_NULL_HANDLE, + "failed compute pipeline outputs are cleared"); + check(graphics_outputs[0] == VK_NULL_HANDLE && graphics_outputs[1] == VK_NULL_HANDLE, + "failed graphics pipeline outputs are cleared"); + check(driver_calls == 0, "the driver is not called without memory"); + pthread_mutex_destroy(&test_device.lock); +} + +int main(int argc, char **argv) +{ + struct spirv_code capped = {0}; + check(spirv_cap_version(newer, newer_count, &capped), "a SPIR-V 1.6 module is capped"); + check(capped.words != NULL, "the capped module is there"); + if (capped.words) { + check(capped.words[1] == 0x00010300u, "the capped module is SPIR-V 1.3"); + check(interface_size(capped.words, capped.count) == 1, + "the entry point lists only the input and output variables"); + check(count_opcodes(capped.words, capped.count, SpvOpKill) == 1, "the discard is an OpKill"); + check(count_opcodes(capped.words, capped.count, SpvOpTerminateInvocation) == 0, + "no OpTerminateInvocation is left"); + if (argc > 1) + write_module(argv[1], &capped); + free(capped.words); + } + + struct spirv_code kept = {0}; + check(!spirv_cap_version(older, older_count, &kept), "a SPIR-V 1.3 module is left alone"); + check(kept.words == NULL, "the untouched module is not handed back"); + check(!spirv_cap_version(capability, capability_count, &kept), + "a module with a capability from SPIR-V 1.5 is left alone"); + check(!spirv_cap_version(memory, memory_count, &kept), "a module with the Vulkan memory model is left alone"); + check(!spirv_cap_version(nonuniform, nonuniform_count, &kept), + "a module with ShaderNonUniform and no SPV_EXT_descriptor_indexing is left alone"); + check(!spirv_cap_version(select_struct, select_struct_count, &kept), + "a module selecting a structure is left alone"); + check(!spirv_cap_version(nonsemantic, nonsemantic_count, &kept), + "a module importing a NonSemantic set without SPV_KHR_non_semantic_info is left alone"); + uint32_t private_readonly[sizeof(zinklike) / sizeof(uint32_t) + 3]; + size_t declaration = 5; + while (OPCODE(zinklike[declaration]) != SpvOpTypeVoid) + declaration += LENGTH(zinklike[declaration]); + memcpy(private_readonly, zinklike, declaration * sizeof(uint32_t)); + private_readonly[declaration] = (3u << 16) | SpvOpDecorate; + private_readonly[declaration + 1] = 3; + private_readonly[declaration + 2] = SpvDecorationNonWritable; + memcpy(private_readonly + declaration + 3, zinklike + declaration, + (zinklike_count - declaration) * sizeof(uint32_t)); + check(!spirv_cap_version(private_readonly, zinklike_count + 3, &kept), + "a private NonWritable variable is left alone"); + if (argc > 6) { + struct spirv_code source = {.words = private_readonly, .count = zinklike_count + 3}; + write_module(argv[6], &source); + } + uint32_t converted[sizeof(zinklike) / sizeof(uint32_t) + 9]; + size_t function = declaration; + while (OPCODE(zinklike[function]) != SpvOpFunction) + function += LENGTH(zinklike[function]); + memcpy(converted, zinklike, function * sizeof(uint32_t)); + const uint32_t conversion[] = {(4u << 16) | SpvOpTypeInt, 23, 32, 0, + (5u << 16) | SpvOpSpecConstantOp, 23, 24, SpvOpUConvert, 15}; + memcpy(converted + function, conversion, sizeof(conversion)); + memcpy(converted + function + 9, zinklike + function, (zinklike_count - function) * sizeof(uint32_t)); + converted[3] = 25; + check(!spirv_cap_version(converted, zinklike_count + 9, &kept), + "a specialization UConvert without its extension is left alone"); + if (argc > 7) { + struct spirv_code source = {.words = converted, .count = zinklike_count + 9}; + write_module(argv[7], &source); + } + check(kept.words == NULL, "no rejected module is handed back"); + + struct spirv_code extension = {0}; + check(spirv_cap_version(nonuniform_extension, nonuniform_extension_count, &extension), + "a module declaring SPV_EXT_descriptor_indexing for ShaderNonUniform is capped"); + if (extension.words) { + check(extension.words[1] == 0x00010300u, "the module with the extension is SPIR-V 1.3"); + if (argc > 3) + write_module(argv[3], &extension); + free(extension.words); + } + + struct spirv_code scalar = {0}; + check(spirv_cap_version(select_scalar, select_scalar_count, &scalar), "a module selecting a scalar is capped"); + if (scalar.words) { + check(count_opcodes(scalar.words, scalar.count, SpvOpSelect) == 1, "the scalar select is kept"); + if (argc > 4) + write_module(argv[4], &scalar); + free(scalar.words); + } + + struct spirv_code debug = {0}; + check(spirv_cap_version(nonsemantic_extension, nonsemantic_extension_count, &debug), + "a module declaring SPV_KHR_non_semantic_info for its NonSemantic import is capped"); + if (debug.words) { + check(debug.words[1] == 0x00010300u, "the module with the NonSemantic import is SPIR-V 1.3"); + if (argc > 5) + write_module(argv[5], &debug); + free(debug.words); + } + + struct spirv_code guest = {0}; + check(spirv_cap_version(zinklike, zinklike_count, &guest), "a guest module with a private global is capped"); + if (guest.words) { + check(guest.words[1] == 0x00010300u, "the guest module is SPIR-V 1.3"); + check(interface_size(guest.words, guest.count) == 1, + "the guest module lists only the input and output variables"); + check(count_opcodes(guest.words, guest.count, SpvOpFunction) == 1, "the guest module keeps its function"); + if (argc > 2) + write_module(argv[2], &guest); + free(guest.words); + } + + struct spirv_code parameter = {0}; + size_t parameter_count = sizeof(readonly_parameter) / sizeof(uint32_t); + check(spirv_cap_version(readonly_parameter, parameter_count, ¶meter), + "a NonWritable storage buffer parameter is capped"); + if (parameter.words) { + check(count_opcodes(parameter.words, parameter.count, SpvOpFunctionParameter) == 1, + "the storage buffer parameter is preserved"); + if (argc > 8) + write_module(argv[8], ¶meter); + free(parameter.words); + } + uint32_t incompatible_parameter[sizeof(readonly_parameter) / sizeof(uint32_t)]; + memcpy(incompatible_parameter, readonly_parameter, sizeof(readonly_parameter)); + for (size_t i = 5; i < parameter_count; i += LENGTH(incompatible_parameter[i])) { + if (OPCODE(incompatible_parameter[i]) == SpvOpTypePointer) { + incompatible_parameter[i + 2] = SpvStorageClassPrivate; + check(!spirv_cap_version(incompatible_parameter, parameter_count, &kept), + "a NonWritable Private parameter is left alone"); + incompatible_parameter[i + 2] = SpvStorageClassFunction; + check(!spirv_cap_version(incompatible_parameter, parameter_count, &kept), + "a NonWritable Function parameter is left alone"); + } + } + + check_pipelines(); + + if (failures) + printf("%d check(s) failed\n", failures); + else + printf("mali compat spirv ok\n"); + return failures ? 1 : 0; +} diff --git a/tools/tests/test_appimage_run.py b/tools/tests/test_appimage_run.py index 14ac8ad676..84c92f49b8 100644 --- a/tools/tests/test_appimage_run.py +++ b/tools/tests/test_appimage_run.py @@ -146,6 +146,24 @@ class AppImageRunTest(unittest.TestCase): env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem")) self.assertEqual("sysmem", env["TU_DEBUG"]) + def test_an_arm64_app_uses_the_sessions_gl_libraries(self): + (self.dir / "arch").write_text("arm64") + self.bundle("usr/lib/libGLESv2.so.2", "usr/lib/libEGL.so.1", "usr/lib/libglfw.so.3", "usr/lib/libGLESv2.so.2.1.0") + _, log = self.launch(RUN_MODE) + lib = self.dir / "app/usr/lib" + self.assertEqual(["libGLESv2.so.2.1.0", "libglfw.so.3"], sorted(p.name for p in lib.iterdir())) + self.assertEqual(["libEGL.so.1", "libGLESv2.so.2"], sorted(p.name for p in (self.dir / "bundled-gl/usr/lib").iterdir())) + self.assertIn("the session's libGLESv2.so.2 replaces the bundled one", log) + _, log = self.launch(RUN_MODE) + self.assertNotIn("replaces the bundled one", log) + + def test_other_architectures_keep_their_gl_libraries(self): + (self.dir / "arch").write_text("x86_64") + self.bundle("usr/lib/libGLESv2.so.2") + self.launch(RUN_MODE) + self.assertTrue((self.dir / "app/usr/lib/libGLESv2.so.2").exists()) + self.assertFalse((self.dir / "bundled-gl").exists()) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py index ece44f60d6..b7bbafa3b4 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -6,7 +6,6 @@ import re import runpy import shutil import tempfile -import threading import time import unittest from unittest import mock @@ -93,8 +92,6 @@ class IdTest(unittest.TestCase): self.assertEqual(int(BNET["APP_ID"]), zlib.crc32(b'"droiddeck-battlenet"Battle.net') | 0x80000000) found = re.search(r"const val APP_ID = (\d+)L", KOTLIN.read_text()) self.assertEqual(found.group(1), BNET["APP_ID"]) - for name in ("FEX_REQUEST", "FEX_RESULT"): - self.assertIn('const val %s = "%s"' % (name, BNET[name]), KOTLIN.read_text()) class ProtonRunOptionsTest(Temp): @@ -761,36 +758,6 @@ class TidyTest(unittest.TestCase): self.assertEqual(self.stopped, []) -class FexRequestTest(Temp): - def answer(self, text, delay=0.2): - def respond(): - request = self.tmp / BNET["FEX_REQUEST"] - deadline = time.monotonic() + 5 - while not request.exists() and time.monotonic() < deadline: - time.sleep(0.02) - self.requested = request.read_text() - request.unlink() - time.sleep(delay) - (self.tmp / (BNET["FEX_RESULT"] + ".tmp")).write_text(text + "\n") - os.replace(self.tmp / (BNET["FEX_RESULT"] + ".tmp"), self.tmp / BNET["FEX_RESULT"]) - thread = threading.Thread(target=respond) - thread.start() - self.addCleanup(thread.join) - - def test_the_apps_answer_comes_back(self): - (self.tmp / BNET["FEX_RESULT"]).write_text("ok an-old-answer\n") - self.answer("ok FEXCore-2610-d2rfix28-linux.wcp") - self.assertEqual(BNET["ask_fex"](str(self.tmp), wait=5), "ok FEXCore-2610-d2rfix28-linux.wcp") - self.assertEqual(self.requested, "appid=%s\n" % BNET["APP_ID"]) - self.assertFalse((self.tmp / BNET["FEX_RESULT"]).exists()) - - def test_no_answer_or_no_session_starts_without_one(self): - with mock.patch.dict(BNET, {"say": lambda message: None}): - self.assertIsNone(BNET["ask_fex"](str(self.tmp), wait=0.3)) - self.assertIsNone(BNET["ask_fex"](None)) - self.assertIsNone(BNET["ask_fex"](str(self.tmp / "gone"))) - - class OpenTest(Temp): def setUp(self): super().setUp() @@ -799,7 +766,6 @@ class OpenTest(Temp): self.alive = [] self.menu = self.tmp / "droiddeck-battlenet.desktop" patcher = mock.patch.dict(BNET, { - "ask_fex": lambda launch_dir, wait=0: "ok fex.wcp", "say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])), "wine_processes": lambda pfx, proc="/proc": list(self.alive), "stop": lambda processes, wait=0: self.calls.append(("stop", [pid for pid, _ in processes])) or self.alive.clear(), @@ -988,7 +954,6 @@ class Harness(Temp): self.states = [] self.last = [] patcher = mock.patch.dict(BNET, { - "ask_fex": lambda launch_dir, wait=0: self.calls.append(("fex",)) or "ok fex.wcp", "say": lambda message: None, "notify": lambda *a, **k: self.calls.append(("notify", a[0])), "wine_processes": self.processes, "stop": lambda processes, wait=0: self.calls.append(("stop", sorted(pid for pid, _ in processes))), @@ -1019,7 +984,7 @@ class LaunchTest(Harness): self.states = [[], [], up, up + [(40, self.GAME)], up, up] self.assertEqual(BNET["launch"](self.root, "Fen"), 0) self.assertEqual(self.calls, [ - ("fex",), ("start", "Battle.net Launcher.exe", None), + ("start", "Battle.net Launcher.exe", None), ("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]), ("stop", [10, 11, 12, 13, 14, 30]), ]) @@ -1034,7 +999,7 @@ class LaunchTest(Harness): with mock.patch.dict(BNET, {"GAME_SETTLE": 0}): self.assertEqual(BNET["launch"](self.root, "Fen"), 0) self.assertEqual(self.calls, [ - ("fex",), ("start", "Battle.net Launcher.exe", None), + ("start", "Battle.net Launcher.exe", None), ("spawn", "Battle.net.exe", "run", ["--exec=launch Fen"]), ("stop", [10, 11, 12, 13, 14, 30]), ("stop", [50]), @@ -1448,7 +1413,8 @@ class AgentJobTest(Harness): self.assertEqual(code, 0) self.assertTrue(os.path.isdir(folder)) cmd = self.started[0] - self.assertEqual(cmd[:6], ["gamescope", "--backend", "headless", "-w", "640", "-h"]) + self.assertEqual(cmd[:4], ["/usr/local/bin/droiddeck-headless", str(self.tmp / "cache" / "agent-runtime"), "--log", + str(self.tmp / "cache" / "agent.log")]) self.assertEqual(cmd[cmd.index("--") + 2:-1], ["agent-serve", "install", "gryphon", "gryphon", "Z:" + folder, "enUS", "USA", "US"]) self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"]) self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"}) @@ -1676,16 +1642,6 @@ class AgentJobTest(Harness): path.write_bytes(json.dumps({"state": 1004}).encode("utf-8")) self.assertEqual(BNET["read_status"](str(path)), {"state": 1004}) - def test_a_large_agent_log_is_rotated_before_a_job(self): - self.install() - os.makedirs(self.tmp / "cache") - log = self.tmp / "cache" / "agent.log" - log.write_bytes(b"x" * (BNET["AGENT_LOG_LIMIT"] + 1)) - self.files = {".game": json.dumps({"installed": False})} - BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0) - self.assertEqual((self.tmp / "cache" / "agent.log.1").stat().st_size, BNET["AGENT_LOG_LIMIT"] + 1) - self.assertEqual(log.stat().st_size, 0) - def test_it_queues_behind_another_battle_net_job(self): self.install() self.files = {".game": json.dumps({"installed": False})} @@ -1716,13 +1672,11 @@ class AgentJobTest(Harness): self.assertEqual(self.lines[0], ("STATE", "waiting")) self.assertEqual(self.lines[1], ("STATE", "starting")) - def test_gamescope_gets_no_display_but_the_agent_keeps_the_one_gamescope_gives_it(self): + def test_the_agent_keeps_the_display_gamescope_gives_it_and_launches_through_the_shared_headless_helper(self): self.install() - os.environ.update(DISPLAY=":5", WAYLAND_DISPLAY="wayland-1") self.files = {".game": json.dumps({"installed": False})} BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0) - self.assertNotIn("DISPLAY", self.envs[0]) - self.assertNotIn("WAYLAND_DISPLAY", self.envs[0]) + self.assertEqual(self.started[0][0], BNET["HEADLESS"]) self.assertEqual(self.envs[0]["PROTON_USE_XALIA"], "0") os.environ["DISPLAY"] = ":0" self.assertEqual(BNET["agent_env"]()["DISPLAY"], ":0") diff --git a/tools/tests/test_binfmt_preload.py b/tools/tests/test_binfmt_preload.py index e207b5c9ca..38c2dc4038 100644 --- a/tools/tests/test_binfmt_preload.py +++ b/tools/tests/test_binfmt_preload.py @@ -138,6 +138,27 @@ class BinfmtPreloadTest(unittest.TestCase): program = self.file("arm64", bytes(arm64)) self.assertEqual(self.run_program("execve", program), (3, "errno %d" % errno.ENOEXEC, None)) + def arm64_appimage(self, name, filesystem): + image = bytearray(128) + image[0:4], image[4], image[5], image[8:11], image[18] = b"\x7fELF", 2, 1, b"AI\x02", 183 + image[0x28:0x30] = (64).to_bytes(8, "little") + image[0x3A:0x3C], image[0x3C:0x3E] = (32).to_bytes(2, "little"), (1).to_bytes(2, "little") + image[96:102] = filesystem + return self.file(name, bytes(image)) + + def test_an_arm64_appimage_goes_to_the_handler(self): + program = self.arm64_appimage("App.AppImage", b"hsqs\0\0") + for how in ("execve", "execvp"): + self.log.unlink(missing_ok=True) + target = program if how == "execve" else program.name + self.assertEqual(self.run_program(how, target, "--x"), (7, "", ["--exec", str(program), "--x"])) + self.log.unlink() + self.assertEqual(self.run_program("spawn", program, "y"), (0, "exit 7", ["--exec", str(program), "y"])) + + def test_an_appimage_runtime_without_a_filesystem_keeps_its_error(self): + runtime = self.arm64_appimage("uruntime", bytes(6)) + self.assertEqual(self.run_program("execve", runtime), (3, "errno %d" % errno.ENOEXEC, None)) + def test_a_script_runs_as_itself(self): script = self.file("script.sh", b"#!/bin/sh\nexit 5\n") self.assertEqual(self.run_program("execve", script), (5, "", None)) @@ -188,6 +209,24 @@ class BinfmtPreloadTest(unittest.TestCase): code = self.chromium_script() self.assertEqual(self.run_program("execve", code, "--version"), (0, "--no-sandbox\n--version", None)) + def test_a_chromium_app_named_on_path_receives_no_sandbox(self): + (self.dir / "code").symlink_to(self.chromium_script()) + for how in ("execvp", "execvpe", "spawnp"): + out = self.run_program(how, "code", "--version") + self.assertEqual(out[1].splitlines()[:2], ["--no-sandbox", "--version"], how) + + def test_a_path_match_that_cannot_run_does_not_decide_the_flags(self): + stale = self.dir / "stale" + stale.mkdir() + (stale / "util").write_text("#!/bin/sh\n") + (stale / "chrome-sandbox").touch() + util = self.dir / "util" + util.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\"\n") + util.chmod(0o755) + for how in ("execvp", "execvpe", "spawnp"): + out = self.run_program(how, "util", "--version", PATH=f"{stale}:{self.dir}:/usr/bin:/bin") + self.assertEqual(out[1].splitlines()[:1], ["--version"], how) + def test_the_hand_off_switch_works_without_the_desktop(self): tool = self.x86() for how in ("execve", "execvp"): diff --git a/tools/tests/test_cdp_guard.py b/tools/tests/test_cdp_guard.py index 9dc5891f36..0fc023e872 100644 --- a/tools/tests/test_cdp_guard.py +++ b/tools/tests/test_cdp_guard.py @@ -19,7 +19,8 @@ class CdpGuardTest(unittest.TestCase): subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), str(SOURCE.parent / "webhelper.c"), str(Path(__file__).with_name("netlink_stubs.c")), "-x", "c", "-", "-ldl", "-o", str(cls.library)], - input=b"int dd_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True) + input=b"int dd_udevmon_stand_in(int fd) { return 0; }\n" + b"int dd_udevmon_bind(int fd, const void *addr, unsigned len, void *real, int *rc) { return 0; }", check=True, capture_output=True) @classmethod def tearDownClass(cls): diff --git a/tools/tests/test_clock_pause_preload.py b/tools/tests/test_clock_pause_preload.py index 3d3f0dd76b..7b92a444bc 100644 --- a/tools/tests/test_clock_pause_preload.py +++ b/tools/tests/test_clock_pause_preload.py @@ -107,6 +107,51 @@ int main(void) { } """ +EARLY_LIBRARY = r""" +#include <pthread.h> +#include <time.h> + +pthread_mutex_t early_lock = PTHREAD_MUTEX_INITIALIZER; + +__attribute__((constructor)) static void early_start(void) { + struct timespec ts; + pthread_mutex_lock(&early_lock); + clock_gettime(CLOCK_MONOTONIC, &ts); + pthread_mutex_unlock(&early_lock); +} +""" + +EARLY_PROGRAM = r""" +#define _GNU_SOURCE +#include <fcntl.h> +#include <pthread.h> +#include <stdarg.h> +#include <stdio.h> +#include <sys/syscall.h> +#include <time.h> +#include <unistd.h> + +extern pthread_mutex_t early_lock; + +int open(const char *path, int flags, ...) { + va_list args; + va_start(args, flags); + mode_t mode = (mode_t)va_arg(args, int); + va_end(args); + pthread_mutex_lock(&early_lock); + pthread_mutex_unlock(&early_lock); + return (int)syscall(SYS_openat, AT_FDCWD, path, flags, mode); +} + +int main(void) { + struct timespec mono, boot; + clock_gettime(CLOCK_MONOTONIC, &mono); + clock_gettime(CLOCK_BOOTTIME, &boot); + printf("gap %lld\n", (long long)(((boot.tv_sec - mono.tv_sec) * 1000000000LL + boot.tv_nsec - mono.tv_nsec) / 1000000LL)); + return 0; +} +""" + SHIFT_MS = 10000 @@ -128,6 +173,13 @@ class ClockPausePreloadTest(unittest.TestCase): subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.shell), str(build / "program.c")], check=True) cls.other = build / "kwin_wayland" shutil.copy(cls.shell, cls.other) + (build / "early.c").write_text(EARLY_LIBRARY) + (build / "early_program.c").write_text(EARLY_PROGRAM) + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-pthread", "-o", str(build / "libearly.so"), + str(build / "early.c")], check=True) + cls.early = build / "early_program" + subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.early), str(build / "early_program.c"), + "-L", str(build), "-learly", "-Wl,-rpath," + str(build)], check=True) @classmethod def tearDownClass(cls): @@ -153,6 +205,11 @@ class ClockPausePreloadTest(unittest.TestCase): self.assertGreaterEqual(paused[name], 50, name) self.assertLess(paused[name], 1000, name) + def test_clock_read_inside_a_library_constructor_does_not_reenter_the_program(self): + plain = self.run_program(self.early, 0) + paused = self.run_program(self.early, SHIFT_MS) + self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50) + def test_program_without_preload_keeps_the_real_clock(self): plain = self.run_program(self.other, 0, preload=False) paused = self.run_program(self.other, SHIFT_MS, preload=False) diff --git a/tools/tests/test_component_reuse.py b/tools/tests/test_component_reuse.py new file mode 100644 index 0000000000..5d67e34c1a --- /dev/null +++ b/tools/tests/test_component_reuse.py @@ -0,0 +1,93 @@ +import hashlib +import importlib.util +import io +import json +from pathlib import Path +import sys +import tarfile +import tempfile +import unittest +from unittest import mock + +COMPONENTS = Path(__file__).resolve().parents[1] / 'components' +sys.path.insert(0, str(COMPONENTS)) +spec = importlib.util.spec_from_file_location('component_reuse', COMPONENTS / 'reuse.py') +reuse = importlib.util.module_from_spec(spec) +spec.loader.exec_module(reuse) +prepare = reuse.prepare + + +class ComponentReuseTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + (self.root / 'tools/ci').mkdir(parents=True) + (self.root / 'tools/ci/toolchains.env').write_text('CI_ANDROID_NDK_VERSION=30.0.1\n') + self.local = {'runtime': 'a', 'proot': 'b'} + self.unregistered, self.submodules = [], [] + for patcher in [mock.patch.object(prepare, 'registry', lambda root: dict.fromkeys(self.local)), + mock.patch.object(prepare, 'identity', lambda name, root: self.local[name]), + mock.patch.object(reuse, 'unregistered_changes', lambda tree, root: self.unregistered), + mock.patch.object(reuse, 'edited_submodules', lambda root: self.submodules)]: + patcher.start() + self.addCleanup(patcher.stop) + self.archive = self.root / 'prepared-components.tar.gz' + self.contents = {name + '/file': name.encode() for name in prepare.TREES} + self.contents.update({name: b'library' for name in prepare.LIBRARIES}) + + def write_archive(self, recipes, contents=None): + contents = contents or self.contents + manifest = dict(version=1, source_tree='tree', run='42', recipes=recipes, + files={name: hashlib.sha256(data).hexdigest() for name, data in self.contents.items()}) + with tarfile.open(self.archive, 'w:gz') as archive: + for name, data in list(contents.items()) + [(prepare.MANIFEST, json.dumps(manifest).encode())]: + entry = tarfile.TarInfo(name) + entry.size = len(data) + entry.mode = 0o644 + archive.addfile(entry, io.BytesIO(data)) + + def test_matching_components_replace_local_ones(self): + stale = self.root / prepare.TREES[0] / 'left-over' + stale.parent.mkdir(parents=True) + stale.write_text('from an older local build') + self.write_archive(dict(self.local)) + self.assertTrue(reuse.reuse(self.archive, self.root)) + self.assertEqual(b'library', (self.root / prepare.LIBRARIES[0]).read_bytes()) + self.assertFalse(stale.exists()) + + def test_a_changed_component_is_not_reused(self): + self.write_archive(dict(self.local, proot='other')) + with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout: + self.assertFalse(reuse.reuse(self.archive, self.root)) + self.assertIn('proot', stdout.getvalue()) + self.assertFalse((self.root / prepare.LIBRARIES[0]).exists()) + + def test_a_tampered_file_is_rejected_and_local_outputs_survive(self): + local = self.root / prepare.LIBRARIES[0] + local.parent.mkdir(parents=True) + local.write_bytes(b'local build') + self.write_archive(dict(self.local), dict(self.contents, **{prepare.LIBRARIES[0]: b'tampered'})) + with self.assertRaisesRegex(ValueError, 'do not match'): + reuse.reuse(self.archive, self.root) + self.assertEqual(b'local build', local.read_bytes()) + + def test_changed_sources_ci_builds_outside_recipes_are_not_reused(self): + self.unregistered = ['tools/linuxfs/xclipse-layer/xclipse_layer.c'] + self.write_archive(dict(self.local)) + with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout: + self.assertFalse(reuse.reuse(self.archive, self.root)) + self.assertIn('xclipse_layer.c', stdout.getvalue()) + + def test_an_edited_submodule_is_not_reused(self): + self.submodules = ['external/MaliBridge'] + self.write_archive(dict(self.local)) + with mock.patch('sys.stdout', new_callable=io.StringIO): + self.assertFalse(reuse.reuse(self.archive, self.root)) + + def test_identities_use_the_ci_runner_and_ndk(self): + seen = {} + with mock.patch.object(prepare, 'identity', lambda name, root: seen.update( + arch=reuse.os.environ['RUNNER_ARCH'], ndk=reuse.os.environ['NDK_VERSION']) or 'x'): + reuse.identities(reuse.ci_environment('X64', self.root), self.root) + self.assertEqual({'arch': 'X64', 'ndk': '30.0.1'}, seen) diff --git a/tools/tests/test_curseforge_helper.py b/tools/tests/test_curseforge_helper.py new file mode 100644 index 0000000000..e65388405d --- /dev/null +++ b/tools/tests/test_curseforge_helper.py @@ -0,0 +1,213 @@ +import os +import shlex +import shutil +import subprocess +import tempfile +import time +import unittest +from pathlib import Path + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +HELPER = BIN / "droiddeck-curseforge" +HEADLESS = BIN / "droiddeck-headless" +URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + + +class HeadlessTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.bin = self.tmp / "bin" + self.bin.mkdir() + self.seen = self.tmp / "seen" + gamescope = self.bin / "gamescope" + gamescope.write_text( + "#!/bin/bash\n" + "printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"GAMESCOPE=${GAMESCOPE_WAYLAND_DISPLAY-}\" " + "\"XAUTH=${XAUTHORITY-}\" \"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n" + "echo logged-by-gamescope\n" % shlex.quote(str(self.seen))) + gamescope.chmod(0o755) + + def env(self, extra=None): + base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", + GAMESCOPE_WAYLAND_DISPLAY="gamescope-0", XAUTHORITY="/run/xauth") + base.update(extra or {}) + return base + + def run_headless(self, *args, env=None): + return subprocess.run(["bash", str(HEADLESS), *args], env=self.env(env), capture_output=True, text=True, timeout=30) + + def test_it_runs_the_command_in_headless_gamescope_with_a_private_runtime_and_no_session_display(self): + runtime = self.tmp / "runtime" + out = self.run_headless(str(runtime), "--", "prog", "arg one") + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual(["DISPLAY=", "WAYLAND=", "GAMESCOPE=", "XAUTH=", "RUNTIME=%s" % runtime, "--backend", "headless", + "-w", "640", "-h", "480", "--", "prog", "arg one"], self.seen.read_text().splitlines()) + self.assertEqual(0o700, runtime.stat().st_mode & 0o777) + + def test_output_goes_to_the_log_which_rotates_when_large(self): + log = self.tmp / "agent.log" + log.write_bytes(b"x" * 100) + self.assertEqual(0, self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog").returncode) + self.assertTrue(log.read_text().endswith("logged-by-gamescope\n")) + self.assertEqual(100, log.stat().st_size - len("logged-by-gamescope\n")) + self.assertFalse((self.tmp / "agent.log.1").exists()) + self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog", env={"DD_HEADLESS_LOG_LIMIT": "50"}) + self.assertEqual(100 + len("logged-by-gamescope\n"), (self.tmp / "agent.log.1").stat().st_size) + self.assertEqual("logged-by-gamescope\n", log.read_text()) + + def test_bad_arguments_are_refused(self): + self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "prog").returncode) + self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "--").returncode) + self.assertEqual(2, self.run_headless().returncode) + + +class CurseForgeHelperTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.proc = self.tmp / "proc" + self.proc.mkdir() + self.dir = self.tmp / "curseforge" + (self.dir / "app").mkdir(parents=True) + self.state = self.tmp / "state" + self.bin = self.tmp / "bin" + self.bin.mkdir() + self.runner = self.tmp / "runner" + self.seen = self.tmp / "seen" + self.runner.write_text( + "#!/bin/bash\n" + "printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" " + "\"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n" + "mkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n" + "echo 'Debugger listening on %s' >&2\n" + "echo 'For help, see: https://nodejs.org/en/docs/inspector' >&2\n" + "sleep 60\n" + % (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL)) + self.runner.chmod(0o755) + gamescope = self.bin / "gamescope" + gamescope.write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@"\n') + gamescope.chmod(0o755) + + def fake(self, pid, *argv): + d = self.proc / str(pid) + d.mkdir() + (d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv)) + + def env(self, extra=None): + base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DD_PROC=str(self.proc), + DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), DD_HEADLESS_RUN=str(HEADLESS), + DD_CURSEFORGE_WAIT="10", DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", XDG_RUNTIME_DIR="/run/user/session", + DBUS_SESSION_BUS_ADDRESS="unix:path=/x") + base.update(extra or {}) + return base + + def run_helper(self, *args, env=None): + return subprocess.run(["bash", str(HELPER), *args], env=self.env(env), capture_output=True, text=True, timeout=60) + + def launch(self, directory=None): + holder = subprocess.Popen(["bash", str(HELPER), "start", str(directory or self.dir)], env=self.env(), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + self.addCleanup(self.finish, holder) + return holder, holder.stdout.readline().strip() + + def finish(self, holder): + if holder.poll() is None: + holder.kill() + holder.communicate() + + def stop(self): + self.run_helper("stop", str(self.dir)) + + def pid(self): + return int((self.state / "pid").read_text().split()[0]) + + def gone(self, pid): + for _ in range(50): + try: + os.kill(pid, 0) + except ProcessLookupError: + return True + time.sleep(0.1) + return False + + def test_a_running_instance_without_the_inspector_is_busy(self): + self.fake(50, "/usr/bin/FEX", str(self.dir) + "/app/curseforge", "--no-sandbox") + out = self.run_helper("start", str(self.dir)) + self.assertEqual(3, out.returncode) + self.assertEqual("busy", out.stdout.strip()) + self.stop() + self.assertTrue((self.proc / "50").exists()) + + def test_start_runs_the_app_in_headless_gamescope_with_a_secret_inspector_and_no_session_display(self): + holder, url = self.launch() + self.addCleanup(self.stop) + self.assertEqual(URL, url) + seen = self.seen.read_text().splitlines() + self.assertEqual(["DISPLAY=", "WAYLAND=", "DBUS=", "RUNTIME=%s/runtime" % self.state, str(self.dir), "--minimized", + "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen) + self.assertEqual(0o700, self.state.stat().st_mode & 0o777) + self.assertEqual(0o700, (self.state / "runtime").stat().st_mode & 0o777) + self.assertEqual(0o600, (self.state / "log").stat().st_mode & 0o777) + _, again = self.launch() + self.assertEqual(URL, again) + + def test_start_holds_the_app_until_it_is_stopped(self): + holder, url = self.launch() + self.assertEqual(URL, url) + app = self.pid() + time.sleep(1) + self.assertIsNone(holder.poll()) + os.kill(app, 0) + self.stop() + self.assertEqual(0, holder.wait(timeout=30)) + self.assertTrue(self.gone(app), "the app is still running") + + def test_stop_ends_the_app_and_the_gamescope_it_ran_in(self): + (self.bin / "gamescope").write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@" &\nwait\n') + self.assertEqual(URL, self.launch()[1]) + gamescope = self.pid() + app = int(next(self.proc.iterdir()).name) + self.assertNotEqual(gamescope, app) + os.kill(app, 0) + self.stop() + self.assertFalse((self.state / "pid").exists()) + self.assertTrue(self.gone(gamescope), "gamescope is still running") + self.assertTrue(self.gone(app), "the app is still running") + + def test_a_launch_for_another_directory_is_busy_and_left_alone(self): + other = self.tmp / "other" + (other / "app").mkdir(parents=True) + self.addCleanup(self.stop) + self.assertEqual(URL, self.launch()[1]) + out = self.run_helper("start", str(other)) + self.assertEqual(3, out.returncode) + self.assertEqual("busy", out.stdout.strip()) + pid = self.pid() + self.run_helper("stop", str(other)) + self.assertEqual(pid, self.pid()) + os.kill(pid, 0) + + def test_each_launch_starts_a_fresh_log(self): + first, _ = self.launch() + self.stop() + first.wait(timeout=30) + self.addCleanup(self.stop) + self.assertEqual(URL, self.launch()[1]) + self.assertEqual(1, (self.state / "log").read_text().count("Debugger listening")) + self.assertTrue((self.state / "log.1").exists()) + + def test_stop_without_a_launch_is_quiet(self): + out = self.run_helper("stop", str(self.dir)) + self.assertEqual(0, out.returncode) + self.assertEqual("", out.stderr) + self.assertEqual("", out.stdout) + + def test_bad_arguments_are_refused(self): + self.assertEqual(2, self.run_helper("start", str(self.tmp / "missing")).returncode) + self.assertEqual(2, self.run_helper("launch", str(self.dir)).returncode) + self.assertEqual(2, self.run_helper("hold", str(self.dir)).returncode) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_ddexec_reexec.py b/tools/tests/test_ddexec_reexec.py new file mode 100644 index 0000000000..640db1706c --- /dev/null +++ b/tools/tests/test_ddexec_reexec.py @@ -0,0 +1,154 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +SOURCE = REPO / "app/src/main/cpp/ddexec/ddexec.c" +SYSROOT = Path("/usr/aarch64-linux-gnu") + +LIBRARY = r""" +int dd_probe_value(void) { return 7; } +""" + +HOOK = r""" +#include <unistd.h> + +__attribute__((constructor)) static void hooked(void) { write(1, "hooked\n", 7); } +""" + +PROGRAM = r""" +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <sys/auxv.h> +#include <sys/syscall.h> + +int dd_probe_value(void); + +int main(int argc, char **argv, char **envp) { + if (dd_probe_value() != 7) return 4; + if (argc > 1 && strcmp(argv[1], "again") == 0) { + for (int i = 0; i < argc; i++) printf("%s%s", i ? "|" : "", argv[i]); + printf("\n%s\n", (char *)getauxval(AT_EXECFN)); + return 0; + } + char *next[] = {"first", "again", "x y", NULL}; + syscall(SYS_execveat, -100, "/proc/self/exe", next, envp, 0); + return 3; +} +""" + + +def ndk_clang(): + sdk = Path(os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") or Path.home() / "Android/Sdk") + for ndk in sorted((sdk / "ndk").glob("*"), reverse=True): + clang = ndk / "toolchains/llvm/prebuilt/linux-x86_64/bin/clang" + if clang.exists(): + return str(clang) + return shutil.which("clang") + + +class DdexecReexecTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cc, prefix = runner() + clang = ndk_clang() + if cc is None or clang is None or not shutil.which("bwrap") or not SYSROOT.is_dir(): + raise unittest.SkipTest("no aarch64 toolchain, runner or bwrap") + cls.qemu = list(prefix[:3]) if prefix else [] + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.loader = tmp / "libddexec.so" + subprocess.run([clang, "--target=aarch64-linux-android29", "-shared", "-fPIC", "-O2", "-ffreestanding", + "-fno-builtin", "-fno-stack-protector", "-fno-asynchronous-unwind-tables", "-nostdlib", + "-Wl,-e,_start", "-Wl,-z,noexecstack", "-Wl,--no-undefined", "-Wl,-Bsymbolic", + "-Wl,-z,max-page-size=16384", "-o", str(cls.loader), str(SOURCE)], check=True) + cls.libdir = tmp / "own-lib" + cls.libdir.mkdir() + (tmp / "lib.c").write_text(LIBRARY) + subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.libdir / "libddprobe.so"), str(tmp / "lib.c")], + check=True) + (tmp / "prog.c").write_text(PROGRAM) + cls.program = tmp / "prog" + subprocess.run([cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c"), "-L", str(cls.libdir), "-lddprobe"], + check=True) + cls.root = tmp / "root" + (cls.root / "usr/lib").mkdir(parents=True) + (cls.root / "lib").mkdir() + shutil.copy2(SYSROOT / "lib/ld-linux-aarch64.so.1", cls.root / "lib/ld-linux-aarch64.so.1") + (tmp / "hook.c").write_text(HOOK) + subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.root / "usr/lib/libddnatv-hook.so"), str(tmp / "hook.c")], + check=True) + probe = subprocess.run(["bwrap", "--dev-bind", "/", "/", "true"], capture_output=True) + if probe.returncode != 0: + raise unittest.SkipTest("bwrap cannot create a namespace here") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def env(self, real_exe, library_path=None, root=SYSROOT): + env = {k: v for k, v in os.environ.items() if not k.startswith(("DDNATV_", "LD_", "QEMU_"))} + env["DDNATV_ROOT"] = str(root) + env["LD_LIBRARY_PATH"] = f"{SYSROOT / 'lib'}:{self.libdir}" if library_path is None else str(SYSROOT / "lib") + if real_exe: + env["DDNATV_REAL_EXE"] = str(real_exe) + if library_path: + env["DDNATV_LIBRARY_PATH"] = library_path + return env + + def reexec(self, execfn, real_exe, library_path=None, root=SYSROOT): + jail = ["bwrap", "--dev-bind", "/", "/", "--tmpfs", "/proc"] + parent = str(Path(execfn).parent) + jail += ["--dir", parent, "--ro-bind", str(self.loader), execfn] + start = self.qemu + ["-0", "first", execfn] if self.qemu else ["bash", "-c", 'exec -a first "$0" "$@"', execfn] + cmd = jail + start + ["again", "x y"] + return subprocess.run(cmd, env=self.env(real_exe, library_path, root), capture_output=True, text=True, timeout=120) + + def test_reexec_through_proc_self_exe_runs_the_guest_program(self): + out = self.reexec("/proc/self/exe", self.program) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_through_thread_self_exe_runs_the_guest_program(self): + out = self.reexec("/proc/thread-self/exe", self.program) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_finds_libraries_through_the_recorded_library_path(self): + out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}") + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_through_ld_so_preloads_the_hook_of_the_root(self): + out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}", self.root) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["hooked", "first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_without_a_known_program_fails_cleanly(self): + out = self.reexec("/proc/self/exe", None) + self.assertEqual(127, out.returncode) + self.assertIn("DDNATV_REAL_EXE", out.stderr) + + def test_a_started_program_keeps_its_own_arguments(self): + ldso = SYSROOT / "lib/ld-linux-aarch64.so.1" + cmd = self.qemu + [str(self.loader), str(ldso), "ld.so", "--library-path", f"{SYSROOT / 'lib'}:{self.libdir}", + str(self.program), "again", "a"] + out = subprocess.run(cmd, env=self.env(self.program), capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual([f"{self.program}|again|a", str(self.program)], out.stdout.splitlines()) + + def test_the_usage_check_still_applies_outside_a_reexec(self): + out = subprocess.run(self.qemu + [str(self.loader), str(self.program)], env=self.env(self.program), + capture_output=True, text=True, timeout=120) + self.assertEqual(127, out.returncode) + self.assertIn("usage", out.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_desktop_chromium_apps.py b/tools/tests/test_desktop_chromium_apps.py index f8d6056d21..8f5525d6d3 100644 --- a/tools/tests/test_desktop_chromium_apps.py +++ b/tools/tests/test_desktop_chromium_apps.py @@ -1,11 +1,8 @@ -import os from pathlib import Path import tempfile import unittest SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/desktop/droiddeck-desktop-gpu" -PREFIX = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 " -FLAGS = " --no-sandbox --ozone-platform=x11" def load(): @@ -24,12 +21,6 @@ class DesktopChromiumAppsTest(unittest.TestCase): self.gpu = load() self.electron = self.app("lib/chat/chat", sandbox=True) self.plain = self.app("lib/editor/editor", sandbox=False) - bin_dir = self.root / "bin" - bin_dir.mkdir() - (bin_dir / "chat").symlink_to(self.electron) - old_path = os.environ.get("PATH", "") - os.environ["PATH"] = "%s:%s" % (bin_dir, old_path) - self.addCleanup(os.environ.__setitem__, "PATH", old_path) def app(self, relative, sandbox): path = self.root / relative @@ -49,34 +40,17 @@ class DesktopChromiumAppsTest(unittest.TestCase): def exec_lines(self, text): return [l[5:] for l in text.splitlines() if l.startswith("Exec=")] - def test_an_electron_app_starts_without_the_sandbox_on_x11(self): - out = self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron)) - self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS + " %U", - PREFIX + str(self.electron) + FLAGS + " --new"]) - self.assertIn("X-DroidDeck-GPU=1", out) - self.assertIn("Actions=new;", out) - self.assertNotIn("droiddeck-window", out) + def test_electron_apps_keep_their_own_entries(self): + self.assertIsNone(self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron))) + self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain)))) - def test_a_command_on_the_path_is_followed_to_its_install_folder(self): - out = self.gpu["wrap"](self.entry("chat %U")) - self.assertEqual(self.exec_lines(out), [PREFIX + "chat" + FLAGS + " %U"]) + def test_an_electron_game_goes_to_the_gpu_as_installed(self): + out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;", actions="%s --new" % self.electron)) + self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + str(self.electron), str(self.electron), + "droiddeck-gpu %s --new" % self.electron]) - def test_a_quoted_program_keeps_its_quotes(self): - out = self.gpu["wrap"](self.entry('"%s" %%U' % self.electron)) - self.assertEqual(self.exec_lines(out), [PREFIX + '"%s"' % self.electron + FLAGS + " %U"]) - - def test_other_apps_are_left_alone(self): - self.assertIsNone(self.gpu["wrap"](self.entry("%s %%F" % self.plain))) - self.assertIsNone(self.gpu["wrap"](self.entry("missing-program %F"))) - - def test_an_electron_game_goes_to_the_gpu_and_keeps_a_window_action(self): - out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;")) - fixed = PREFIX + str(self.electron) + FLAGS - self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + fixed, fixed]) - - def test_with_the_gpu_off_electron_apps_are_still_fixed(self): - out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False) - self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS]) + def test_with_the_gpu_off_no_entry_is_written(self): + self.assertIsNone(self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False)) self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain), categories="Game;"), False)) def test_games_that_are_not_chromium_are_unchanged(self): diff --git a/tools/tests/test_desktop_display_buffers.py b/tools/tests/test_desktop_display_buffers.py new file mode 100644 index 0000000000..0c3defcb83 --- /dev/null +++ b/tools/tests/test_desktop_display_buffers.py @@ -0,0 +1,29 @@ +from pathlib import Path +import re +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +DESKTOP = ROOT / "tools/linuxfs/desktop/droiddeck-desktop" +SOURCE = ROOT / "app/src/main/cpp/waylandcomp/src/display_buffers.c" + + +class DesktopDisplayBuffersTest(unittest.TestCase): + def test_clearing_the_runtime_directory_keeps_what_the_compositor_serves(self): + socket = re.search(r'#define DISPLAY_BUFFERS_SOCKET "([^"]+)"', SOURCE.read_text()).group(1) + lines = [line for line in DESKTOP.read_text().splitlines() if line.startswith('find "$XDG_RUNTIME_DIR"')] + self.assertEqual(len(lines), 1) + with tempfile.TemporaryDirectory() as directory: + runtime = Path(directory) / "runtime" + (runtime / "dbus-1").mkdir(parents=True) + kept = ["wayland-0", "wayland-0.lock", "keymap.xkb", socket] + for name in kept + ["wayland-1", "pipewire-0", "dbus-1/session"]: + (runtime / name).write_text("") + subprocess.run(["bash", "-c", lines[0]], env={"XDG_RUNTIME_DIR": str(runtime), "PATH": "/usr/bin:/bin"}, + check=True, timeout=20) + self.assertEqual(sorted(path.name for path in runtime.iterdir()), sorted(kept)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_desktop_firefox_software.py b/tools/tests/test_desktop_firefox_software.py new file mode 100644 index 0000000000..b2b839edd3 --- /dev/null +++ b/tools/tests/test_desktop_firefox_software.py @@ -0,0 +1,40 @@ +import os +from pathlib import Path +import subprocess +import unittest + + +DESKTOP = (Path(__file__).resolve().parents[1] / 'linuxfs/desktop/droiddeck-desktop').read_text() +START = 'if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then' +LINE = '\n [ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0\n' + + +class DesktopFirefoxSoftwareTest(unittest.TestCase): + def firefox_environment(self, gl_present): + head = DESKTOP[:DESKTOP.index('\n', DESKTOP.index('export MOZ_ENABLE_WAYLAND=1'))] + head = head[head.rindex('\n') + 1:] + block = DESKTOP[DESKTOP.index(START):] + block = block[block.index('\n') + 1:block.index('\n if [ -z "${KWIN_RENDER_NODES:-}" ]')] + environment = {key: value for key, value in os.environ.items() + if key not in ('DD_STEAM_GL_PRESENT', 'MOZ_ENABLE_WAYLAND', 'MOZ_ACCELERATED')} + if gl_present is not None: + environment['DD_STEAM_GL_PRESENT'] = gl_present + script = head + '\n' + block + '\nsh -c \'echo "wayland:${MOZ_ENABLE_WAYLAND:-unset} accelerated:${MOZ_ACCELERATED:-unset}"\'' + result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True, + text=True, timeout=5) + self.assertEqual(0, result.returncode, result.stderr) + return result.stdout.strip().splitlines()[-1] + + def test_system_powervr_desktop_runs_firefox_on_wayland_with_software_rendering(self): + self.assertEqual('wayland:1 accelerated:0', self.firefox_environment('1')) + + def test_other_drivers_keep_firefox_hardware_rendering(self): + self.assertEqual('wayland:1 accelerated:unset', self.firefox_environment(None)) + self.assertEqual('wayland:1 accelerated:unset', self.firefox_environment('0')) + + def test_override_is_set_before_plasma(self): + self.assertLess(DESKTOP.index(LINE), DESKTOP.index('dbus-run-session -- startplasma-wayland')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_desktop_powervr.py b/tools/tests/test_desktop_powervr.py new file mode 100644 index 0000000000..ad91719803 --- /dev/null +++ b/tools/tests/test_desktop_powervr.py @@ -0,0 +1,42 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +DESKTOP = (Path(__file__).resolve().parents[1] / 'linuxfs/desktop/droiddeck-desktop').read_text() +START = 'if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then' +LAUNCH = 'dbus-run-session -- startplasma-wayland' +STUBS = ''' +pipewire() { return 0; } +dbus-run-session() { sh -c 'echo "kopper:${LIBGL_KOPPER_DISABLE:-on}"'; } +''' + + +class DesktopPowerVrTest(unittest.TestCase): + def kopper_at_plasma_launch(self, gl_present): + segment = DESKTOP[DESKTOP.index(START):DESKTOP.index(LAUNCH) + len(LAUNCH)] + with tempfile.TemporaryDirectory() as run: + segment = (segment.replace(START, 'if true; then') + .replace('/usr/local/bin/droiddeck-pipewire', 'pipewire') + .replace('/run/droiddeck', run)) + environment = {key: value for key, value in os.environ.items() + if key not in ('DD_STEAM_GL_PRESENT', 'LIBGL_KOPPER_DISABLE')} + if gl_present is not None: + environment['DD_STEAM_GL_PRESENT'] = gl_present + result = subprocess.run(['bash', '-c', STUBS + segment], env=environment, + capture_output=True, text=True, timeout=5) + self.assertEqual(0, result.returncode, result.stderr) + return result.stdout.strip().splitlines()[-1] + + def test_system_powervr_plasma_starts_with_kopper_off(self): + self.assertEqual('kopper:true', self.kopper_at_plasma_launch('1')) + + def test_other_drivers_start_plasma_with_kopper(self): + self.assertEqual('kopper:on', self.kopper_at_plasma_launch(None)) + self.assertEqual('kopper:on', self.kopper_at_plasma_launch('0')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_droiddeck_agent.py b/tools/tests/test_droiddeck_agent.py index a84a54ca8b..72931860b7 100644 --- a/tools/tests/test_droiddeck_agent.py +++ b/tools/tests/test_droiddeck_agent.py @@ -348,6 +348,45 @@ class AgentTest(unittest.TestCase): self.assertEqual("INVALID_TARGET", caught.exception.code) connect.assert_not_called() + def test_one_shot_inspector_eval_prints_the_session_answer_without_a_launch_dir(self): + import contextlib + import io + url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + seen = {} + + def evaluate(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None, command_line_api=False): + seen.update(expression=expression, timeout=timeout, inspector=inspector, api=command_line_api) + return {"target": "inspector", "type": "string", "value": "ok", "description": None} + + out = io.StringIO() + with patch.dict(os.environ, {}, clear=False), patch.object(agent, "cdp_eval", evaluate), contextlib.redirect_stdout(out): + os.environ.pop("DD_LAUNCH_DIR", None) + self.assertEqual(0, agent.main(["--cdp-inspector", url, "12.5", "1 + 1"])) + self.assertEqual({"target": "inspector", "type": "string", "value": "ok", "description": None, "ok": True}, json.loads(out.getvalue())) + self.assertEqual({"expression": "1 + 1", "timeout": 12.5, "inspector": url, "api": True}, seen) + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(0, agent.main(["--cdp-inspector", "ws://example.com:9229/x", "5", "1"])) + self.assertEqual("INVALID_REQUEST", json.loads(out.getvalue())["error"]["code"]) + self.assertEqual(2, agent.main(["--cdp-inspector", url])) + + def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self): + class Lost: + def __init__(self, *args, **kwargs): + pass + + def send(self, text): + raise BrokenPipeError("closed") + + def close(self): + pass + + with patch.object(agent, "WebSocket", Lost), patch.object( + agent, "cdp_targets", return_value=[{"title": "SharedJSContext", "webSocketDebuggerUrl": "ws://127.0.0.1:1/x"}]): + with self.assertRaises(agent.AgentError) as caught: + agent.cdp_eval(str(self.dir), "1") + self.assertEqual("DEVTOOLS_UNREACHABLE", caught.exception.code) + def test_cdp_without_a_port(self): os.environ.pop("DD_CDP_PORT", None) self.assertEqual("NO_DEVTOOLS", self.ask({"kind": "cdp", "expression": "1"})["error"]["code"]) @@ -368,6 +407,22 @@ class AgentTest(unittest.TestCase): missing = self.ask({"kind": "cdp", "expression": "1", "target": "Nope"}) self.assertEqual("NO_TARGET", missing["error"]["code"]) + def test_cdp_eval_on_a_secret_inspector_url(self): + server = FakeDevTools({"result": {"result": {"type": "string", "value": "ok"}}}) + server.start() + self.addCleanup(server.server.close) + os.environ.pop("DD_CDP_PORT", None) + url = "ws://127.0.0.1:%d/0f8fad5b-d9cb-469f-a165-70867728950e" % server.port + answer = self.ask({"kind": "cdp", "expression": "require('electron')", "inspector": url, "commandLineApi": True}) + self.assertTrue(answer["ok"], answer) + self.assertEqual("inspector", answer["target"]) + self.assertTrue(server.seen[0]["params"]["includeCommandLineAPI"]) + + def test_cdp_refuses_inspector_urls_without_a_session_id(self): + for url in ("ws://127.0.0.1:9229/", "ws://127.0.0.1:9229/json/list", "ws://10.0.0.2:9229/0f8fad5b-d9cb-469f-a165-70867728950e", + "ws://127.0.0.1:80/0f8fad5b-d9cb-469f-a165-70867728950e", "ws://127.0.0.1:9229/0f8fad5b-d9cb-469f-a165-70867728950e/x", 9229): + self.assertEqual("INVALID_REQUEST", self.ask({"kind": "cdp", "expression": "1", "inspector": url})["error"]["code"]) + def test_steam_selection(self): with patch.object(agent, "cdp_eval", return_value={"value": "3180310"}) as evaluate: answer = self.ask({"kind": "steam-selection"}) diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 825cd8b8d4..628fcd57ef 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -526,6 +526,21 @@ class PrepareTest(FexTestCase): for name in names: self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new ABI " + name.encode()) + def test_opengl_dispatch_library_comes_from_the_newer_runtime_when_the_base_lacks_it(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + self.write(sniper / "files/lib" / arch / "libGLdispatch.so.0", b"base dispatch") + self.write(provider / "files/lib" / arch / "libOpenGL.so.0.0.0", b"opengl " + arch.encode()) + os.symlink("libOpenGL.so.0.0.0", provider / "files/lib" / arch / "libOpenGL.so.0") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + root = Path(fex["rootfs"]) / "lib" / arch + self.assertEqual((root / "libOpenGL.so.0").read_bytes(), b"opengl " + arch.encode()) + self.assertEqual((root / "libGLdispatch.so.0").read_bytes(), b"base dispatch") + def test_gbm_requires_usable_provider_dependencies_on_both_architectures(self): self.fex_tool() sniper = self.runtime() @@ -1008,6 +1023,128 @@ class ExtractTest(FexTestCase): self.assertIn("-no-xattrs", commands[-1]) self.assertTrue(Path("squashfs-root/AppRun").is_file()) + def seven_zip(self, tool, which, works=True): + commands = [] + + def call(argv, **kwargs): + commands.append(argv) + if argv[0] != "/usr/bin/7z" or not works: + return 2 + (self.work / "squashfs-root").mkdir() + (self.work / "squashfs-root/AppRun").touch() + return 0 + + with mock.patch.dict(G, { + "URUNTIME": tool, + "prepare": lambda: None, + "fex_install": lambda: None, + "steam_running": lambda: False, + "want_fex": lambda: None, + }), mock.patch("shutil.which", side_effect=lambda name: which.get(name)), \ + mock.patch("subprocess.call", side_effect=call): + status, said = self.quiet(FEX["extract"], "image.AppImage") + return status, said, commands + + def test_without_proot_the_shipped_runtime_reads_the_open_image(self): + self.write(self.image, elf(183) + b"payload", 0o755) + tool = self.uruntime('cmp "$TARGET_APPIMAGE" "%s" || exit 9\nmkdir -p AppDir && touch AppDir/AppRun\n' % self.image) + with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}): + status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"}) + self.assertEqual((status, said), (0, "")) + self.assertEqual([], commands) + self.assertTrue(Path("squashfs-root/AppRun").is_file()) + + def test_without_proot_runtime_failure_falls_back_to_7zip(self): + self.write(self.image, elf(183) + b"payload", 0o755) + tool = self.uruntime("exit 1\n") + with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}): + status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"}) + self.assertEqual(status, 0) + self.assertIn("uruntime could not extract it (status 1)", said) + self.assertEqual("/usr/bin/7z", commands[-1][0]) + self.assertTrue(Path("squashfs-root/AppRun").is_file()) + + def test_with_proot_the_shipped_runtime_is_still_tried_first(self): + ran = self.tmp / "uruntime-ran" + tool = self.uruntime("touch %s\nexit 1\n" % ran) + env = {k: v for k, v in os.environ.items() if k != "DDNATV_ROOT"} + with mock.patch.dict(os.environ, env, clear=True): + status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"}) + self.assertEqual(status, 0) + self.assertTrue(ran.exists()) + self.assertIn("uruntime could not extract it (status 1)", said) + self.assertEqual("/usr/bin/7z", commands[-1][0]) + + def test_unsquashfs_is_preferred_over_7zip(self): + tool = self.uruntime("exit 1\n") + status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"}) + self.assertEqual(status, 0) + self.assertIn("unsquashfs could not extract it (status 2)", said) + self.assertEqual(["/usr/bin/unsquashfs", "/usr/bin/7z"], [c[0] for c in commands]) + + def test_a_7zip_failure_leaves_nothing_unpacked(self): + tool = self.uruntime("exit 1\n") + status, said, _ = self.seven_zip(tool, {"7z": "/usr/bin/7z"}, works=False) + self.assertEqual(status, 1) + self.assertIn("7-Zip could not extract it (status 2)", said) + self.assertNotIn("no unsquashfs", said) + self.assertFalse(os.path.lexists("squashfs-root")) + + def runtime_elf(self): + head = bytearray(elf(183)) + struct.pack_into("<Q", head, 0x28, len(head)) + return bytes(head) + + def dwarfs(self, body): + self.write(self.image, self.runtime_elf() + b"DWARFS\x02\x05payload", 0o755) + self.ran = self.tmp / "dwarfsextract-ran" + return str(self.write(self.tmp / "dwarfsextract", "#!/bin/sh\ntouch %s\n%s" % (self.ran, body), 0o755)) + + def test_a_dwarfs_image_the_runtime_cannot_unpack_is_read_through_its_open_descriptor(self): + reader = self.dwarfs( + '[ "$1 $3 $4 $5" = "--input --image-offset=64 --output squashfs-root" ] || exit 9\n' + 'case $2 in /proc/self/fd/*) ;; *) exit 8 ;; esac\n' + 'cmp -s "$2" "%s" || exit 7\ntouch squashfs-root/AppRun\n' % self.image) + tool = self.uruntime("echo 'Failed to execute dwarfsextract: EACCES: Permission denied' >&2\nexit 1\n") + with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}), \ + mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}), \ + mock.patch("shutil.which", return_value=None): + status, said = self.quiet(FEX["extract"], "image.AppImage") + self.assertEqual(status, 0) + self.assertIn("uruntime could not extract it (status 1)", said) + self.assertNotIn("dwarfsextract could not", said) + self.assertTrue(Path("squashfs-root/AppRun").is_file()) + self.assertFalse((self.home / ".config/droiddeck/fex-wanted").exists()) + + def test_a_dwarfs_image_the_runtime_unpacks_never_runs_dwarfsextract(self): + reader = self.dwarfs("touch squashfs-root/AppRun\n") + tool = self.uruntime("mkdir -p AppDir && touch AppDir/AppRun\n") + with mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}): + status, said = self.quiet(FEX["extract"], "image.AppImage") + self.assertEqual((status, said), (0, "")) + self.assertFalse(self.ran.exists()) + + def test_a_dwarfsextract_failure_leaves_nothing_unpacked(self): + reader = self.dwarfs("mkdir -p squashfs-root/usr\nexit 3\n") + tool = self.uruntime("exit 1\n") + with mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}), \ + mock.patch("shutil.which", return_value=None): + status, said = self.quiet(FEX["extract"], "image.AppImage") + self.assertEqual(status, 1) + self.assertTrue(self.ran.exists()) + self.assertIn("dwarfsextract could not extract it (status 3)", said) + self.assertFalse(os.path.lexists("squashfs-root")) + + def test_a_squashfs_image_still_goes_to_unsquashfs(self): + reader = self.dwarfs("exit 0\n") + self.write(self.image, self.runtime_elf() + b"hsqs" + b"payload", 0o755) + tool = self.uruntime("exit 1\n") + with mock.patch.dict(G, {"DWARFSEXTRACT": reader}): + status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"}) + self.assertEqual(status, 0) + self.assertNotIn("dwarfsextract", said) + self.assertEqual(["/usr/bin/unsquashfs", "/usr/bin/7z"], [c[0] for c in commands]) + class LaunchTest(FexTestCase): def test_the_guest_environment(self): @@ -1055,6 +1192,12 @@ class LaunchTest(FexTestCase): guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"}) self.assertNotIn("GLIBC_TUNABLES", guest) + def test_host_iconv_modules_stay_on_the_host(self): + guest = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/r/usr/lib/aarch64-linux-gnu/gconv"}) + self.assertEqual(guest["GCONV_PATH"], "") + own = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/opt/gconv"}) + self.assertEqual(own["GCONV_PATH"], "/opt/gconv") + def test_proton_runs_in_the_runtime_its_manifest_requires(self): self.fex_tool() self.runtime() diff --git a/tools/tests/test_droiddeckctl_gamepad.py b/tools/tests/test_droiddeckctl_gamepad.py new file mode 100644 index 0000000000..201a92e599 --- /dev/null +++ b/tools/tests/test_droiddeckctl_gamepad.py @@ -0,0 +1,91 @@ +import json +import unittest + +from test_droiddeckctl import FakeAdbTest, ctl + + +def key_frames(commands): + found = [] + for command in commands: + if command["command"] == "inject": + events = command["events"] + found.append({code: value for code, value in zip(events[1::3], events[2::3]) if code != "SYN_REPORT"}) + return found + + +class GamepadTest(FakeAdbTest): + def setUp(self): + super().setUp() + self.configure({}) + + def gamepad(self, *argv): + return self.run_ctl("input", "gamepad", *argv) + + def script(self): + [call] = [c for c in self.calls() if c["args"][:3] == ["shell", "uinput", "-"]] + return [json.loads(line) for line in call["stdin"].splitlines()] + + def test_buttons_are_pressed_in_order_on_a_real_looking_gamepad(self): + code, out = self.gamepad("b", "rb", "--hold", "50", "--gap", "100") + self.assertEqual(0, code) + self.assertEqual({"ok": True, "command": "input", "type": "gamepad", "buttons": ["b", "rb"], "deviceSerial": "fake-1"}, + {k: v for k, v in out.items() if k != "ms"}) + self.assertFalse(self.calls("input")) + commands = self.script() + register = commands[0] + bits = {c["type"]: c["data"] for c in register["configuration"]} + self.assertEqual(("register", "usb", ["EV_KEY", "EV_ABS"]), (register["command"], register["bus"], bits["UI_SET_EVBIT"])) + self.assertFalse(register["name"].lower().startswith(("uinput-", "uinput_"))) + self.assertTrue({"BTN_SOUTH", "BTN_EAST", "BTN_TL", "BTN_TR", "BTN_START"} <= set(bits["UI_SET_KEYBIT"])) + self.assertEqual(set(bits["UI_SET_ABSBIT"]), {a["code"] for a in register["abs_info"]}) + self.assertEqual({"id": 1, "command": "delay", "duration": ctl.UINPUT_REGISTER_MS}, commands[1]) + self.assertEqual([{"BTN_EAST": 1}, {"BTN_EAST": 0}, {"BTN_TR": 1}, {"BTN_TR": 0}], key_frames(commands)) + self.assertEqual([50, 100, 50, 100], [c["duration"] for c in commands[2:-2] if c["command"] == "delay"]) + self.assertEqual({"id": 1, "command": "sync", "syncToken": ctl.GAMEPAD_SYNC}, commands[-1]) + + def test_a_zero_gap_sends_no_empty_delay_which_android_rejects(self): + code, _ = self.gamepad("a", "b", "--hold", "40", "--gap", "0") + self.assertEqual(0, code) + commands = self.script() + self.assertEqual([{"BTN_SOUTH": 1}, {"BTN_SOUTH": 0}, {"BTN_EAST": 1}, {"BTN_EAST": 0}], key_frames(commands)) + self.assertEqual([], [c for c in commands if c["command"] == "delay" and c["duration"] <= 0]) + self.assertEqual([40, 40], [c["duration"] for c in commands[2:-2] if c["command"] == "delay"]) + + def test_a_dpad_release_never_runs_into_the_next_press_even_at_zero_gap(self): + code, _ = self.gamepad("left", "left", "--hold", "40", "--gap", "0") + self.assertEqual(0, code) + commands = self.script() + self.assertEqual([{"ABS_HAT0X": -1}, {"ABS_HAT0X": 0}, {"ABS_HAT0X": -1}, {"ABS_HAT0X": 0}], key_frames(commands)) + self.assertEqual([40, ctl.GAMEPAD_DPAD_MIN_GAP_MS, 40, ctl.GAMEPAD_DPAD_MIN_GAP_MS], + [c["duration"] for c in commands[2:-2] if c["command"] == "delay"]) + + def test_the_dpad_uses_the_hat_axes(self): + code, _ = self.gamepad("up", "right", "down", "left") + self.assertEqual(0, code) + self.assertEqual([{"ABS_HAT0Y": -1}, {"ABS_HAT0Y": 0}, {"ABS_HAT0X": 1}, {"ABS_HAT0X": 0}, + {"ABS_HAT0Y": 1}, {"ABS_HAT0Y": 0}, {"ABS_HAT0X": -1}, {"ABS_HAT0X": 0}], + key_frames(self.script())) + + def test_an_unknown_button_or_bad_timing_is_refused_before_touching_the_device(self): + for argv, message in ((("nope",), "Unknown gamepad button 'nope'"), (("a", "--hold", "1"), "--hold must be"), + (("a", "--gap", "-5"), "--gap 0..5000")): + with self.subTest(argv=argv): + code, out = self.gamepad(*argv) + self.assertEqual((2, "INVALID_INPUT"), (code, out["error"]["code"])) + self.assertIn(message, out["error"]["message"]) + self.assertFalse(self.calls()) + + def test_a_shell_without_uinput_is_unavailable(self): + self.configure({}, uinput_probe="no-dev-uinput") + code, out = self.gamepad("a") + self.assertEqual((3, "UINPUT_UNAVAILABLE"), (code, out["error"]["code"])) + self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "uinput"]]) + + def test_uinput_that_stops_early_fails(self): + self.configure({}, uinput_stdout="") + code, out = self.gamepad("a") + self.assertEqual((3, "UINPUT_FAILED"), (code, out["error"]["code"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_effects_source_resolution.py b/tools/tests/test_effects_source_resolution.py index aae6052cec..cd63c69d64 100644 --- a/tools/tests/test_effects_source_resolution.py +++ b/tools/tests/test_effects_source_resolution.py @@ -26,7 +26,7 @@ class EffectsSourceResolutionTest(unittest.TestCase): header = (REPO / 'app/src/main/cpp/waylandcomp/src/vk_present.h').read_text() effects = (REPO / 'app/src/main/cpp/waylandcomp/src/effects_chain.c').read_text() functions = '\n'.join(function(source, signature) for signature in ( - 'static void release_external_client_image(', 'static void release_external_client_draws(', + 'static int foreign_image(', 'static void release_external_client_image(', 'static void release_external_client_draws(', 'static int map_draw(', 'static int draw_to_blit(', 'static int draw_to_scene_blit(', 'static int effects_source_draw(', 'static void effects_source_note(', @@ -113,7 +113,7 @@ TYPES = r''' #include <stdio.h> #include <stdlib.h> #include <string.h> -typedef int VkImage, VkDeviceMemory, VkFormat, VkCommandBuffer, VkResult, VkFilter; +typedef int VkImage, VkDeviceMemory, VkFormat, VkCommandBuffer, VkResult, VkFilter, VkBuffer; typedef int VkImageLayout, VkPipelineStageFlags, VkImageUsageFlags; typedef uint64_t VkDeviceSize; typedef struct { unsigned width, height; } VkExtent2D; @@ -126,6 +126,13 @@ typedef struct { VkImageSubresourceLayers dstSubresource; VkOffset3D dstOffsets[2]; } VkImageBlit; +typedef struct { + VkDeviceSize bufferOffset; + unsigned bufferRowLength, bufferImageHeight; + VkImageSubresourceLayers imageSubresource; + VkOffset3D imageOffset; + struct { unsigned width, height, depth; } imageExtent; +} VkBufferImageCopy; typedef struct { int sType, flags; } VkCommandBufferBeginInfo; typedef struct { int sType, oldLayout, newLayout, srcQueueFamilyIndex, dstQueueFamilyIndex; @@ -161,6 +168,8 @@ typedef struct AHardwareBuffer AHardwareBuffer; STUBS = r''' +static void stage_linear_dmabufs(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) { (void)cmd; (void)draws; (void)count; } +static int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) { return dmabuf && !staged; } static void quarantine_pending_work(VkResult result, const char *where) { (void)result; (void)where; } static int noop(int handle, ...) { return VK_SUCCESS; } static VkImageMemoryBarrier recorded_barriers[64]; @@ -194,7 +203,7 @@ static struct { float kx, ky, off_x, off_y; int rx, ry, rw, rh; } g_map; static struct { VkImage img; int w, h; } g_scene; struct vkp_img_slot { VkImage img; int w, h; }; static struct vkp_img_slot g_hdrscene, g_fgscene; -static struct { int active, rw, rh; VkImage result; } g_pass; +static struct { int active, rw, rh, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; static struct { int64_t present_ns, present_max_ns; unsigned presents; } g_perf; static int effects_active = 1, framegen, cardboard; struct fx_settings { int scaling, cas_on, cas_pct; }; @@ -359,7 +368,7 @@ static void run_path(int offscreen, const struct vkp_draw *draw, int n, const st assert(n > 0 && n <= 4); memcpy(before, draw, n * sizeof(*draw)); int rw = 0, rh = 0; - assert((offscreen ? pass_begin_impl(1920, 1080, draw, n, hdr, &rw, &rh) + assert((offscreen ? pass_begin_impl(1920, 1080, draw, n, hdr, 0, &rw, &rh) : render_impl(1920, 1080, draw, n, hdr, NULL)) == 0); assert(memcmp(draw, before, n * sizeof(*draw)) == 0); if (offscreen) assert(rw == (fail_effects ? effects_w : (int)g_extent.width) && @@ -384,7 +393,7 @@ static void check_path(int offscreen) { run_path(offscreen, &draw, 1, NULL); check_input(1280, 720); reset(); draw = fullscreen(); draw.dw = 1280; draw.dh = 720; int rw, rh; - assert((offscreen ? pass_begin_impl(1280, 720, &draw, 1, NULL, &rw, &rh) + assert((offscreen ? pass_begin_impl(1280, 720, &draw, 1, NULL, 0, &rw, &rh) : render_impl(1280, 720, &draw, 1, NULL, NULL)) == 0); check_input(1280, 720); } diff --git a/tools/tests/test_fex_fd_exec.py b/tools/tests/test_fex_fd_exec.py new file mode 100644 index 0000000000..4b917ec539 --- /dev/null +++ b/tools/tests/test_fex_fd_exec.py @@ -0,0 +1,35 @@ +import re +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch" +SYSCALLS = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp" +INTERPRETER = "Source/Tools/FEXInterpreter/FEXInterpreter.cpp" + + +def lines(sign): + return [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith(sign) and not line.startswith(sign * 3)] + + +class FexFdExecTest(unittest.TestCase): + def test_only_the_execve_handler_and_the_interpreter_change(self): + self.assertEqual([INTERPRETER, SYSCALLS], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)) + + def test_a_descriptor_exec_keeps_the_callers_argv0(self): + self.assertIn("if (!NeedsLoaderFD) {", lines("-")) + self.assertIn("if (!NeedsLoaderFD && !IsFDExec) {", lines("+")) + + def test_an_anonymous_program_reports_its_recovered_path(self): + self.assertIn('FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, "<Anonymous>");', lines("-")) + self.assertIn("FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, Program.ProgramPath);", lines("+")) + + def test_the_config_name_stays_anonymous(self): + self.assertNotIn('FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, "<Anonymous>");', lines("-")) + + def test_no_comments_are_added(self): + self.assertFalse([line for line in lines("+") if line.startswith(("//", "/*"))]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_gl_thunk_overlay.py b/tools/tests/test_fex_gl_thunk_overlay.py new file mode 100644 index 0000000000..e06d59e632 --- /dev/null +++ b/tools/tests/test_fex_gl_thunk_overlay.py @@ -0,0 +1,29 @@ +from pathlib import Path +import re +import unittest + +PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0015-gl-thunk-overlays-libopengl.patch" + + +def hunk(sign): + lines = [line for line in PATCH.read_text().splitlines() if not line.startswith(("diff ", "index ", "--- ", "+++ ", "@@"))] + return re.findall(r'"([^"]+)"', "\n".join(line[1:] for line in lines if line[:1] in (" ", sign))) + + +class FexGlThunkOverlayTest(unittest.TestCase): + def test_libopengl_joins_the_gl_overlay(self): + before, after = hunk("-"), hunk("+") + self.assertNotIn("@PREFIX_LIB@/libOpenGL.so.0", before) + self.assertIn("@PREFIX_LIB@/libOpenGL.so.0", after) + self.assertIn("@PREFIX_LIB@/libOpenGL.so.0.0.0", after) + self.assertEqual([path for path in before if path.startswith("@PREFIX_LIB@/libGL.")], + [path for path in after if path.startswith("@PREFIX_LIB@/libGL.")]) + self.assertLess(after.index("@PREFIX_LIB@/libGL.so.1.7.0"), after.index("Vulkan")) + self.assertLess(after.index("@PREFIX_LIB@/libOpenGL.so.0.0.0"), after.index("Vulkan")) + + def test_patch_touches_only_the_thunks_database(self): + self.assertEqual(["Data/ThunksDB.json"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_guest_preload.py b/tools/tests/test_fex_guest_preload.py new file mode 100644 index 0000000000..4b2f200bc0 --- /dev/null +++ b/tools/tests/test_fex_guest_preload.py @@ -0,0 +1,120 @@ +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0014-guest-preload-drops-host-libraries.patch" + +HARNESS = r""" +#include <cstdio> +#include <cstring> +#include <elf.h> +#include <fcntl.h> +#include <string> +#include <unistd.h> +namespace fextl { using string = std::string; } +namespace ELFLoader { +struct ELFContainer { + enum ELFType { TYPE_NONE, TYPE_X86_64, TYPE_X86_32, TYPE_OTHER_ELF }; + static ELFType GetELFType(const std::string& Filename) { + int FD = open(Filename.c_str(), O_RDONLY | O_CLOEXEC); + if (FD == -1) return TYPE_NONE; + Elf64_Ehdr Header {}; + ssize_t Read = pread(FD, &Header, sizeof(Header), 0); + close(FD); + if (Read < (ssize_t)sizeof(Header) || memcmp(Header.e_ident, ELFMAG, SELFMAG) != 0) return TYPE_NONE; + if (Header.e_machine == EM_X86_64) return TYPE_X86_64; + if (Header.e_machine == EM_386) return TYPE_X86_32; + return TYPE_OTHER_ELF; + } +}; +} +struct Loader { + static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) { return RootFS + File; } + GUEST_PRELOAD +}; +int main(int argc, char** argv) { + std::printf("%s", Loader::GuestPreload(argv[1], argv[2]).c_str()); +} +""" + + +def x86_compiler(): + for name in ("x86_64-linux-gnu-gcc", "gcc"): + path = shutil.which(name) + if path and subprocess.run([path, "-dumpmachine"], capture_output=True, text=True).stdout.startswith("x86_64"): + return path + return None + + +X86_CC = x86_compiler() + + +def patch_function(): + lines = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + body = "\n".join(lines) + first = body.index(" static fextl::string GuestPreload(") + last = body.index("\n }\n", first) + len("\n }\n") + return body[first:last] + + +@unittest.skipUnless(shutil.which("g++") and X86_CC and shutil.which("aarch64-linux-gnu-gcc"), "needs g++, an x86-64 gcc and aarch64-linux-gnu-gcc") +class FexGuestPreloadTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.dir = Path(cls.tmp.name) + source = cls.dir / "harness.cpp" + source.write_text(HARNESS.replace("GUEST_PRELOAD", patch_function())) + cls.binary = cls.dir / "harness" + subprocess.run(["g++", "-std=c++20", "-O1", "-o", str(cls.binary), str(source)], check=True) + stub = cls.dir / "stub.c" + stub.write_text("int stub(void) { return 0; }\n") + cls.host = cls.dir / "host" + cls.rootfs = cls.dir / "rootfs" + cls.shadow = cls.host / "lib/libshadow.so" + cls.rootfs_shadow = Path(str(cls.rootfs) + str(cls.shadow)) + for folder in (cls.host / "lib", cls.rootfs_shadow.parent): + folder.mkdir(parents=True) + cls.compile("aarch64-linux-gnu-gcc", stub, cls.host / "lib/libhost.so") + cls.compile(X86_CC, stub, cls.host / "lib/libguest.so") + cls.compile("aarch64-linux-gnu-gcc", stub, cls.shadow) + cls.compile(X86_CC, stub, cls.rootfs_shadow) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + @staticmethod + def compile(compiler, source, output): + subprocess.run([compiler, "-shared", "-fPIC", "-o", str(output), str(source)], check=True) + + def preload(self, value, rootfs=None): + root = str(self.rootfs) if rootfs is None else rootfs + return subprocess.run([str(self.binary), value, root], check=True, capture_output=True, text=True).stdout + + def test_host_libraries_leave_the_guest_list(self): + host, guest = self.host / "lib/libhost.so", self.host / "lib/libguest.so" + self.assertEqual(str(guest), self.preload(f"{host}:{guest}")) + self.assertEqual("", self.preload(str(host))) + + def test_rootfs_copy_decides_before_the_host_path(self): + self.assertEqual(str(self.shadow), self.preload(str(self.shadow))) + self.assertEqual("", self.preload(str(self.shadow), "")) + + def test_names_missing_files_and_separators_are_kept(self): + missing = str(self.dir / "missing.so") + guest = str(self.host / "lib/libguest.so") + self.assertEqual(f"libgamemodeauto.so.0:{missing}:{guest}", + self.preload(f" libgamemodeauto.so.0::{missing} {guest}:")) + + def test_patch_adds_no_comments(self): + added = [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + self.assertFalse([line for line in added if line.startswith(("//", "/*"))]) + self.assertEqual(["Source/Tools/FEXInterpreter/ELFCodeLoader.h"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_identity_syscalls.py b/tools/tests/test_fex_identity_syscalls.py new file mode 100644 index 0000000000..3c2101c824 --- /dev/null +++ b/tools/tests/test_fex_identity_syscalls.py @@ -0,0 +1,148 @@ +import os +import re +import subprocess +import tempfile +import unittest +from pathlib import Path + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0016-identity-syscalls-through-libc.patch" +HOOK = REPO / "tools/nativeguest/hook/privileged.c" +HOOK_BUILD = REPO / "tools/nativeguest/build.sh" +PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp" +REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);") +IDENTITY = {"getuid", "getgid", "geteuid", "getegid", "setuid", "setgid", "setreuid", "setregid", "getgroups", + "setgroups", "setresuid", "getresuid", "setresgid", "getresgid", "setfsuid", "setfsgid", "fchown"} + + +def changed(): + removed, added = {}, {} + for line in PATCH.read_text().splitlines(): + found = REGISTER.search(line) + if found and line[:1] in "+-": + (added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:] + return removed, added + + +class FexIdentitySyscallsTest(unittest.TestCase): + def test_only_the_passthrough_table_changes(self): + self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH]) + + def test_each_identity_syscall_keeps_its_arity_and_goes_through_libc(self): + removed, added = changed() + self.assertEqual(sorted(removed), sorted(added)) + self.assertEqual(IDENTITY, {number for _, _, number in added.values()}) + for name, (template, arity, number) in added.items(): + with self.subTest(name=name): + self.assertEqual(("SyscallPassthrough", arity, number), removed[name]) + self.assertEqual("SyscallPathPassthrough", template) + + def test_the_new_template_calls_the_libc_syscall(self): + added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + self.assertEqual([" uint64_t Result = ::syscall(syscall_num);"], [line for line in added if "Result =" in line]) + self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))]) + + def test_every_routed_syscall_is_answered_by_the_hook(self): + hook = HOOK.read_text() + for number in IDENTITY: + with self.subTest(number=number): + self.assertIn(f"number == __NR_{number})", hook) + + +PROBE = r""" +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <sys/mman.h> +#include <sys/syscall.h> +#include <unistd.h> + +int main(int argc, char **argv) { + unsigned int r = 7, e = 7, s = 7; + long rc = syscall(SYS_getresuid, &r, &e, &s); + printf("getresuid %ld %u %u %u\n", rc, r, e, s); + errno = 0; + rc = syscall(SYS_getresuid, NULL, &e, &s); + printf("getresuid-null %ld %d\n", rc, errno); + r = e = s = 7; + rc = syscall(SYS_getresgid, &r, &e, &s); + printf("getresgid %ld %u %u %u\n", rc, r, e, s); + errno = 0; + rc = syscall(SYS_getresgid, &r, NULL, &s); + printf("getresgid-null %ld %d\n", rc, errno); + unsigned int *locked = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + errno = 0; + rc = syscall(SYS_getresuid, &r, &e, locked); + printf("getresuid-readonly %ld %d\n", rc, errno); + errno = 0; + rc = syscall(SYS_getresgid, locked, &e, &s); + printf("getresgid-readonly %ld %d\n", rc, errno); + gid_t groups[8]; + rc = syscall(SYS_getgroups, 8, groups); + printf("getgroups %ld %u\n", rc, rc > 0 ? groups[0] : 99u); + errno = 0; + rc = syscall(SYS_getgroups, 8, locked); + printf("getgroups-readonly %ld %d\n", rc, errno); + int fd = open(argv[1], O_RDONLY); + printf("fchown %ld\n", syscall(SYS_fchown, fd, 4321, 4321)); + printf("getuid %ld\n", syscall(SYS_getuid)); + return 0; +} +""" + + +class NativeHookIdentityTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True) + (tmp / "root").mkdir() + cls.file = tmp / "owned" + cls.file.write_text("") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def probe(self): + hook_env = {"DDNATV_ROOT": str(Path(self.tmp.name) / "root"), "LD_PRELOAD": str(self.hook)} + env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe"), str(self.file)], env=env, + capture_output=True, text=True, timeout=120) + self.assertEqual(0, out.returncode, out.stderr) + return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in out.stdout.splitlines()} + + def test_the_hook_answers_identity_syscalls_as_root(self): + result = self.probe() + self.assertEqual("0 0 0 0", result["getresuid"]) + self.assertEqual("0 0 0 0", result["getresgid"]) + self.assertEqual("1 0", result["getgroups"]) + self.assertEqual("-1 14", result["getgroups-readonly"]) + self.assertEqual("0", result["fchown"]) + self.assertEqual("0", result["getuid"]) + + def test_a_missing_pointer_still_faults(self): + result = self.probe() + self.assertEqual("-1 14", result["getresuid-null"]) + self.assertEqual("-1 14", result["getresgid-null"]) + self.assertEqual("-1 14", result["getresuid-readonly"]) + self.assertEqual("-1 14", result["getresgid-readonly"]) + self.assertEqual(os.stat(self.file).st_uid, os.getuid()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_path_syscalls.py b/tools/tests/test_fex_path_syscalls.py new file mode 100644 index 0000000000..203f2eaac1 --- /dev/null +++ b/tools/tests/test_fex_path_syscalls.py @@ -0,0 +1,49 @@ +import re +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0013-path-syscalls-through-libc.patch" +HOOK = REPO / "tools/nativeguest/hook/privileged.c" +PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp" +REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);") + + +def changed(): + removed, added = {}, {} + for line in PATCH.read_text().splitlines(): + found = REGISTER.search(line) + if found and line[:1] in "+-": + (added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:] + return removed, added + + +class FexPathSyscallsTest(unittest.TestCase): + def test_only_the_passthrough_table_changes(self): + self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH]) + + def test_each_path_syscall_keeps_its_arity_and_goes_through_libc(self): + removed, added = changed() + self.assertEqual(sorted(removed), sorted(added)) + self.assertGreater(len(added), 10) + for name, (template, arity, number) in added.items(): + with self.subTest(name=name): + self.assertEqual(("SyscallPassthrough", arity, number), removed[name]) + self.assertEqual("SyscallPathPassthrough", template) + + def test_the_new_templates_call_the_libc_syscall(self): + added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + calls = [line for line in added if "syscall(" in line and "Result" in line] + self.assertEqual(5, len(calls)) + self.assertTrue(all("::syscall(syscall_num" in line for line in calls)) + self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))]) + + def test_every_routed_syscall_is_rewritten_by_the_hook(self): + hook = HOOK.read_text() + for name, (_, _, number) in changed()[1].items(): + with self.subTest(name=name): + self.assertIn(f"number == __NR_{number})", hook) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_signal_handler_escape.py b/tools/tests/test_fex_signal_handler_escape.py new file mode 100644 index 0000000000..c208b874bf --- /dev/null +++ b/tools/tests/test_fex_signal_handler_escape.py @@ -0,0 +1,117 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0009-signal-handler-escape-frees-host-stack.patch" +PROBE = FEX / "probes/signal-handler-escape.c" +DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp" +CONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h" +THREADS = "Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h" +FIELDS = ["PrevGuestFrame", "GuestFrameEnd", "GuestInterruptedSP", "GuestAltBase", "GuestAltEnd"] + + +def files(): + sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M) + return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)} + + +def hunks(section): + return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M) + + +def added(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(body): + return [line for line in body.splitlines() if line.startswith("-") and not line.startswith("---")] + + +class SignalHandlerEscapeTest(unittest.TestCase): + def test_only_signal_state_files_change(self): + self.assertEqual(sorted(files()), sorted([CONTEXT, DELEGATOR, THREADS])) + + def test_nothing_is_removed(self): + for name, section in files().items(): + self.assertEqual(removed(section), [], name) + + def test_added_code_has_no_comments(self): + for name, section in files().items(): + for line in added(section): + self.assertFalse("//" in line or "/*" in line, f"{name}: {line}") + + def test_both_context_backups_record_the_guest_frame(self): + lines = added(files()[CONTEXT]) + self.assertEqual(lines, [f"uint64_t {field};" for field in FIELDS] * 2) + + def test_each_thread_keeps_its_frame_chain(self): + self.assertEqual([line for line in added(files()[THREADS]) if line], ["uint64_t GuestFrames {};", "uint32_t GuestFrameCount {};"]) + + def test_delivery_pushes_and_reclaims_only_left_frames_at_the_dispatch_level(self): + found = hunks(files()[DELEGATOR]) + delivery = "".join(body for function, body in found if "HandleDispatcherGuestSignal" in function) + lines = added(delivery) + self.assertIn("#ifdef ARCHITECTURE_arm64", lines) + gate = " ".join(lines) + self.assertIn("WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames", gate) + self.assertIn("Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1", gate) + self.assertIn("GuestLeftFrame(Newest, OldGuestSP", gate) + self.assertIn("ContextBackup->PrevSP = HostTop;", lines) + self.assertIn("Frame->SignalHandlerRefCounter -= LeftFrames;", lines) + self.assertIn("SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(ContextBackup);", lines) + self.assertIn("++SignalInfo.GuestFrameCount;", lines) + self.assertLess(lines.index("#endif"), lines.index("ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames;")) + + def test_signal_return_pops_its_frame_and_any_newer_ones(self): + found = hunks(files()[DELEGATOR]) + restore = "".join(body for function, body in found if "RestoreThreadState" in function) + lines = added(restore) + self.assertIn("if (Entry == OldSP) {", lines) + self.assertIn("SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame;", lines) + self.assertIn("Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1;", lines) + self.assertNotIn("TYPE_PAUSE", " ".join(lines)) + + def test_thread_stop_clears_the_chain(self): + found = hunks(files()[DELEGATOR]) + pause = "".join(body for function, body in found if "HandleSignalPause" in function) + self.assertEqual(added(pause), ["ThreadObject->SignalInfo.GuestFrames = 0;", "ThreadObject->SignalInfo.GuestFrameCount = 0;"]) + + def test_patch_follows_the_syscall_state_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0008-signal-return-restores-syscall-state.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class SignalHandlerEscapeProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-escape-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_survives_every_escape(self): + result = subprocess.run([str(self.binary), "20000"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + for phase in ("onstack", "offstack", "mixed", "returns", "outer"): + self.assertEqual(counts[phase], "20000", phase) + self.assertEqual(counts["nested"], "60000") + self.assertEqual(counts["wrong"], "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_signal_register_update.py b/tools/tests/test_fex_signal_register_update.py new file mode 100644 index 0000000000..dabc5afff3 --- /dev/null +++ b/tools/tests/test_fex_signal_register_update.py @@ -0,0 +1,134 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch" +PROBE = FEX / "probes/signal-register-update.c" +HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h" +FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp" +X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"] + + +def files(): + sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M) + return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)} + + +def added(section): + return [line[1:].strip() for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(section): + return [line[1:].strip() for line in section.splitlines() if line.startswith("-") and not line.startswith("---")] + + +def helper(): + lines = added(files()[FRAMES]) + start = next(i for i, line in enumerate(lines) if line.startswith("void SignalDelegator::ResumeWithGuestGPRs(")) + end = lines.index("#endif", start) + return lines[start:end + 1] + + +class SignalRegisterUpdateTest(unittest.TestCase): + def test_only_signal_frame_files_change(self): + self.assertEqual(sorted(files()), sorted([FRAMES, HEADER])) + + def test_patch_only_adds_code(self): + for name, section in files().items(): + self.assertEqual(removed(section), [], name) + + def test_added_code_has_no_comments(self): + for name, section in files().items(): + for line in added(section): + self.assertNotIn("//", line, name) + self.assertNotIn("/*", line, name) + + def test_helper_is_declared_once(self): + self.assertEqual(sum(line.startswith("void ResumeWithGuestGPRs(") for line in added(files()[HEADER])), 1) + + def test_only_changed_registers_are_written_back(self): + body = helper() + self.assertIn("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {", body) + self.assertEqual(body[body.index("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {") + 1], "continue;") + + def test_spilled_registers_go_to_the_frame_and_live_ones_to_host_registers(self): + body = helper() + self.assertIn("const bool InFrame = AllSpilled || (Spilled & (1U << HostReg));", body) + self.assertIn("Frame->State.gregs[i] = GuestGPRs[i];", body) + self.assertIn("ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]);", body) + self.assertIn("for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) {", body) + + def test_signals_outside_jit_code_are_left_alone(self): + body = helper() + guard = body.index("if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {") + self.assertEqual(body[guard + 1], "return;") + self.assertEqual(body[2], "#ifdef ARCHITECTURE_arm64") + + def test_every_frame_type_applies_registers_when_rip_is_unchanged(self): + lines = added(files()[FRAMES]) + calls = [line for line in lines if line.startswith("ResumeWithGuestGPRs(")] + self.assertEqual(calls, [ + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL);", + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);", + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);", + ]) + branches = [lines[i + 1] for i, line in enumerate(lines[:-1]) if line == "} else {" and lines[i + 1].startswith("uint64_t GuestGPRs[")] + self.assertEqual(branches, ["uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS];", "uint64_t GuestGPRs[8];", "uint64_t GuestGPRs[8];"]) + + def test_registers_are_stored_by_guest_register_index(self): + lines = added(files()[FRAMES]) + x64 = [m.group(1) for line in lines for m in [re.fullmatch(r"COPY_REG\((\w+)\);", line)] if m] + self.assertEqual(sorted(x64), sorted(X64_ORDER)) + self.assertIn("#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x];", lines) + legacy = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->sc\.(\w+);", "\n".join(lines)) + self.assertEqual(sorted(legacy), sorted((r, r[1:].lower()) for r in X64_ORDER[:8])) + rt = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->uc\.uc_mcontext\.gregs\[FEXCore::x86::FEX_REG_(\w+)\];", "\n".join(lines)) + self.assertEqual(sorted(rt), sorted((r, r) for r in X64_ORDER[:8])) + + def test_patch_follows_the_thunk_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0011-thunk-calls-mark-spilled-state.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code") +class SignalRegisterUpdateProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not cls.compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-regs-")) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def build(self, *flags): + binary = self.tmp / ("probe" + "".join(flags)) + result = subprocess.run([self.compiler, "-O2", *flags, "-o", str(binary), str(PROBE)], capture_output=True, text=True) + return binary if result.returncode == 0 else None + + def check(self, binary, *args): + result = subprocess.run([str(binary), *args], capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout) + self.assertIn("seen=1", result.stdout) + + def test_native_kernel_applies_handler_register_changes(self): + self.check(self.build()) + + def test_native_kernel_applies_handler_register_changes_in_32_bit_frames(self): + binary = self.build("-m32") + if binary is None: + self.skipTest("no 32-bit toolchain") + self.check(binary) + self.check(binary, "legacy") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_signal_syscall_state.py b/tools/tests/test_fex_signal_syscall_state.py new file mode 100644 index 0000000000..5638a41fea --- /dev/null +++ b/tools/tests/test_fex_signal_syscall_state.py @@ -0,0 +1,78 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0008-signal-return-restores-syscall-state.patch" +PROBE = FEX / "probes/async-signal-context.c" +RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;" + + +def hunks(): + text = PATCH.read_text() + files = re.findall(r"^diff --git a/(\S+) ", text, re.M) + return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M) + + +class SignalReturnSyscallStateTest(unittest.TestCase): + def test_only_the_signal_delegator_changes(self): + files, found = hunks() + self.assertEqual(files, ["Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"]) + self.assertEqual(len(found), 1) + + def test_only_returns_to_jit_code_restore_the_saved_syscall_state(self): + _, found = hunks() + function, body = found[0] + self.assertIn("SignalDelegator::RestoreThreadState", function) + lines = body.splitlines() + added = [line[1:].strip() for line in lines if line.startswith("+")] + removed = [line for line in lines if line.startswith("-")] + self.assertEqual(added, [RESTORE]) + self.assertEqual(removed, []) + context = [line[1:].strip() for line in lines] + self.assertEqual(context[0], "auto Frame = Thread->CurrentFrame;") + in_jit = context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {") + restore = context.index(RESTORE) + self.assertLess(in_jit, restore) + self.assertEqual(context[restore + 1], "}") + self.assertLess(restore, context.index("RestoreFrame_x64(Thread, Context, Frame, ucontext);")) + + def test_thread_pause_returns_are_untouched(self): + _, found = hunks() + body = found[0][1] + self.assertNotIn("TYPE_PAUSE", "".join(line for line in body.splitlines() if line.startswith("+"))) + + def test_patch_is_applied_to_every_release(self): + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class AsyncSignalContextProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-async-signal-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-pthread", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_reports_the_interrupted_registers(self): + result = subprocess.run([str(self.binary), "500"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertGreaterEqual(int(counts["matched"]), 500) + self.assertEqual(counts["stale"], "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_smc_alias.py b/tools/tests/test_fex_smc_alias.py new file mode 100644 index 0000000000..2af888d77b --- /dev/null +++ b/tools/tests/test_fex_smc_alias.py @@ -0,0 +1,211 @@ +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0006-smc-alias-of-code-created-after-translation.patch" + +HARNESS = r""" +#include <algorithm> +#include <cstdint> +#include <cstdio> +#include <map> +#include <string> +#include <sys/mman.h> + +namespace FEXCore::Config { +enum { CONFIG_SMC_NONE, CONFIG_SMC_MTRACK, CONFIG_SMC_FULL }; +} +namespace LogMan::Throw { +template<typename... Args> void AFmt(bool, const char*, Args...) {} +} + +union VMAProt { + struct { bool Readable : 1; bool Writable : 1; bool Executable : 1; }; +}; +struct VMAFlags { bool Shared : 1; }; +struct MappedResource; +struct VMAEntry { + MappedResource* Resource; + VMAEntry* ResourcePrevVMA; + VMAEntry* ResourceNextVMA; + uint64_t Base, Offset, Length; + VMAFlags Flags; + VMAProt Prot; +}; +struct MappedResource { VMAEntry* FirstVMA; }; +struct VMATrackingT { + std::map<uint64_t, VMAEntry> VMAs; + std::map<uint64_t, VMAEntry>::const_iterator FindVMAEntry(uint64_t Addr) const { + auto it = VMAs.upper_bound(Addr); + if (it == VMAs.begin()) return VMAs.end(); + --it; + return Addr < it->first + it->second.Length ? it : VMAs.end(); + } +}; + +struct Recorded { uint64_t Address, Length; int Prot; }; +static Recorded calls[16]; +static int count; +static int fake_mprotect(void* address, size_t length, int prot) { + calls[count++] = {(uint64_t)address, length, prot}; + return 0; +} +#define mprotect fake_mprotect + +struct SyscallHandler { + int SMCChecks = FEXCore::Config::CONFIG_SMC_MTRACK; + VMATrackingT VMATracking; + void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length); +}; + +#include "extracted.inc" + +static MappedResource resource, other; + +int main(int argc, char** argv) { + std::string scenario = argc > 1 ? argv[1] : ""; + SyscallHandler handler; + VMAEntry code{}, alias{}; + code.Resource = &resource; + code.Base = 0x100000; + code.Offset = 0x10000; + code.Length = 0x4000; + code.Flags.Shared = true; + code.Prot.Readable = true; + code.Prot.Executable = true; + alias.Resource = &resource; + alias.Base = 0x700000; + alias.Offset = 0x10000; + alias.Length = 0x4000; + alias.Flags.Shared = true; + alias.Prot.Readable = true; + alias.Prot.Writable = true; + uint64_t base = alias.Base, length = alias.Length; + if (scenario == "disjoint") { + code.Offset = 0x80000; + } else if (scenario == "partial") { + code.Offset = 0x12000; + code.Length = 0x1000; + } else if (scenario == "tail") { + base += 0x2000; + length = 0x10000; + } else if (scenario == "gap") { + base -= 0x2000; + length = 0x6000; + } else if (scenario == "two") { + length = 0x6000; + } else if (scenario == "no_code") { + code.Prot.Executable = false; + } else if (scenario == "private") { + alias.Flags.Shared = false; + } else if (scenario == "read_only") { + alias.Prot.Writable = false; + } else if (scenario == "full") { + handler.SMCChecks = FEXCore::Config::CONFIG_SMC_FULL; + } else if (scenario == "none") { + handler.SMCChecks = FEXCore::Config::CONFIG_SMC_NONE; + } + code.ResourceNextVMA = &alias; + alias.ResourcePrevVMA = &code; + resource.FirstVMA = &code; + handler.VMATracking.VMAs[code.Base] = code; + handler.VMATracking.VMAs[alias.Base] = alias; + handler.VMATracking.VMAs[code.Base].ResourceNextVMA = &handler.VMATracking.VMAs[alias.Base]; + handler.VMATracking.VMAs[alias.Base].ResourcePrevVMA = &handler.VMATracking.VMAs[code.Base]; + resource.FirstVMA = &handler.VMATracking.VMAs[code.Base]; + handler.VMATracking.VMAs[code.Base].Resource = &resource; + handler.VMATracking.VMAs[alias.Base].Resource = &resource; + if (scenario == "two") { + VMAEntry& next_code = handler.VMATracking.VMAs[0x200000]; + VMAEntry& next_alias = handler.VMATracking.VMAs[0x704000]; + next_code = {}; + next_code.Resource = &other; + next_code.Base = 0x200000; + next_code.Length = 0x2000; + next_code.Flags.Shared = true; + next_code.Prot.Readable = true; + next_code.Prot.Executable = true; + next_alias = {}; + next_alias.Resource = &other; + next_alias.Base = 0x704000; + next_alias.Length = 0x2000; + next_alias.Flags.Shared = true; + next_alias.Prot.Readable = true; + next_alias.Prot.Writable = true; + next_code.ResourceNextVMA = &next_alias; + next_alias.ResourcePrevVMA = &next_code; + other.FirstVMA = &next_code; + } + handler.ProtectWritableAliasOfCode(base, length); + printf("%d", count); + for (int i = 0; i < count; i++) printf(" %llx+%llx:%d", (unsigned long long)calls[i].Address, (unsigned long long)calls[i].Length, calls[i].Prot); + printf("\n"); + return 0; +} +""" + + +def extracted(): + text = PATCH.read_text() + section = re.search(r"^diff --git a/\S*SyscallsSMCTracking\.cpp .*?(?=^diff --git |\Z)", text, re.S | re.M).group(0) + added = [line[1:] for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")] + body = "\n".join(added) + start = body.index("void SyscallHandler::ProtectWritableAliasOfCode") + end = body.index("\n}\n", start) + 3 + return body[start:end] + + +class SmcAliasTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("g++") or shutil.which("c++") + if not compiler: + raise unittest.SkipTest("no C++ compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-smc-alias-")) + (cls.tmp / "extracted.inc").write_text(extracted()) + (cls.tmp / "harness.cpp").write_text(HARNESS) + subprocess.run([compiler, "-std=c++20", "-fno-strict-aliasing", "-I", str(cls.tmp), "-o", str(cls.tmp / "harness"), str(cls.tmp / "harness.cpp")], + check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def run_scenario(self, name=""): + return subprocess.run([str(self.tmp / "harness"), name], check=True, capture_output=True, text=True).stdout.strip() + + def test_writable_alias_of_translated_code_is_read_only_until_it_faults(self): + self.assertEqual(self.run_scenario(), "1 700000+4000:1") + + def test_only_the_overlapping_part_of_the_alias_is_protected(self): + self.assertEqual(self.run_scenario("partial"), "1 702000+1000:1") + + def test_alias_beyond_the_mapping_end_is_clamped(self): + self.assertEqual(self.run_scenario("tail"), "1 702000+2000:1") + + def test_range_starting_in_a_gap_reaches_the_alias_after_it(self): + self.assertEqual(self.run_scenario("gap"), "1 700000+4000:1") + + def test_every_alias_in_one_range_is_protected(self): + self.assertEqual(self.run_scenario("two"), "2 700000+4000:1 704000+2000:1") + + def test_alias_of_another_file_range_is_untouched(self): + self.assertEqual(self.run_scenario("disjoint"), "0") + + def test_alias_without_an_executable_mirror_is_untouched(self): + self.assertEqual(self.run_scenario("no_code"), "0") + + def test_private_and_read_only_mappings_are_untouched(self): + self.assertEqual(self.run_scenario("private"), "0") + self.assertEqual(self.run_scenario("read_only"), "0") + + def test_explicit_smc_check_settings_are_respected(self): + self.assertEqual(self.run_scenario("full"), "0") + self.assertEqual(self.run_scenario("none"), "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_socket_credentials.py b/tools/tests/test_fex_socket_credentials.py new file mode 100644 index 0000000000..c8e13ea688 --- /dev/null +++ b/tools/tests/test_fex_socket_credentials.py @@ -0,0 +1,147 @@ +import os +import re +import subprocess +import tempfile +import unittest +from pathlib import Path + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0018-socket-credentials-through-libc.patch" +HOOK = REPO / "tools/nativeguest/hook/privileged.c" +HOOK_BUILD = REPO / "tools/nativeguest/build.sh" +PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp" +REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL_X64\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);") +ROUTED = {"sendmsg", "recvmsg", "getsockopt"} + + +def changed(): + removed, added = {}, {} + for line in PATCH.read_text().splitlines(): + found = REGISTER.search(line) + if found and line[:1] in "+-": + (added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:] + return removed, added + + +class FexSocketCredentialsTest(unittest.TestCase): + def test_only_the_passthrough_table_changes(self): + self.assertEqual([PASSTHROUGH], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)) + + def test_each_socket_call_keeps_its_arity_and_goes_through_libc(self): + removed, added = changed() + self.assertEqual(ROUTED, set(removed)) + self.assertEqual(ROUTED, set(added)) + for name, (template, arity, number) in added.items(): + with self.subTest(name=name): + self.assertEqual(name, number) + self.assertEqual(("SyscallPassthrough", arity, number), removed[name]) + self.assertEqual("SyscallPathPassthrough", template) + + def test_every_routed_call_is_answered_by_the_hook(self): + hook = HOOK.read_text() + for number in ROUTED: + with self.subTest(number=number): + self.assertIn(f"number == __NR_{number})", hook) + + +PROBE = r""" +#define _GNU_SOURCE +#include <errno.h> +#include <stdio.h> +#include <string.h> +#include <sys/socket.h> +#include <sys/syscall.h> +#include <unistd.h> + +int main(void) { + int sv[2], on = 1; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return 2; + setsockopt(sv[1], SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)); + struct ucred sent = {getpid(), (uid_t)syscall(SYS_getuid), (gid_t)syscall(SYS_getgid)}; + char byte = 0, ctrl[CMSG_SPACE(sizeof(struct ucred))]; + struct iovec iov = {&byte, 1}; + struct msghdr msg = {0}; + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = ctrl; + msg.msg_controllen = sizeof(ctrl); + struct cmsghdr *c = CMSG_FIRSTHDR(&msg); + c->cmsg_level = SOL_SOCKET; + c->cmsg_type = SCM_CREDENTIALS; + c->cmsg_len = CMSG_LEN(sizeof(sent)); + memcpy(CMSG_DATA(c), &sent, sizeof(sent)); + errno = 0; + long rc = syscall(SYS_sendmsg, sv[0], &msg, 0); + printf("sendmsg %ld %d %u\n", rc, errno, sent.uid); + char in_ctrl[CMSG_SPACE(sizeof(struct ucred))]; + struct msghdr in = {0}; + in.msg_iov = &iov; + in.msg_iovlen = 1; + in.msg_control = in_ctrl; + in.msg_controllen = sizeof(in_ctrl); + rc = syscall(SYS_recvmsg, sv[1], &in, MSG_DONTWAIT); + struct ucred got = {0, 99, 99}; + for (c = CMSG_FIRSTHDR(&in); c; c = CMSG_NXTHDR(&in, c)) + if (c->cmsg_type == SCM_CREDENTIALS) memcpy(&got, CMSG_DATA(c), sizeof(got)); + printf("recvmsg %ld %u\n", rc, got.uid); + struct ucred peer = {0, 99, 99}; + socklen_t len = sizeof(peer); + rc = syscall(SYS_getsockopt, sv[1], SOL_SOCKET, SO_PEERCRED, &peer, &len); + printf("peercred %ld %u\n", rc, peer.uid); + return 0; +} +""" + + +class NativeHookSocketCredentialsTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + if os.getuid() == 0: + raise unittest.SkipTest("root may send any credentials") + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True) + (tmp / "root").mkdir() + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def probe(self, hooked): + hook_env = {"DDNATV_ROOT": str(Path(self.tmp.name) / "root")} + if hooked: + hook_env["LD_PRELOAD"] = str(self.hook) + env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe")], env=env, capture_output=True, text=True, + timeout=120) + self.assertEqual(0, out.returncode, out.stderr) + return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in out.stdout.splitlines()} + + def test_root_credentials_sent_through_the_raw_call_reach_the_peer_as_root(self): + result = self.probe(hooked=True) + self.assertEqual("1 0 0", result["sendmsg"]) + self.assertEqual("1 0", result["recvmsg"]) + self.assertEqual("0 0", result["peercred"]) + + def test_without_the_hook_the_kernel_keeps_the_real_ids(self): + result = self.probe(hooked=False) + self.assertEqual(f"1 0 {os.getuid()}", result["sendmsg"]) + self.assertEqual(f"1 {os.getuid()}", result["recvmsg"]) + self.assertEqual(f"0 {os.getuid()}", result["peercred"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_syscall_host_stack.py b/tools/tests/test_fex_syscall_host_stack.py new file mode 100644 index 0000000000..018863cf59 --- /dev/null +++ b/tools/tests/test_fex_syscall_host_stack.py @@ -0,0 +1,67 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0010-syscall-exit-resets-host-stack.patch" +PROBE = FEX / "probes/syscall-host-stack.c" +BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp" + + +def hunks(): + text = PATCH.read_text() + files = re.findall(r"^diff --git a/(\S+) ", text, re.M) + return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M) + + +class SyscallHostStackTest(unittest.TestCase): + def test_only_the_branch_ops_change(self): + files, found = hunks() + self.assertEqual(files, [BRANCH_OPS]) + self.assertEqual(len(found), 2) + + def test_both_ops_that_leave_the_block_reset_the_stack_after_spilling(self): + _, found = hunks() + for (function, body), op in zip(found, ("DEF_OP(Syscall)", "DEF_OP(ThreadRemoveCodeEntry)")): + lines = body.splitlines() + added = [line[1:].strip() for line in lines if line.startswith("+")] + self.assertEqual([line for line in added if line], ["ResetStack();"], op) + self.assertEqual([line for line in lines if line.startswith("-")], [], op) + context = [line[1:].strip() for line in lines] + self.assertIn(op, function + " " + " ".join(context)) + self.assertLess(context.index("SpillStaticRegs(TMP1);"), context.index("ResetStack();"), op) + + def test_patch_is_skipped_once_upstream_ships_it(self): + self.assertEqual(PATCH.read_text().splitlines()[0], "Fixed-upstream: FEX-2612") + self.assertIn("Fixed-upstream: FEX-", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class SyscallHostStackProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-syscall-stack-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_runs_every_syscall(self): + result = subprocess.run([str(self.binary), "200000"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertIn(counts["mode"], ("avx", "mmx")) + self.assertEqual(counts["syscalls"], "200000") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_thunk_signal_state.py b/tools/tests/test_fex_thunk_signal_state.py new file mode 100644 index 0000000000..83d6008589 --- /dev/null +++ b/tools/tests/test_fex_thunk_signal_state.py @@ -0,0 +1,124 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0011-thunk-calls-mark-spilled-state.patch" +PROBE = FEX / "probes/vdso-signal-state.c" +CORE = "FEXCore/Source/Interface/Core/Core.cpp" +BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp" +DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp" +FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp" +MARK = "str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));" +CLEAR = "str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));" +RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;" + + +def files(): + sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M) + return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)} + + +def hunks(section): + return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M) + + +def added(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("-") and not line.startswith("---")] + + +def context(body): + return [line[1:].strip() for line in body.splitlines() if line[:1] in (" ", "+")] + + +class ThunkSignalStateTest(unittest.TestCase): + def test_only_signal_state_files_change(self): + self.assertEqual(sorted(files()), sorted([BRANCH_OPS, CORE, DELEGATOR, FRAMES])) + + def test_added_code_has_no_new_comments(self): + for name, section in files().items(): + moved = set(removed(section)) + for line in added(section): + if "//" in line or "/*" in line: + self.assertIn(line, moved, f"{name}: {line}") + + def test_thunk_call_marks_all_state_spilled_until_the_refill(self): + section = files()[BRANCH_OPS] + lines = context(section) + self.assertEqual([line for line in added(section) if line], ["LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF);", MARK, CLEAR]) + self.assertEqual(removed(section), []) + self.assertLess(lines.index("PushDynamicRegs(TMP1);"), lines.index(MARK)) + self.assertLess(lines.index(MARK), lines.index("InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);")) + refill = lines.index("FillStaticRegs({") + self.assertEqual(lines[refill + 1:refill + 3], [".NZCV = false,", "});"]) + self.assertLess(refill, lines.index(CLEAR)) + + def test_fully_spilled_state_is_never_respilled_from_host_registers(self): + found = hunks(files()[DELEGATOR]) + spill = "".join(body for function, body in found if "SpillSRA" in function or "IgnoreMask" in body) + lines = context(spill) + guard = lines.index("if ((IgnoreMask & 0xFFFF) == 0xFFFF) {") + self.assertIn("RestoreRIPFromHostPC", lines[guard - 2]) + self.assertEqual(lines[guard + 1], "return;") + self.assertIn("for (size_t i = 0; i < Config.SRAGPRCount; i++) {", lines[guard + 2:guard + 5]) + + def test_every_guest_signal_saves_and_clears_the_mark(self): + section = files()[DELEGATOR] + lines = added(section) + self.assertIn("ContextBackup->InSyscallInfo = Frame->InSyscallInfo;", lines) + self.assertIn("Frame->InSyscallInfo = 0;", lines) + self.assertIn(RESTORE, lines) + self.assertIn("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {", removed(section)) + self.assertNotIn("TYPE_PAUSE", " ".join(lines)) + + def test_redirected_returns_restart_with_no_mark(self): + section = files()[FRAMES] + self.assertEqual(added(section), ["Frame->InSyscallInfo = 0;"] * 3) + self.assertEqual(removed(section), [RESTORE] * 3) + + def test_guest_callbacks_run_with_no_mark(self): + lines = added(files()[CORE]) + self.assertEqual(lines[1:3], ["const auto InSyscallInfo = Frame->InSyscallInfo;", "Frame->InSyscallInfo = 0;"]) + self.assertEqual(lines[-1], "Frame->InSyscallInfo = InSyscallInfo;") + self.assertIn("ExecuteJITCallback(Frame, RIP);", lines[-2]) + + def test_patch_follows_the_host_stack_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0010-syscall-exit-resets-host-stack.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class VdsoSignalStateProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-vdso-signal-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_keeps_registers_across_interrupted_clock_calls(self): + result = subprocess.run([str(self.binary), "1"], capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertGreater(int(counts["calls"]), 0) + self.assertGreater(int(counts["alarms"]), 0) + self.assertEqual(counts["bad"], "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index 41f05beb83..453346281d 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -1,3 +1,4 @@ +import contextlib import hashlib import io import json @@ -1536,6 +1537,77 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(MODULE["engine_fixes"]("/game/FSD-Win64-Shipping.exe", []), ({}, [], [])) self.assertEqual(MODULE["engine_fixes"]("/game/Other-WinGDK-Shipping.exe", []), ({}, [], [])) + def test_dragons_dogma_2_turns_its_wine_detection_off_unless_the_user_sets_it(self): + game = "/game/Dragons Dogma 2/DD2.exe" + env, extra, notes = MODULE["engine_fixes"](game, [], "2054970") + self.assertEqual(extra, ["/WineDetectionEnabled:False"]) + self.assertEqual(env, {}) + self.assertTrue(notes) + self.assertEqual(MODULE["engine_fixes"](game, ["-dx12"], "2054970")[1], ["/WineDetectionEnabled:False"]) + for own in ("/WineDetectionEnabled:False", "/WineDetectionEnabled:True", "/winedetectionenabled:false"): + self.assertEqual(MODULE["engine_fixes"](game, [own], "2054970"), ({}, [], [])) + self.assertEqual(MODULE["engine_fixes"](game, [], "42"), ({}, [], [])) + self.assertEqual(MODULE["engine_fixes"](game, []), ({}, [], [])) + + def test_dragon_quest_monsters_4_writes_full_detail_mesh_settings(self): + apply = MODULE["dragon_quest_monsters_4_mesh_detail"] + wanted = "r.SkeletalMeshLODBias=-4\nr.SkeletalMeshLODRadiusScale=0.25\n" + for exe, project in (("DragonQuestMonsters4Demo.exe", "DragonQuestMonsters4Demo"), + ("DragonQuestMonsters4-Win64-Shipping.exe", "DragonQuestMonsters4")): + with self.subTest(exe=exe), tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "pfx").mkdir() + config = Path(tmp) / "pfx/drive_c/users/steamuser/AppData/Local" / project / "Saved/Config/Windows/Engine.ini" + with contextlib.redirect_stderr(io.StringIO()): + apply("/game/" + exe, {"STEAM_COMPAT_DATA_PATH": tmp}) + self.assertEqual(config.read_text(), "[SystemSettings]\n" + wanted) + + def test_dragon_quest_monsters_4_keeps_other_engine_settings(self): + with tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "pfx").mkdir() + config = Path(tmp) / "pfx/drive_c/users/steamuser/AppData/Local/DragonQuestMonsters4Demo/Saved/Config/Windows/Engine.ini" + config.parent.mkdir(parents=True) + config.write_text("[Core.Log]\nLogTemp=Log\n\n[SystemSettings]\nr.Fog=0\nr.SkeletalMeshLODBias=0\n\n[Other]\nKey=1\n") + config.chmod(0o444) + with contextlib.redirect_stderr(io.StringIO()): + MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters4Demo.exe", {"STEAM_COMPAT_DATA_PATH": tmp}) + self.assertEqual(config.read_text(), "[Core.Log]\nLogTemp=Log\n\n[SystemSettings]\nr.Fog=0\n" + "r.SkeletalMeshLODBias=-4\nr.SkeletalMeshLODRadiusScale=0.25\n\n[Other]\nKey=1\n") + self.assertEqual(config.stat().st_mode & 0o777, 0o444) + + def test_dragon_quest_monsters_4_settings_use_the_game_profile_prefix(self): + with tempfile.TemporaryDirectory() as tmp: + home = Path(tmp) + exe = home / "game/DragonQuestMonsters4Demo.exe" + exe.parent.mkdir() + exe.touch() + proton = home / "fake-proton" + proton.write_text("#!" + sys.executable + "\nimport json, sys\nprint(json.dumps(sys.argv[1:]))\n") + proton.chmod(0o755) + inherited, chosen = home / "compatdata/42", home / "profile/42" + for data in (inherited, chosen): + (data / "pfx").mkdir(parents=True) + config = home / ".config/droiddeck/game-environment.json" + config.parent.mkdir(parents=True) + config.write_text(json.dumps({"version": 1, "games": {"42": {"STEAM_COMPAT_DATA_PATH": str(chosen)}}})) + subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(proton), "waitforexitandrun", str(exe)], + env=dict(os.environ, HOME=tmp, STEAM_COMPAT_DATA_PATH=str(inherited)), + text=True, capture_output=True, check=True) + engine = "pfx/drive_c/users/steamuser/AppData/Local/DragonQuestMonsters4Demo/Saved/Config/Windows/Engine.ini" + self.assertIn("r.SkeletalMeshLODBias=-4", (chosen / engine).read_text()) + self.assertFalse((inherited / engine).exists()) + + def test_dragon_quest_monsters_4_prefix_errors_do_not_stop_the_launch(self): + errors = io.StringIO() + with mock.patch.object(Path, "is_dir", side_effect=PermissionError("denied")), contextlib.redirect_stderr(errors): + MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters4Demo.exe", {"STEAM_COMPAT_DATA_PATH": "/compatdata/42"}) + self.assertIn("left as is", errors.getvalue()) + + def test_other_games_do_not_get_the_dragon_quest_monsters_4_settings(self): + with tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "pfx").mkdir() + MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters3.exe", {"STEAM_COMPAT_DATA_PATH": tmp}) + self.assertEqual(list((Path(tmp) / "pfx").iterdir()), []) + def test_arkham_city_gets_full_x87_precision_over_the_preset(self): with tempfile.TemporaryDirectory() as tmp: city = Path(tmp) / "Batman Arkham City GOTY/Binaries/Win32" @@ -1854,6 +1926,18 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(MODULE["apply_config"]({}, config, "1771300", env), {"VKD3D_FEATURE_LEVEL": "12_1", "VKD3D_SHADER_MODEL": "6_9"}) self.assertEqual(MODULE["engine_fixes"](str(exe), [], "42")[0], {}) + def test_hades_ii_runs_at_feature_level_12_2_from_steam_and_xbox_unless_the_game_overrides_it(self): + with tempfile.TemporaryDirectory() as tmp: + for exe in (Path(tmp) / "Hades II/Ship/Hades2.exe", Path(tmp) / "Xbox/Hades II/Hades2.exe"): + exe.parent.mkdir(parents=True) + exe.touch() + env, extra, notes = MODULE["engine_fixes"](str(exe), []) + self.assertEqual(env, {"VKD3D_FEATURE_LEVEL": "12_2"}, str(exe)) + self.assertTrue(notes) + config = {"version": 1, "shared": {}, "games": {"42": {"VKD3D_FEATURE_LEVEL": "12_1"}}} + self.assertEqual(MODULE["apply_config"]({}, config, "42", env), {"VKD3D_FEATURE_LEVEL": "12_1"}) + self.assertEqual(MODULE["engine_fixes"]("/game/Hades/x64/Hades.exe", [])[0], {}) + def test_unity_players_keep_tso_over_the_preset(self): with tempfile.TemporaryDirectory() as tmp: def game(*names): diff --git a/tools/tests/test_gamescope_disabled_touch_mouse.py b/tools/tests/test_gamescope_disabled_touch_mouse.py new file mode 100644 index 0000000000..8dc144c9c5 --- /dev/null +++ b/tools/tests/test_gamescope_disabled_touch_mouse.py @@ -0,0 +1,76 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0141-nested-mouse-moves-when-touch-is-disabled.patch" + + +def patched_source(): + return "\n".join(line[1:] for line in PATCH.read_text().splitlines() + if line[:1] in (" ", "+") and not line.startswith("+++")) + + +def branch(text, start): + begin = text.index(start) + depth = 0 + for i in range(text.index("{", begin), len(text)): + depth += {"{": 1, "}": -1}.get(text[i], 0) + if depth == 0: + return text[begin:i + 1] + raise ValueError(start) + + +PREAMBLE = r''' +#include <cassert> +#include <cstdint> +namespace gamescope { enum class TouchClickModes { Hover, Left, Right, Middle, Passthrough, Disabled, Trackpad }; } +static int warps, bumps, warp_from_touch = -1; +static double warp_x, warp_y; +static void wlserver_mousewarp( double x, double y, uint32_t, bool, bool bFromTouch = false ) { warps++; warp_x = x; warp_y = y; warp_from_touch = bFromTouch; } +static void bump_input_counter() { bumps++; } + +static void touchmotion( double tx, double ty, uint32_t time, bool bAlwaysWarpCursor ) +{ + gamescope::TouchClickModes eMode = gamescope::TouchClickModes::Disabled; + if ( eMode == gamescope::TouchClickModes::Passthrough ) + { + } +''' + +MAIN = r''' + bump_input_counter(); +} + +int main() { + touchmotion( 0.0, 0.0, 1, false ); + assert( warps == 0 && bumps == 0 ); + + touchmotion( 640.5, 360.25, 2, true ); + assert( warps == 1 && warp_x == 640.5 && warp_y == 360.25 ); + assert( warp_from_touch == 0 ); + assert( bumps == 1 ); + return 0; +} +''' + + +class GamescopeDisabledTouchMouseTest(unittest.TestCase): + def test_the_nested_mouse_moves_the_pointer_while_fingers_stay_ignored(self): + compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++") + if not compiler: + self.skipTest("no C++ compiler") + disabled = branch(patched_source(), "else if ( eMode == gamescope::TouchClickModes::Disabled )") + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / "disabled_touch_mouse.cpp" + exe = Path(tmp) / "disabled_touch_mouse" + src.write_text(PREAMBLE + "\t" + disabled + "\n" + MAIN) + subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True) + subprocess.run([str(exe)], check=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_gamescope_focus_opacity.py b/tools/tests/test_gamescope_focus_opacity.py new file mode 100644 index 0000000000..3d5be63026 --- /dev/null +++ b/tools/tests/test_gamescope_focus_opacity.py @@ -0,0 +1,70 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0140-focus-follows-window-opacity.patch" + + +def added_lines(): + return [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def patched_rule(): + text = "\n".join(added_lines()) + start = text.index("static bool") + return text[start:text.index("\n}\n", start) + 3] + + +PREAMBLE = r''' +#include <cassert> +#include <cstdio> + +#define TRANSLUCENT 0x00000000 +#define OPAQUE 0xffffffff +''' + +MAIN = r''' +int main() { + assert(opacity_changes_focus_candidacy(TRANSLUCENT, OPAQUE)); + assert(opacity_changes_focus_candidacy(TRANSLUCENT, 0x01010101u)); + assert(opacity_changes_focus_candidacy(OPAQUE, TRANSLUCENT)); + assert(opacity_changes_focus_candidacy(0x80808080u, TRANSLUCENT)); + assert(!opacity_changes_focus_candidacy(0x40404040u, 0xc0c0c0c0u)); + assert(!opacity_changes_focus_candidacy(OPAQUE, 0x80808080u)); + assert(!opacity_changes_focus_candidacy(TRANSLUCENT, TRANSLUCENT)); + assert(!opacity_changes_focus_candidacy(OPAQUE, OPAQUE)); + puts("ok"); + return 0; +} +''' + + +@unittest.skipUnless(shutil.which("c++"), "needs a C++ compiler") +class FocusOpacityRuleTest(unittest.TestCase): + def test_only_crossing_fully_transparent_changes_focus_candidacy(self): + with tempfile.TemporaryDirectory() as tmp: + source = Path(tmp) / "opacity.cpp" + binary = Path(tmp) / "opacity" + source.write_text(PREAMBLE + patched_rule() + MAIN) + subprocess.run(["c++", "-std=c++17", "-Wall", "-Werror", str(source), "-o", str(binary)], check=True) + self.assertEqual(subprocess.run([str(binary)], capture_output=True, text=True, check=True).stdout.strip(), "ok") + + +class FocusOpacityHandlerTest(unittest.TestCase): + def test_opacity_property_change_reevaluates_focus_when_candidacy_changes(self): + hunks = PATCH.read_text().split("\n@@ ") + handler = next(hunk for hunk in hunks if "handle_property_notify(" in hunk.split("\n", 1)[0]) + added = [line[1:].strip() for line in handler.splitlines() if line.startswith("+")] + self.assertIn("const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity );", added) + self.assertIn("MakeFocusDirty();", added) + context = [line[1:].strip() for line in handler.splitlines() if line.startswith(" ")] + self.assertIn("w->opacity = newOpacity;", context) + self.assertLess(added.index("const bool bFocusCandidacyChanged = opacity_changes_focus_candidacy( w->opacity, newOpacity );"), added.index("MakeFocusDirty();")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_gamescope_limiter_cadence.py b/tools/tests/test_gamescope_limiter_cadence.py new file mode 100644 index 0000000000..79a4319adb --- /dev/null +++ b/tools/tests/test_gamescope_limiter_cadence.py @@ -0,0 +1,118 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0138-limiter-even-cadence.patch" + + +def added_source(): + return "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")) + + +def block(text, start): + begin = text.index(start) + return text[begin:text.index("\n}", begin) + 3] + + +PREAMBLE = r''' +#include <cassert> +#include <cstdint> +#include <cstdio> +#include <vector> +''' + +MAIN = r''' +struct Run { + std::vector<int> gaps; + int frames = 0; +}; + +static Run run(int hz, int fps, int vblanks, uint64_t latency) { + const uint64_t cycle = 1000000000ull / hz; + const uint64_t limited = cycle * hz / fps; + uint64_t target = 0; + int last = -1; + Run r; + for (int i = 0; i < vblanks; i++) { + const uint64_t now = (1000ull + i) * cycle; + if (limiter_holds_vblank(target, now, limited, cycle)) continue; + target = limiter_latch_target(target, now + latency, limited, cycle); + if (last >= 0) r.gaps.push_back(i - last); + last = i; + r.frames++; + } + return r; +} + +static void check(int hz, int fps, uint64_t latency) { + const int vblanks = hz * 20; + const Run r = run(hz, fps, vblanks, latency); + const int low = hz / fps; + const int high = (hz + fps - 1) / fps; + for (int gap : r.gaps) { + if (gap != low && gap != high) { + std::printf("%d Hz at %d fps: a frame was held for %d refreshes\n", hz, fps, gap); + assert(false); + } + } + const int expected = fps * 20; + if (r.frames < expected - 1 || r.frames > expected + 1) { + std::printf("%d Hz at %d fps: %d frames, expected %d\n", hz, fps, r.frames, expected); + assert(false); + } +} + +int main() { + const int rates[] = {60, 90, 120, 144, 165}; + const int limits[] = {24, 30, 36, 40, 45, 48, 50, 60, 72, 80, 90, 100, 120, 144}; + for (int hz : rates) { + for (int fps : limits) { + if (fps > hz) continue; + check(hz, fps, 0); + check(hz, fps, 1000000000ull / hz / 4); + } + } + + const Run even = run(60, 30, 600, 0); + for (int gap : even.gaps) assert(gap == 2); + const Run full = run(120, 120, 600, 0); + for (int gap : full.gaps) assert(gap == 1); + const Run two_of_three = run(60, 40, 600, 0); + for (size_t i = 1; i < two_of_three.gaps.size(); i++) assert(two_of_three.gaps[i] != two_of_three.gaps[i - 1]); + + const uint64_t cycle = 16666666, limited = cycle * 60 / 45; + assert(limiter_latch_target(1000 * cycle, 1500 * cycle, limited, cycle) == 1500 * cycle); + assert(limiter_latch_target(1500 * cycle, 1000 * cycle, limited, cycle) == 1000 * cycle); + assert(limiter_latch_target(1000 * cycle, 1001 * cycle, limited, cycle) == 1000 * cycle + limited); + return 0; +} +''' + + +class GamescopeLimiterCadenceTest(unittest.TestCase): + def test_a_limit_the_refresh_rate_does_not_divide_is_spread_evenly(self): + compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++") + if not compiler: + self.skipTest("no C++ compiler") + added = added_source() + source = PREAMBLE + block(added, "static uint64_t limiter_latch_target") + block(added, "static bool limiter_holds_vblank") + MAIN + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / "limiter_cadence.cpp" + exe = Path(tmp) / "limiter_cadence" + src.write_text(source) + subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True) + subprocess.run([str(exe)], check=True) + + def test_the_limited_cycle_is_no_longer_a_whole_number_of_refreshes(self): + added = added_source() + self.assertIn("g_SteamCompMgrAppRefreshCycle * nRealRefreshHz / nTargetFPS", added) + removed = "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("-") and not line.startswith("---")) + self.assertIn("nVblankDivisor", removed) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_hdr_live_switch.py b/tools/tests/test_hdr_live_switch.py new file mode 100644 index 0000000000..4468be5048 --- /dev/null +++ b/tools/tests/test_hdr_live_switch.py @@ -0,0 +1,87 @@ +from pathlib import Path +import re +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0139-hdr-switch-live.patch" +APP = ROOT / "app/src/main/java/com/droiddeck/launcher" +RES = ROOT / "app/src/main/res" + + +def lines(prefix): + return [line[1:] for line in PATCH.read_text().splitlines() + if line.startswith(prefix) and not line.startswith(prefix * 3)] + + +class HdrLiveSwitchTest(unittest.TestCase): + def test_display_capability_does_not_depend_on_the_setting(self): + added = [line for line in lines("+") if "bExposeHDRSupport =" in line] + self.assertEqual(len(added), 1) + self.assertNotIn("cv_hdr_enabled", added[0]) + self.assertIn("m_uMaxTargetLuminance > m_pConnector->m_uReferenceLuminance", added[0]) + + def test_sdr_keeps_the_8_bit_output(self): + added = [line for line in lines("+") if "*pPrimaryPlaneFormat" in line] + self.assertEqual(len(added), 1) + self.assertRegex(added[0], r"cv_hdr_enabled && u10BitFormat != DRM_FORMAT_INVALID \) \? u10BitFormat : u8BitFormat") + + def test_remade_output_images_pick_the_format_again(self): + text = PATCH.read_text() + hunk = text[text.index("src/rendervulkan.cpp"):] + added = [line[1:] for line in hunk.splitlines() if line.startswith("+") and not line.startswith("+++")] + self.assertEqual([line.strip() for line in added], + ["GetBackend()->GetPreferredOutputFormat( &pOutput->uOutputFormat, &pOutput->uOutputFormatOverlay );"]) + self.assertIn("if ( vulkan_defer_output_images() )", hunk[:hunk.index(added[0])]) + + def test_capable_display_does_not_force_dxvk_hdr_off(self): + added = "\n".join(lines("+")) + self.assertIn('unsetenv( "DXVK_HDR" )', added) + off = added.index('setenv( "DXVK_HDR", "0", true )') + self.assertIn("!GetCurrentConnector()->GetHDRInfo().bExposeHDRSupport", added[:off]) + + def test_the_gate_follows_the_display_not_the_setting(self): + text = (APP / "SessionActivity.kt").read_text() + start = text.index("val attached = CompositorHost.isStarted") + block = text[start:text.index("DriverSetupLog.write", start)] + request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))] + self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")]) + self.assertIn("capable, false", request) + self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block) + + def test_both_switches_apply_to_the_running_session(self): + helper = (APP / "session/SessionHdr.kt").read_text() + self.assertIn('setGamescopeConvar(app, "hdr_enabled", if (on) 1 else 0)', helper) + self.assertIn("nativeSetHdrOutput(on)", helper) + self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode))", helper) + self.assertIn("SessionPrefs.prefMode(SessionState.mode) != mode", helper) + for name in ("SessionActivity.kt", "FrontEndActivity.kt"): + text = (APP / name).read_text() + self.assertEqual(len(re.findall(r"onHdr = \{ on -> com\.droiddeck\.launcher\.session\.SessionHdr\.set\(", text)), 1, name) + self.assertNotIn("SessionPrefs.setHdr(", text, name) + + def test_a_saved_opt_out_applies_before_the_gate_opens(self): + native = (ROOT / "app/src/main/cpp/waylandcomp/src/wl_color_mgmt.c").read_text() + switch = native[native.index("void droiddeck_color_set_output(int on)"):] + switch = switch[:switch.index("if (gate != 1)")] + self.assertLess(switch.index("pthread_mutex_lock(&g_output_mu)"), switch.index("atomic_store(&g_output_wanted, on)")) + self.assertLess(switch.index("atomic_exchange(&g_output_on, on)"), switch.index("pthread_mutex_unlock(&g_output_mu)")) + opened = native[native.index("atomic_store(&g_gate, 1);") - 40:] + opened = opened[:opened.index("pthread_mutex_unlock(&g_output_mu)")] + self.assertIn("pthread_mutex_lock(&g_output_mu)", opened) + self.assertIn("if (mode == 3 || !atomic_load(&g_output_wanted)) atomic_store(&g_output_on, 0);", opened) + text = (APP / "SessionActivity.kt").read_text() + self.assertNotIn("if (attached) WaylandCompositor.nativeSetHdrOutput", text) + + def test_retries_stay_with_the_session_that_asked(self): + helper = (APP / "session/SessionHdr.kt").read_text() + self.assertIn("val session = SessionState.sessionId", helper) + self.assertIn("SessionState.sessionId == session", helper) + + def test_no_restart_hint_is_left(self): + for path in list(RES.glob("values*/strings.xml")) + list(APP.rglob("*.kt")): + self.assertNotIn("mode_hdr_restart", path.read_text(), str(path)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_hdr_steam_sync.py b/tools/tests/test_hdr_steam_sync.py new file mode 100644 index 0000000000..c550a892d8 --- /dev/null +++ b/tools/tests/test_hdr_steam_sync.py @@ -0,0 +1,185 @@ +import json +from pathlib import Path +import runpy +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +BIN = ROOT / "tools/linuxfs/overlay/usr/local/bin" +APP = ROOT / "app/src/main/java/com/droiddeck/launcher" +LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat")) + +HARNESS = r""" +const assert = require('assert'); +globalThis.window = globalThis; +globalThis.btoa = text => Buffer.from(text, 'binary').toString('base64'); +let now = 0, tick = null; +Object.defineProperty(globalThis, 'performance', { value: { now: () => now }, configurable: true }); +globalThis.setInterval = callback => { tick = callback; return 1; }; +const varints = bytes => { const out = []; let value = 0, shift = 0; + for (const b of bytes) { value += (b & 127) * 2 ** shift; shift += 7; if (b < 128) { out.push(value); value = 0; shift = 0; } } + return out; }; +const writes = [], told = []; +let apply = true; +globalThis.settingsStore = { clientSettings: { gamescope_hdr_enabled: false } }; +globalThis.SteamClient = { Settings: { SetSetting(encoded) { + const [key, value] = varints([...Buffer.from(encoded, 'base64')]); + assert.strictEqual(key, 21015 * 8); + writes.push(value); + if (apply) settingsStore.clientSettings.gamescope_hdr_enabled = value === 1; +} } }; +window.droiddeckHdrChanged = value => told.push(value); +const script = require('fs').readFileSync(process.argv[2], 'utf8'); +assert.strictEqual(eval(script), 'installed'); +assert.strictEqual(eval(script), 'present'); +const bridge = window.__droiddeckHdr; +tick(); +assert.deepStrictEqual(told, [], 'an unchanged client setting is not reported'); +assert.strictEqual(bridge.set(true), true); +assert.deepStrictEqual(writes, [1]); +tick(); +assert.deepStrictEqual(told, [], 'a value the app set is not reported back to it'); +assert.strictEqual(bridge.set(true), true); +assert.deepStrictEqual(writes, [1], 'an equal value is not written again'); +settingsStore.clientSettings.gamescope_hdr_enabled = false; +tick(); +assert.deepStrictEqual(told, ['0'], 'a change made in the client reaches the app'); +tick(); +assert.deepStrictEqual(told, ['0']); +settingsStore.clientSettings.gamescope_hdr_enabled = true; +tick(); +assert.deepStrictEqual(told, ['0', '1']); +apply = false; +bridge.set(false); +assert.deepStrictEqual(writes, [1, 0]); +now += 500; tick(); +assert.deepStrictEqual(told, ['0', '1'], 'the old value is not reported while a write is settling'); +now += 3000; tick(); +assert.deepStrictEqual(told, ['0', '1', '1'], 'a write the client did not take is reported as its real value'); +assert.strictEqual(bridge.set('yes'), true); +assert.deepStrictEqual(writes, [1, 0]); +bridge.set(false); +bridge.set(true); +assert.deepStrictEqual(writes, [1, 0, 0, 1], 'a newer opposite value is written while the earlier write is settling'); +settingsStore.clientSettings.gamescope_hdr_enabled = false; +now += 500; tick(); +settingsStore.clientSettings.gamescope_hdr_enabled = true; +now += 500; tick(); +assert.deepStrictEqual(told, ['0', '1', '1'], 'the earlier write landing late is not reported to the app'); +delete globalThis.__droiddeckHdr; +delete settingsStore.clientSettings.gamescope_hdr_enabled; +assert.strictEqual(eval(script), 'unavailable'); +""" + + +class HdrSteamSyncTest(unittest.TestCase): + def test_bridge_keeps_the_client_setting_and_the_app_equal(self): + with tempfile.TemporaryDirectory() as directory: + script = Path(directory) / "bridge.js" + script.write_text(LIVE["HDR_JS"]) + test = Path(directory) / "test.js" + test.write_text(HARNESS) + result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_requests_accept_only_on_and_off(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "hdr.request" + for value in ["2", "true", "", None, 1]: + LIVE["hdr_request"](value, directory) + self.assertFalse(path.exists()) + LIVE["hdr_request"]("1", directory) + self.assertEqual(path.read_text(), "1\n") + LIVE["hdr_request"]("0", directory) + self.assertEqual(path.read_text(), "0\n") + + def helper(self, directory): + helper = LIVE["Helper"]("/steam", 0) + calls = [] + + class Page: + answer = True + + def call(self, method, params=None): + calls.append((method, params)) + + def evaluate(self, expression): + calls.append(expression) + return "installed" if expression == LIVE["HDR_JS"] else self.answer + + helper.page = Page() + return helper, calls + + def test_the_app_state_is_applied_once_per_change(self): + with tempfile.TemporaryDirectory() as directory: + globals_ = LIVE["Helper"].sync_hdr.__globals__ + previous = globals_["CONTROLS_DIR"] + try: + globals_["CONTROLS_DIR"] = directory + helper, calls = self.helper(directory) + path = Path(directory) / "state.json" + helper.sync_hdr() + path.write_text(json.dumps({"brightness": 0.5})) + helper.sync_hdr() + self.assertEqual(calls, [], "a session that cannot show HDR leaves the client setting alone") + path.write_text(json.dumps({"brightness": 0.5, "hdr": True})) + helper.sync_hdr() + helper.sync_hdr() + self.assertEqual(calls[0], ("Runtime.addBinding", {"name": LIVE["HDR_BINDING"]})) + self.assertEqual(calls[1], LIVE["HDR_JS"]) + self.assertEqual(calls[2:], ["window.__droiddeckHdr ? window.__droiddeckHdr.set(true) : false"]) + path.write_text(json.dumps({"brightness": 0.7, "hdr": True})) + helper.sync_hdr() + self.assertEqual(len(calls), 3) + path.write_text(json.dumps({"hdr": False})) + helper.sync_hdr() + self.assertEqual(calls[3], "window.__droiddeckHdr ? window.__droiddeckHdr.set(false) : false") + helper.page.answer = False + path.write_text(json.dumps({"hdr": True})) + helper.sync_hdr() + self.assertFalse(helper.hdr_installed) + self.assertIsNone(helper.hdr_state) + helper.page.answer = True + path.write_text(json.dumps({"hdr": False})) + helper.sync_hdr() + self.assertEqual(calls[-1], "window.__droiddeckHdr ? window.__droiddeckHdr.set(false) : false") + finally: + globals_["CONTROLS_DIR"] = previous + + def test_a_client_without_the_setting_is_left_alone(self): + with tempfile.TemporaryDirectory() as directory: + globals_ = LIVE["Helper"].sync_hdr.__globals__ + previous = globals_["CONTROLS_DIR"] + try: + globals_["CONTROLS_DIR"] = directory + helper, calls = self.helper(directory) + helper.page.evaluate = lambda expression: calls.append(expression) or "unavailable" + (Path(directory) / "state.json").write_text(json.dumps({"hdr": True})) + helper.sync_hdr() + self.assertEqual(calls, [("Runtime.addBinding", {"name": LIVE["HDR_BINDING"]}), LIVE["HDR_JS"]]) + self.assertFalse(helper.hdr_installed) + self.assertIsNone(helper.hdr_state) + helper.sync_hdr() + self.assertEqual(len(calls), 2, "a client without the setting is not asked again straight away") + finally: + globals_["CONTROLS_DIR"] = previous + + def test_the_app_publishes_and_takes_the_shared_value(self): + controls = (APP / "runtime/DeviceControlsComponent.kt").read_text() + self.assertIn('if (SessionState.hdrCapable) controls.put("hdr", SessionState.hdr)', controls) + self.assertIn('"hdr.request" -> if (text == "0" || text == "1")', controls) + self.assertIn('SessionHdr.set(context, SessionPrefs.prefMode(SessionState.mode), text == "1")', controls) + self.assertIn('"hdr.request")', controls[controls.index("REQUESTS = setOf"):]) + session = (APP / "SessionActivity.kt").read_text() + self.assertIn("if (key == SessionPrefs.hdrKey(hdrPrefMode()))", session) + self.assertIn("registerOnSharedPreferenceChangeListener(hdrPrefListener)", session) + self.assertIn("unregisterOnSharedPreferenceChangeListener(hdrPrefListener)", session) + + def test_frame_limit_writes_share_the_setting_writer(self): + self.assertIn("(21002, value)", LIVE["FRAME_LIMIT_JS"]) + self.assertNotIn("__SET_SETTING__", LIVE["FRAME_LIMIT_JS"] + LIVE["HDR_JS"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_inputudev_preload.py b/tools/tests/test_inputudev_preload.py index c1d970fd1d..68d55403fe 100644 --- a/tools/tests/test_inputudev_preload.py +++ b/tools/tests/test_inputudev_preload.py @@ -1,5 +1,6 @@ from pathlib import Path import os +import re import shutil import subprocess import sys @@ -77,6 +78,66 @@ char *realpath(const char *path, char *resolved) { } """ +LOCKED = r""" +#include <sys/syscall.h> +#include <unistd.h> + +extern int busy; + +__attribute__((constructor)) static void start(void) { + busy = 1; + syscall(SYS_getpid); + busy = 0; +} +""" + +ARENA = r""" +#include <stdint.h> +#include <stdio.h> +#include <string.h> + +static _Alignas(64) unsigned char arena[1 << 23]; +static size_t used; +int busy; +static int busy_allocations; + +void *memalign(size_t align, size_t size) { + uintptr_t start; + if (busy) busy_allocations++; + if (align < 16) align = 16; + start = ((uintptr_t)(arena + used) + 16 + align - 1) & ~(uintptr_t)(align - 1); + if (start + size > (uintptr_t)(arena + sizeof(arena))) return NULL; + ((size_t *)start)[-1] = size; + used = start + size - (uintptr_t)arena; + return (void *)start; +} + +void *malloc(size_t size) { return memalign(16, size); } +void *aligned_alloc(size_t align, size_t size) { return memalign(align, size); } +int posix_memalign(void **out, size_t align, size_t size) { return (*out = memalign(align, size)) ? 0 : 12; } +void free(void *p) { (void)p; } + +void *calloc(size_t n, size_t size) { + void *p = malloc(n * size); + if (p) memset(p, 0, n * size); + return p; +} + +void *realloc(void *p, size_t size) { + void *q = malloc(size); + if (p && q) { + size_t old = ((size_t *)p)[-1]; + memcpy(q, p, old < size ? old : size); + } + return q; +} + +int main(void) { + printf("allocations %d\n", busy_allocations); + return 0; +} +""" + UDEV = r""" #include <stdio.h> #include <stdlib.h> @@ -121,20 +182,48 @@ void *udev_device_new_from_subsystem_sysname(void *udev, const char *subsystem, (void)udev; (void)subsystem; (void)sysname; return NULL; } -void *udev_device_unref(void *device) { (void)device; return NULL; } -void *udev_device_ref(void *device) { (void)device; return NULL; } -void *udev_device_get_parent(void *device) { (void)device; return NULL; } -void *udev_device_get_udev(void *device) { (void)device; return NULL; } -const char *udev_device_get_syspath(void *device) { (void)device; return "real"; } -const char *udev_device_get_sysnum(void *device) { (void)device; return "real"; } +int real_device_calls; +void *udev_device_unref(void *device) { (void)device; real_device_calls++; return NULL; } +void *udev_device_ref(void *device) { (void)device; real_device_calls++; return NULL; } +void *udev_device_get_parent(void *device) { (void)device; real_device_calls++; return NULL; } +void *udev_device_get_udev(void *device) { (void)device; real_device_calls++; return NULL; } +const char *udev_device_get_syspath(void *device) { (void)device; real_device_calls++; return "real"; } +const char *udev_device_get_sysnum(void *device) { (void)device; real_device_calls++; return "real"; } +void *udev_device_new_from_devnum(void *udev, char type, unsigned long devnum) { + (void)udev; (void)type; (void)devnum; + return NULL; +} """ +DEVICE_FUNCTIONS = ( + "p:udev_device_ref", "p:udev_device_get_udev", "p:udev_device_get_parent", + "P:udev_device_get_parent_with_subsystem_devtype", "s:udev_device_get_devpath", "s:udev_device_get_subsystem", + "s:udev_device_get_devtype", "s:udev_device_get_syspath", "s:udev_device_get_sysname", + "s:udev_device_get_sysnum", "s:udev_device_get_devnode", "i:udev_device_get_is_initialized", + "p:udev_device_get_devlinks_list_entry", "p:udev_device_get_properties_list_entry", + "p:udev_device_get_tags_list_entry", "p:udev_device_get_current_tags_list_entry", + "p:udev_device_get_sysattr_list_entry", "S:udev_device_get_property_value", "s:udev_device_get_driver", + "d:udev_device_get_devnum", "s:udev_device_get_action", "u:udev_device_get_seqnum", + "u:udev_device_get_usec_since_initialized", "S:udev_device_get_sysattr_value", + "W:udev_device_set_sysattr_value", "I:udev_device_has_tag", "I:udev_device_has_current_tag", + "p:udev_device_unref", +) +SIGNATURES = { + "p": ("void *", ""), "s": ("const char *", ""), "i": ("int", ""), "d": ("dev_t", ""), + "u": ("unsigned long long", ""), "S": ("const char *", ", const char *a"), "I": ("int", ", const char *a"), + "P": ("void *", ", const char *a, const char *b"), "W": ("int", ", const char *a, const char *b"), +} +UDEV += "#include <sys/types.h>\n" + "".join( + f"{SIGNATURES[kind][0]} {name}(void *device{SIGNATURES[kind][1]}) {{ (void)device; real_device_calls++; return 0; }}\n" + for kind, _, name in (entry.partition(":") for entry in DEVICE_FUNCTIONS) if not re.search(rf"\b{name}\(", UDEV)) + PROGRAM = r""" #define _GNU_SOURCE #include <dlfcn.h> #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <sys/sysmacros.h> #include <unistd.h> #define PAD "/sys/devices/virtual/input/droiddeck0" @@ -340,6 +429,37 @@ static void run_enumerate(void) { printf("nothing added scan %d\n", scan(other)); } +static void run_every(int count, char **entries) { + void *(*from_devnum)(void *, char, dev_t) = sym("udev_device_new_from_devnum"); + int *real_calls = dlsym(lib, "real_device_calls"); + int udev; + void *pad = from_devnum(&udev, 'c', makedev(13, 64)); + int i; + + for (i = 0; pad != NULL && i < count; i++) { + const char *name = entries[i] + 2; + void *call = sym(name); + + if (call == NULL) { + printf("missing %s\n", name); + continue; + } + switch (entries[i][0]) { + case 'p': ((void *(*)(void *))call)(pad); break; + case 's': ((const char *(*)(void *))call)(pad); break; + case 'i': ((int (*)(void *))call)(pad); break; + case 'd': ((dev_t (*)(void *))call)(pad); break; + case 'u': ((unsigned long long (*)(void *))call)(pad); break; + case 'S': ((const char *(*)(void *, const char *))call)(pad, "attr"); break; + case 'I': ((int (*)(void *, const char *))call)(pad, "attr"); break; + case 'P': ((void *(*)(void *, const char *, const char *))call)(pad, "input", NULL); break; + case 'W': ((int (*)(void *, const char *, const char *))call)(pad, "attr", "value"); break; + default: printf("unknown signature %s\n", entries[i]); + } + } + printf("pad %d real calls %d\n", pad != NULL, real_calls != NULL ? *real_calls : -1); +} + static void run_probe(void) { int udev; @@ -387,6 +507,7 @@ int main(int argc, char **argv) { name = sym("udev_list_entry_get_name"); value = sym("udev_list_entry_get_value"); if (strcmp(argv[1], "probe") == 0) run_probe(); + else if (strcmp(argv[1], "every") == 0) run_every(argc - 3, argv + 3); else if (strcmp(argv[1], "stable") == 0) run_stable(); else if (strcmp(argv[1], "enumerate") == 0) run_enumerate(); else run_udev(); @@ -414,7 +535,7 @@ class InputUdevPreloadTest(unittest.TestCase): if "__GLIBC__" not in compile_c("-dM", "-E", "-x", "c", "-include", "limits.h", "/dev/null"): raise unittest.SkipTest("needs a glibc toolchain") sources = (("once.c", ONCE), ("first.c", FIRST), ("second.c", SECOND), ("chain.c", CHAIN), ("mark.c", MARK), - ("udev.c", UDEV), ("program.c", PROGRAM)) + ("udev.c", UDEV), ("program.c", PROGRAM), ("locked.c", LOCKED), ("arena.c", ARENA)) for name, text in sources: (build / name).write_text(text) cls.lib = cls.dir / "libddsession.so" @@ -427,6 +548,11 @@ class InputUdevPreloadTest(unittest.TestCase): compile_c("-shared", "-fPIC", "-O2", "-o", str(cls.udev), str(build / "udev.c")) cls.program = cls.dir / "program" compile_c("-O0", "-o", str(cls.program), str(build / "program.c"), str(cls.dir / "libfirst.so"), "-ldl") + compile_c("-shared", "-fPIC", "-O0", "-o", str(cls.dir / "liblocked.so"), str(build / "locked.c")) + cls.arena = cls.dir / "arena" + compile_c("-O0", "-rdynamic", "-o", str(cls.arena), str(build / "arena.c"), "-Wl,--no-as-needed", + str(cls.dir / "liblocked.so"), + f"-Wl,-rpath,{cls.dir}") cls.pads = cls.pad_dir("pads", "event0") @classmethod @@ -437,11 +563,11 @@ class InputUdevPreloadTest(unittest.TestCase): (pads / node).write_text("") return pads - def run_program(self, mode, *preloads, pads=None, slots="0=/pad", program=None): + def run_program(self, mode, *preloads, pads=None, slots="0=/pad", program=None, args=()): env = dict(os.environ, LD_PRELOAD=":".join(str(self.dir / name) for name in ("libddsession.so", *preloads)), FAKE_EVDEV_MEMFD_PATHS=slots, FAKE_EVDEV_DIR=str(pads or self.pads)) env.pop("FAKE_EVDEV_UINPUT", None) - result = subprocess.run([str(program or self.program), mode, str(self.udev)], env=env, capture_output=True, text=True, + result = subprocess.run([str(program or self.program), mode, str(self.udev), *args], env=env, capture_output=True, text=True, timeout=20) self.assertEqual(result.returncode, 0, result.stderr) return result.stdout.splitlines() @@ -449,6 +575,12 @@ class InputUdevPreloadTest(unittest.TestCase): def test_a_lookup_from_another_preloads_initialiser_does_not_reenter_it(self): self.assertEqual(self.run_program("once", "libonce.so"), ["readlink 1"]) + def test_a_first_wrapped_call_inside_the_programs_allocator_does_not_allocate(self): + result = subprocess.run([str(self.arena)], env=dict(os.environ, LD_PRELOAD=str(self.lib)), capture_output=True, + text=True, timeout=20) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.splitlines(), ["allocations 0"]) + def test_the_real_lookup_still_sees_the_original_caller(self): self.assertEqual(self.run_program("next", "libfirst.so", "libsecond.so"), ["next 2"]) @@ -483,6 +615,9 @@ class InputUdevPreloadTest(unittest.TestCase): "contexts 1 1", ]) + def test_no_device_call_on_a_pad_reaches_the_real_libudev(self): + self.assertEqual(self.run_program("every", args=DEVICE_FUNCTIONS), ["pad 1 real calls 0"]) + def test_a_handle_keeps_its_strings_after_the_pad_goes_away(self): self.assertEqual(self.run_program("stable", pads=self.pad_dir("stable", "event0")), [ "gone 1", @@ -515,9 +650,11 @@ class InputUdevPreloadTest(unittest.TestCase): "nothing added scan -1", ]) - def test_only_the_steam_client_runtime_path_gets_the_real_libudev(self): - for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/steam-probe", 1), - ("xsteamrt64/steam", 1), ("steamrt64/xsteam", 1), ("steamrt/steam", 1)): + def test_only_the_steam_client_and_its_remote_play_client_get_the_real_libudev(self): + for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/streaming_client", 0), + ("steamrtarm64/streaming_client", 0), ("steamrt64/steam-probe", 1), + ("steamrt64/streaming_client2", 1), ("xsteamrt64/steam", 1), ("steamrt64/xsteam", 1), + ("steamrt/steam", 1), ("steamrt/streaming_client", 1)): with self.subTest(path=path): client = self.dir / "clients" / path client.parent.mkdir(parents=True, exist_ok=True) diff --git a/tools/tests/test_mali_compat_spirv.py b/tools/tests/test_mali_compat_spirv.py new file mode 100644 index 0000000000..a5c0e38e2d --- /dev/null +++ b/tools/tests/test_mali_compat_spirv.py @@ -0,0 +1,90 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +LAYER = ROOT / "tools/venus/layer" +DEPS = ROOT / "build/layer-deps" +HARNESS = Path(__file__).with_name("mali_compat_spirv_test.c") + + +def include(variable, default): + return Path(os.environ.get(variable, str(default))) + + +class MaliCompatSpirvTest(unittest.TestCase): + def test_the_layer_lowers_a_module_to_the_version_the_driver_knows(self): + compiler = shutil.which(os.environ.get("CC", "cc")) + if not compiler: + self.fail("A C compiler is required for the Mali compatibility layer test") + vulkan = include("MALI_COMPAT_VULKAN_INCLUDE", DEPS / "vulkan/include") + spirv = include("MALI_COMPAT_SPIRV_INCLUDE", DEPS / "spirv/include") + missing = [str(path) for path in (vulkan / "vulkan/vk_layer.h", spirv / "spirv/unified1/spirv.h") + if not path.is_file()] + if missing: + message = "Vulkan 1.4 and SPIR-V headers are required: " + ", ".join(missing) + if os.environ.get("CI"): + self.fail(message) + self.skipTest(message) + with tempfile.TemporaryDirectory(prefix="droiddeck-mali-spirv-") as tmp: + program = Path(tmp) / "mali-compat-spirv" + module = Path(tmp) / "capped.spv" + guest = Path(tmp) / "guest.spv" + extension = Path(tmp) / "extension.spv" + scalar = Path(tmp) / "scalar.spv" + debug = Path(tmp) / "debug.spv" + private_readonly = Path(tmp) / "private-readonly.spv" + parameter = Path(tmp) / "parameter.spv" + converted = Path(tmp) / "converted.spv" + built = subprocess.run( + [compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", "-UNDEBUG", + "-pthread", "-Dcalloc=test_calloc", "-I", str(LAYER), "-I", str(vulkan), "-I", str(spirv), + str(HARNESS), str(LAYER / "spirv.c"), str(LAYER / "pipeline.c"), "-o", str(program)], + capture_output=True, text=True) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + ran = subprocess.run([str(program), str(module), str(guest), str(extension), str(scalar), str(debug), + str(private_readonly), str(converted), str(parameter)], + capture_output=True, text=True, timeout=30) + self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) + self.assertIn("mali compat spirv ok", ran.stdout) + self.assertTrue(module.is_file()) + self.assertTrue(guest.is_file()) + self.assertTrue(extension.is_file()) + self.assertTrue(scalar.is_file()) + self.assertTrue(debug.is_file()) + validator = shutil.which("spirv-val") + if not validator: + return + for original in (private_readonly, converted): + checked = subprocess.run([validator, "--target-env", "vulkan1.3", str(original)], + capture_output=True, text=True) + self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr) + downgraded = bytearray(original.read_bytes()) + downgraded[4:8] = (0x00010300).to_bytes(4, "little") + offset = 20 + while True: + instruction = int.from_bytes(downgraded[offset:offset + 4], "little") + length, opcode = instruction >> 16, instruction & 0xffff + if opcode == 15: + downgraded[offset:offset + 4] = (((length - 1) << 16) | opcode).to_bytes(4, "little") + del downgraded[offset + (length - 1) * 4:offset + length * 4] + break + offset += length * 4 + original.write_bytes(downgraded) + checked = subprocess.run([validator, "--target-env", "vulkan1.1", str(original)], + capture_output=True, text=True) + self.assertNotEqual(checked.returncode, 0, "the 1.3 form must be rejected") + expected = "NonWritable" if original == private_readonly else "UConvert" + self.assertIn(expected, checked.stdout + checked.stderr) + for lowered in (module, guest, extension, scalar, debug, parameter): + checked = subprocess.run([validator, "--target-env", "vulkan1.1", str(lowered)], + capture_output=True, text=True) + self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_memory_guard_ab.py b/tools/tests/test_memory_guard_ab.py index 6d75f7206f..96565efffa 100644 --- a/tools/tests/test_memory_guard_ab.py +++ b/tools/tests/test_memory_guard_ab.py @@ -66,6 +66,15 @@ class DumpParsingTest(unittest.TestCase): def test_the_bottom_home_is_the_visible_home_on_another_display(self): self.assertEqual((2, "rip.moth.cocoonshell"), ab.bottom_home(ACTIVITIES, 0)) + def test_android_13_activity_records_are_counted(self): + self.assertEqual(1, ab.session_count( + " * Hist #1: ActivityRecord{e1ec207 u0 com.droiddeck.launcher/.SessionActivity} t14519}\n")) + + def test_the_visible_app_stands_in_when_no_home_is_on_the_other_display(self): + dump = ("Display #4 (activities from top to bottom):\n" + " * Task{21f60d6 #14493 type=standard A=10113:com.discord U=0 visible=true visibleRequested=true mode=fullscreen}\n") + self.assertEqual((4, "com.discord"), ab.bottom_home(dump, 0)) + def test_no_bottom_home_without_another_display(self): self.assertIsNone(ab.bottom_home(ACTIVITIES.split("\n\n")[1], 0)) @@ -80,6 +89,25 @@ class DumpParsingTest(unittest.TestCase): self.assertIsNone(ab.logical_size(DISPLAYS, 5)) +class HogScriptTest(unittest.TestCase): + def test_both_modes_start_the_fill_counter(self): + script = ab.HOG.splitlines() + counter = next(n for n, line in enumerate(script) if line.startswith("i=0")) + self.assertLess(counter, script.index('if [ "$mode" = burst ]; then')) + self.assertLess(counter, next(n for n, line in enumerate(script) if line.startswith("while [ $i -lt 512 ]"))) + + + def test_a_failed_write_never_reports_released(self): + script = ab.HOG.splitlines() + check = script.index('[ "$failed" = 0 ] || { echo "write failed"; cleanup; exit 1; }') + self.assertLess(check, script.index("echo released")) + self.assertIn("failed=1", ab.HOG.split("echo released")[0]) + + def test_a_burst_takes_the_remainder_below_one_chunk(self): + self.assertIn("rest=$((take % 256))", ab.HOG) + self.assertIn('echo "nothing to take"', ab.HOG) + + class SummaryTest(unittest.TestCase): def test_max_adj_skips_samples_after_death(self): self.assertEqual(50, ab.max_adj(["0", "50", "DEAD", ""])) diff --git a/tools/tests/test_native_hook_cmdline.py b/tools/tests/test_native_hook_cmdline.py new file mode 100644 index 0000000000..81ff864e7c --- /dev/null +++ b/tools/tests/test_native_hook_cmdline.py @@ -0,0 +1,179 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +HOOK_BUILD = REPO / "tools/nativeguest/build.sh" +DDEXEC = REPO / "app/src/main/cpp/ddexec/ddexec.c" +DDEXEC_FLAGS = ["-shared", "-fPIC", "-O2", "-ffreestanding", "-fno-builtin", "-fno-stack-protector", + "-fno-asynchronous-unwind-tables", "-nostdlib", "-Wl,-e,_start", "-Wl,-z,noexecstack", + "-Wl,--no-undefined", "-Wl,-Bsymbolic"] + +WINDOWS_PROGRAM = "C:\\Program Files (x86)\\Battle.net\\Battle.net.exe" + +PROBE = r""" +#define _GNU_SOURCE +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <string.h> +#include <sys/auxv.h> +#include <sys/syscall.h> +#include <unistd.h> + +static void show_cmdline(const char *label) { + static char buf[1 << 20]; + int fd = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/cmdline", O_RDONLY); + ssize_t len = 0, n; + while (fd >= 0 && (n = read(fd, buf + len, sizeof(buf) - len)) > 0) len += n; + if (fd >= 0) close(fd); + while (len > 0 && buf[len - 1] == '\0') len--; + printf("%s", label); + for (ssize_t at = 0; at < len; at += (ssize_t)strlen(buf + at) + 1) printf("\t%s", buf + at); + printf("\n"); +} + +int main(int argc, char **argv) { + int contiguous = 1; + for (int i = 1; i < argc; i++) { + if (argv[i] != argv[i - 1] + strlen(argv[i - 1]) + 1) contiguous = 0; + } + printf("execfn\t%s\n", (const char *)getauxval(AT_EXECFN)); + printf("contiguous\t%d\n", contiguous); + printf("argv"); + for (int i = 0; i < argc; i++) printf("\t%s", argv[i]); + printf("\n"); + printf("name\t%s\t%s\n", program_invocation_name, program_invocation_short_name); + show_cmdline("cmdline"); + if (argc > 1 && contiguous) { + size_t offset = (size_t)(argv[1] - argv[0]); + char *end = argv[argc - 1] + strlen(argv[argc - 1]) + 1; + memmove(argv[0], argv[1], (size_t)(end - argv[1])); + memset(end - offset, 0, offset); + show_cmdline("shifted"); + } + return 0; +} +""" + + +class NativeHookCmdlineTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.ddexec = tmp / "lib/libddexec.so" + cls.ddexec.parent.mkdir() + subprocess.run([cls.cc, *DDEXEC_FLAGS, "-o", str(cls.ddexec), str(DDEXEC)], check=True) + cls.ddexec_runs = subprocess.run(list(cls.prefix) + [str(cls.ddexec), str(cls.probe), str(cls.probe)], + capture_output=True, timeout=120).returncode == 0 + cls.root = tmp / "root" + cls.root.mkdir() + if cls.prefix: + libs = Path(cls.prefix[cls.prefix.index("-L") + 1]) / "lib" + else: + libs = next(Path(p) for p in ("/lib/aarch64-linux-gnu", "/usr/lib/aarch64-linux-gnu", "/lib64") + if (Path(p) / "libc.so.6").exists()) + cls.ld_so = next(str(p) for p in (libs / "ld-linux-aarch64.so.1", Path("/lib/ld-linux-aarch64.so.1")) + if p.exists()) + cls.libs = str(libs) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_probe(self, argv, root=True, preload=False): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")} + if root: + env["DDNATV_ROOT"] = str(self.root) + runner_args = list(self.prefix) + if preload and self.prefix: + runner_args += ["-E", f"LD_PRELOAD={self.hook}"] + elif preload: + env["LD_PRELOAD"] = str(self.hook) + out = subprocess.run(runner_args + argv, env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()} + + def loader_argv(self, *args, name="/usr/bin/wine"): + named = ["--argv0", name] if name else [] + return [self.ld_so, "--preload", str(self.hook), "--library-path", self.libs, *named, str(self.probe), *args] + + def test_a_program_its_loader_starts_has_its_arguments_together(self): + seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray")) + self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM, "--in-tray"], seen["argv"]) + self.assertEqual(["1"], seen["contiguous"]) + self.assertEqual(["/usr/bin/wine", "wine"], seen["name"]) + + @unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments") + def test_the_command_line_shows_the_arguments_the_program_was_started_with(self): + seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray")) + self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM, "--in-tray"], seen["cmdline"]) + self.assertEqual([WINDOWS_PROGRAM, "--in-tray"], seen["shifted"]) + + @unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments") + def test_the_app_loader_in_front_of_the_loader_is_left_out(self): + if not self.ddexec_runs: + self.skipTest("libddexec.so does not start a program on this host") + seen = self.run_probe([str(self.ddexec), self.ld_so] + self.loader_argv(WINDOWS_PROGRAM)) + self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["argv"]) + self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["cmdline"]) + self.assertEqual([WINDOWS_PROGRAM], seen["shifted"]) + + @unittest.skipIf(runner()[1], "qemu answers AT_EXECFN from its own copy of the arguments") + def test_a_program_its_loader_starts_still_finds_its_own_path(self): + unchanged = self.run_probe(self.loader_argv(WINDOWS_PROGRAM), root=False) + self.assertEqual([str(self.probe)], unchanged["execfn"]) + seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray")) + self.assertEqual([WINDOWS_PROGRAM, "--in-tray"], seen["shifted"]) + self.assertEqual(unchanged["execfn"], seen["execfn"]) + + @unittest.skipIf(runner()[1], "qemu answers AT_EXECFN from its own copy of the arguments") + def test_a_program_the_app_loader_starts_still_finds_its_own_path(self): + if not self.ddexec_runs: + self.skipTest("libddexec.so does not start a program on this host") + argv = [str(self.ddexec), self.ld_so] + self.loader_argv(WINDOWS_PROGRAM) + unchanged = self.run_probe(argv, root=False) + seen = self.run_probe(argv) + self.assertEqual([WINDOWS_PROGRAM], seen["shifted"]) + self.assertEqual(unchanged["execfn"], seen["execfn"]) + self.assertNotEqual([""], seen["execfn"]) + + def test_a_loader_run_without_a_program_name_keeps_its_command_line(self): + argv = self.loader_argv(WINDOWS_PROGRAM, name=None) + seen = self.run_probe(argv) + self.assertEqual([str(self.probe), WINDOWS_PROGRAM], seen["argv"]) + self.assertEqual(["1"], seen["contiguous"]) + if not self.prefix: + self.assertEqual(argv, seen["cmdline"]) + + def test_outside_the_native_userland_the_command_line_is_unchanged(self): + argv = self.loader_argv(WINDOWS_PROGRAM) + seen = self.run_probe(argv, root=False) + self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["argv"]) + self.assertEqual(["0"], seen["contiguous"]) + if not self.prefix: + self.assertEqual(argv, seen["cmdline"]) + + def test_a_program_started_directly_is_unchanged(self): + seen = self.run_probe([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], preload=True) + self.assertEqual([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], seen["argv"]) + self.assertEqual(["1"], seen["contiguous"]) + if not self.prefix: + self.assertEqual([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], seen["cmdline"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_exec_target.py b/tools/tests/test_native_hook_exec_target.py new file mode 100644 index 0000000000..29c7b10cac --- /dev/null +++ b/tools/tests/test_native_hook_exec_target.py @@ -0,0 +1,116 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +RECORDER = r""" +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +int execve(const char *path, char *const argv[], char *const envp[]) { + const char *exe = "-"; + for (int i = 0; envp && envp[i]; i++) + if (strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) exe = envp[i] + 16; + printf("exe\t%s\n", exe); + fflush(stdout); + _exit(0); +} +""" + +PROBE = r""" +#include <stdio.h> +#include <unistd.h> + +int main(int argc, char **argv) { + if (argc < 2) return 0; + char *args[] = {argv[1], NULL}; + execv(argv[1], args); + perror("execv"); + return 1; +} +""" + + +class NativeHookExecTargetTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "recorder.c").write_text(RECORDER) + cls.recorder = tmp / "recorder.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + opt = cls.root / "opt" + (opt / "real").mkdir(parents=True) + (opt / "nest").mkdir() + (cls.root / "lib").mkdir() + (cls.root / "lib/ld-linux-aarch64.so.1").write_bytes(b"") + shutil.copy(cls.probe, opt / "real/prog") + shutil.copy(cls.probe, opt / "real/.l2s.prog0001") + os.symlink("./real", opt / "rel") + os.symlink("/opt/real", opt / "abs") + os.symlink("../rel", opt / "nest/sub") + os.symlink("rel/prog", opt / "link") + os.symlink(".l2s.prog0001", opt / "real/hard") + cls.real = str(opt / "real/prog") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def exe(self, program): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), program], env=env, capture_output=True, text=True, timeout=120) + for line in out.stdout.splitlines(): + if line.startswith("exe\t"): + return line.split("\t", 1)[1] + self.fail(out.stdout + out.stderr) + + def test_a_program_reached_through_a_relative_directory_link_is_named_by_its_real_path(self): + self.assertEqual(self.real, self.exe("/opt/rel/prog")) + + def test_a_program_reached_through_a_guest_absolute_directory_link_is_named_by_its_real_path(self): + self.assertEqual(self.real, self.exe("/opt/abs/prog")) + + def test_links_that_climb_with_dot_dot_resolve_like_the_kernel(self): + self.assertEqual(self.real, self.exe("/opt/nest/sub/./prog")) + + def test_a_link_to_the_program_itself_still_resolves(self): + self.assertEqual(self.real, self.exe("/opt/link")) + + def test_a_plain_path_is_unchanged(self): + self.assertEqual(self.real, self.exe("/opt/real/prog")) + + def test_a_missing_directory_is_not_skipped_by_dot_dot(self): + self.assertNotEqual(self.real, self.exe("/opt/missing/../real/prog")) + + def test_a_file_is_not_used_as_a_directory(self): + self.assertNotEqual(self.real, self.exe("/opt/real/prog/../prog")) + + def test_a_proot_hard_link_keeps_its_own_name(self): + self.assertEqual(str(self.root / "opt/real/hard"), self.exe("/opt/real/hard")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_execvp.py b/tools/tests/test_native_hook_execvp.py new file mode 100644 index 0000000000..6fa37c4664 --- /dev/null +++ b/tools/tests/test_native_hook_execvp.py @@ -0,0 +1,140 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +RECORDER = r""" +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <errno.h> +#include <fcntl.h> + +int execve(const char *path, char *const argv[], char *const envp[]) { + if (access(path, F_OK) != 0) { errno = ENOENT; return -1; } + if (access(path, X_OK) != 0) { errno = EACCES; return -1; } + char head[2] = {0}; + int fd = open(path, O_RDONLY); + if (fd >= 0) { if (read(fd, head, 2) < 0) head[0] = 0; close(fd); } + if (memcmp(head, "#!", 2) != 0 && memcmp(head, "\177E", 2) != 0) { + errno = ENOEXEC; + return -1; + } + printf("call"); + for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]); + printf("\n"); + fflush(stdout); + _exit(0); +} +""" + +PROBE = r""" +#define _GNU_SOURCE +#include <errno.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +int main(int argc, char **argv) { + int ret; + if (strcmp(argv[1], "vpe") == 0) { + char path[4096]; + snprintf(path, sizeof(path), "PATH=%s", argv[2]); + char *envp[] = {path, NULL}; + ret = execvpe(argv[3], argv + 3, envp); + } else { + ret = execvp(argv[2], argv + 2); + } + printf("ret\t%d\t%s\n", ret, strerror(errno)); + return 1; +} +""" + + +class NativeHookExecvpTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "recorder.c").write_text(RECORDER) + cls.recorder = tmp / "recorder.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + cls.dirs = Path("/opt/probe") + for name in ("bin", "opt/probe/locked", "opt/probe/open", "opt/probe/work"): + (cls.root / name).mkdir(parents=True) + (tmp / "sh.c").write_text("int main(void) { return 0; }\n") + subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/sh"), str(tmp / "sh.c")], check=True) + cls.script("locked/tool", 0o644) + cls.script("open/tool", 0o755, "#!/bin/sh\n") + cls.script("open/plain", 0o755) + cls.script("work/here", 0o755) + + @classmethod + def script(cls, name, mode, text="echo plain\n"): + path = cls.root / "opt/probe" / name + path.write_text(text) + path.chmod(mode) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def call(self, *argv, cwd=None): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), *argv], env=env, cwd=cwd, capture_output=True, text=True, + timeout=120) + for line in out.stdout.splitlines(): + if line.startswith("call\t"): + return line.split("\t")[1:] + if line.startswith("ret\t"): + return line.split("\t")[1:] + self.fail(out.stdout + out.stderr) + + def test_a_script_without_a_shebang_runs_through_sh(self): + plain = str(self.dirs / "open/plain") + self.assertEqual(["/bin/sh", plain, "a"], self.call("vp", plain, "a")) + + def test_path_search_runs_a_script_without_a_shebang_through_sh(self): + plain = str(self.dirs / "open/plain") + self.assertEqual(["/bin/sh", plain, "a"], self.call("vpe", str(self.dirs / "open"), "plain", "a")) + + def test_a_denied_entry_earlier_in_path_is_skipped(self): + path = f"{self.dirs / 'locked'}:{self.dirs / 'open'}" + call = self.call("vpe", path, "tool", "x") + self.assertTrue(call[-2].endswith("/opt/probe/open/tool"), call) + self.assertEqual("x", call[-1]) + + def test_only_denied_entries_report_permission_denied(self): + self.assertEqual(["-1", os.strerror(13)], self.call("vpe", str(self.dirs / "locked"), "tool")) + + def test_an_empty_path_entry_means_the_current_directory(self): + here = self.call("vpe", f"{self.dirs / 'open'}:", "here", cwd=self.root / "opt/probe/work") + self.assertEqual(["/bin/sh", "here"], here) + + def test_a_bare_name_is_not_run_from_the_current_directory_without_an_empty_entry(self): + missing = self.call("vpe", str(self.dirs / "open"), "here", cwd=self.root / "opt/probe/work") + self.assertEqual(["-1", os.strerror(2)], missing) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_go_identity.py b/tools/tests/test_native_hook_go_identity.py new file mode 100644 index 0000000000..3ebc1d53df --- /dev/null +++ b/tools/tests/test_native_hook_go_identity.py @@ -0,0 +1,147 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +MAIN = r""" +package main + +import ( + "fmt" + "probe/quiet" + "syscall" +) + +func main() { + _, _, errno := syscall.RawSyscall(syscall.SYS_SETREUID, ^uintptr(0), 0, 0) + euid, _ := quiet.Call(syscall.SYS_GETEUID, 0, 0, 0) + fmt.Println(syscall.Getuid(), syscall.Getgid(), int(euid), errno == 0) +} +""" + +QUIET = """#include "textflag.h" + +TEXT ·Call(SB),NOSPLIT,$0-48 +\tMOVD\ta1+8(FP), R0 +\tMOVD\ta2+16(FP), R1 +\tMOVD\ta3+24(FP), R2 +\tMOVD\t$0, R3 +\tMOVD\t$0, R4 +\tMOVD\t$0, R5 +\tMOVD\ttrap+0(FP), R8 +\tSVC +\tMOVD\tR0, r1+32(FP) +\tMOVD\tR1, r2+40(FP) +\tRET +""" + +QUIET_GO = """package quiet + +func Call(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) +""" + +CGO = """package main + +import "C" +""" + +LAUNCHER = r""" +#include <unistd.h> + +int main(int argc, char **argv) { + execv(argv[1], argv + 1); + return 0; +} +""" + + +class NativeHookGoIdentityTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + if not shutil.which("go"): + raise unittest.SkipTest("no Go toolchain") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "launcher.c").write_text(LAUNCHER) + cls.launcher = tmp / "launcher" + subprocess.run([cls.cc, "-O1", "-o", str(cls.launcher), str(tmp / "launcher.c")], check=True) + src = tmp / "src" + src.mkdir() + (src / "go.mod").write_text("module probe\n\ngo 1.19\n") + (src / "main.go").write_text(MAIN) + (src / "quiet").mkdir() + (src / "quiet/quiet.go").write_text(QUIET_GO) + (src / "quiet/quiet_arm64.s").write_text(QUIET) + (src / "cgo.go").write_text(CGO) + cls.root = tmp / "root" + (cls.root / "usr/bin").mkdir(parents=True) + cls.go_env = {**os.environ, "GOOS": "linux", "GOARCH": "arm64", "GOCACHE": str(tmp / "gocache"), + "GOPATH": str(tmp / "gopath"), "GOFLAGS": "-buildvcs=false", "GOTOOLCHAIN": "local"} + cls.static = cls.root / "usr/bin/go-static" + subprocess.run(["go", "build", "-o", str(cls.static), "."], cwd=src, check=True, capture_output=True, + env={**cls.go_env, "CGO_ENABLED": "0"}) + cls.dynamic = cls.root / "usr/bin/go-dynamic" + built = subprocess.run(["go", "build", "-o", str(cls.dynamic), "."], cwd=src, capture_output=True, + env={**cls.go_env, "CGO_ENABLED": "1", "CC": cls.cc}) + if built.returncode != 0: + cls.dynamic = None + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def prepare(self, program): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + subprocess.run(cmd + [str(self.launcher), str(program)], env=env, capture_output=True, timeout=120) + return b"CXGOSYS1" in program.read_bytes() + + def run_go(self, program): + cmd = list(self.prefix) + [str(program)] + result = subprocess.run(cmd, capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.split() + + def check_identity(self, program): + before = self.run_go(program) + if os.getuid() != 0: + self.assertNotEqual(before[0], "0") + self.assertEqual(before[3], "false") + self.assertTrue(self.prepare(program)) + self.assertEqual(self.run_go(program), ["0", "0", "0", "true"]) + moved = self.root.with_name("root-away") + self.root.rename(moved) + try: + away = self.run_go(moved / program.relative_to(self.root)) + finally: + moved.rename(self.root) + if os.getuid() != 0: + self.assertEqual(away, before) + + def test_static_go_program_sees_the_session_identity(self): + self.check_identity(self.static) + + def test_dynamic_go_program_sees_the_session_identity(self): + if self.dynamic is None: + self.skipTest("no cgo cross build") + self.check_identity(self.dynamic) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_ldso_spawn.py b/tools/tests/test_native_hook_ldso_spawn.py new file mode 100644 index 0000000000..8d8b417f82 --- /dev/null +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -0,0 +1,232 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" +GUEST_LDSO = "/usr/lib/ld-linux-aarch64.so.1" +GUEST_TOOL = "/usr/local/bin/tool" +BOUND_DIR = "/opt/runtime" +ANDROID_DIR = "/opt/android" +HOST_SHELL = "/data/local/tmp/droiddeck-hook-probe-sh" + +RECORDER = r""" +#define _GNU_SOURCE +#include <spawn.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +static void show(const char *path, char *const argv[], char *const envp[]) { + printf("call\t%s", path); + for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]); + printf("\n"); + for (int i = 0; envp && envp[i]; i++) + if (strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) printf("libpath\t%s\n", envp[i] + 20); + else if (strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0) printf("envpath\t%s\n", envp[i] + 16); + fflush(stdout); +} + +int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions, + const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { + show(path, argv, envp); + if (pid) *pid = 1; + return 0; +} + +int execve(const char *path, char *const argv[], char *const envp[]) { + show(path, argv, envp); + _exit(0); +} +""" + +PROBE = r""" +#include <spawn.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +extern char **environ; + +int main(int argc, char **argv) { + if (argc < 3) return 2; + if (strcmp(argv[1], "spawn") == 0) { + pid_t pid; + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + posix_spawn_file_actions_adddup2(&actions, 1, 1); + int ret = posix_spawn(&pid, argv[2], &actions, NULL, argv + 2, environ); + posix_spawn_file_actions_destroy(&actions); + printf("ret\t%d\n", ret); + return 0; + } + execve(argv[2], argv + 2, environ); + printf("ret\t-1\n"); + return 1; +} +""" + + +def guest_loader(prefix): + roots = [Path(prefix[prefix.index("-L") + 1])] if prefix and "-L" in prefix else [Path("/")] + for root in roots: + for name in ("lib/ld-linux-aarch64.so.1", "lib64/ld-linux-aarch64.so.1", "usr/lib/ld-linux-aarch64.so.1"): + if (root / name).exists(): + return root / name + return None + + +class NativeHookLdsoSpawnTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + loader = guest_loader(cls.prefix) + if loader is None: + raise unittest.SkipTest("no aarch64 glibc loader to put in the rootfs") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "recorder.c").write_text(RECORDER) + cls.recorder = tmp / "recorder.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + for guest, source in ((GUEST_LDSO, loader), (GUEST_TOOL, cls.probe)): + host = cls.root / guest.lstrip("/") + host.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(source, host) + host.chmod(0o755) + (cls.root / "usr/lib/aarch64-linux-gnu").mkdir(parents=True, exist_ok=True) + cls.runtime = tmp / "runtime" + cls.runtime.mkdir() + shutil.copy(cls.probe, cls.runtime / "bash") + (cls.runtime / "bash").chmod(0o755) + cls.android = tmp / "root-android" + cls.android.mkdir() + subprocess.run([cls.cc, "-O1", "-Wl,--dynamic-linker=/system/bin/linker64", "-o", str(cls.android / "sh"), + str(tmp / "probe.c")], check=True) + for name, interpreter in (("bound.sh", f"{BOUND_DIR}/bash"), ("host.sh", HOST_SHELL), + ("android.sh", f"{ANDROID_DIR}/sh")): + script = cls.root / "opt" / name + script.parent.mkdir(exist_ok=True) + script.write_text(f"#!{interpreter}\n") + script.chmod(0o755) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def call(self, how, *argv, binds=None, real_exe=None, ld_library_path=None): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + if binds: + hook_env["DDNATV_BINDS"] = binds + if real_exe: + hook_env["DDNATV_REAL_EXE"] = real_exe + if ld_library_path is not None: + hook_env["LD_LIBRARY_PATH"] = ld_library_path + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120) + calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")] + self.library_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("libpath\t")] + self.env_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("envpath\t")] + self.assertEqual(1, len(calls), out.stdout + out.stderr) + if how == "spawn": + self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr) + return calls[0] + + def test_spawned_ldso_list_loads_the_program_from_the_rootfs(self): + call = self.call("spawn", GUEST_LDSO, "--list", GUEST_TOOL) + argv = call[1:] + self.assertEqual(str(self.root / GUEST_TOOL.lstrip("/")), argv[-1]) + self.assertEqual("--list", argv[-2]) + self.assertIn("--library-path", argv[:-2]) + + def test_spawn_and_exec_start_ldso_with_the_same_arguments(self): + for args in (("--list", GUEST_TOOL), (GUEST_TOOL, "x"), ("--library-path", "/opt/own", "--list", GUEST_TOOL)): + with self.subTest(args=args): + self.assertEqual(self.call("exec", GUEST_LDSO, *args), self.call("spawn", GUEST_LDSO, *args)) + + def test_a_callers_own_library_path_is_kept(self): + call = self.call("spawn", GUEST_LDSO, "--library-path", "/opt/own", "--list", GUEST_TOOL) + self.assertEqual([GUEST_LDSO, "--library-path", "/opt/own", "--list", str(self.root / GUEST_TOOL.lstrip("/"))], call[1:]) + + def test_ldso_without_a_program_is_spawned_unchanged(self): + call = self.call("spawn", GUEST_LDSO, "--version") + self.assertEqual([GUEST_LDSO, "--version"], call[1:]) + + def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self): + self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x")) + + def test_guest_library_environment_is_preserved(self): + for how in ("exec", "spawn"): + for value in (None, "", "/custom/lib:/other/lib"): + with self.subTest(how=how, value=value): + argv = self.call(how, GUEST_TOOL, ld_library_path=value)[1:] + self.assertEqual([] if value is None else [value], self.env_paths) + self.assertIn(str(self.root / "usr/lib/aarch64-linux-gnu"), argv[argv.index("--library-path") + 1]) + + def test_a_program_started_through_ldso_records_its_library_path(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + argv = self.call(how, GUEST_TOOL, "x")[1:] + self.assertEqual([argv[argv.index("--library-path") + 1]], self.library_paths) + + def test_ldso_started_by_name_records_no_library_path(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + self.call(how, GUEST_LDSO, "--list", GUEST_TOOL) + self.assertEqual([], self.library_paths) + + def test_a_program_from_a_bind_starts_itself_again_through_proc_self_exe(self): + bash = str(self.runtime / "bash") + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/proc/self/exe", "x", binds=f"/proc:/proc|{self.runtime}:{BOUND_DIR}", real_exe=bash) + self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0]) + self.assertEqual([bash, "x"], call[-2:]) + + def test_a_rootfs_program_starts_itself_again_through_proc_self_exe(self): + tool = str(self.root / GUEST_TOOL.lstrip("/")) + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/proc/self/exe", "x", binds="/proc:/proc", real_exe=tool) + self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0]) + self.assertEqual([tool, "x"], call[-2:]) + + def test_a_script_interpreter_from_a_bind_runs_as_a_guest_program(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/opt/bound.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}") + self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0]) + self.assertEqual([str(self.runtime / "bash"), str(self.root / "opt/bound.sh"), "x"], call[-3:]) + + def test_a_script_interpreter_outside_the_rootfs_and_its_binds_stays_on_the_host(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/opt/host.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}") + self.assertEqual([HOST_SHELL, HOST_SHELL, str(self.root / "opt/host.sh"), "x"], call) + + def test_an_android_interpreter_reached_through_a_bind_stays_on_the_host(self): + sh = str(self.android / "sh") + for how in ("exec", "spawn"): + with self.subTest(how=how): + call = self.call(how, "/opt/android.sh", "x", binds=f"{self.android}:{ANDROID_DIR}") + self.assertEqual([sh, sh, str(self.root / "opt/android.sh"), "x"], call) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_mounts.py b/tools/tests/test_native_hook_mounts.py index ff46a0fa18..ca56256aa7 100644 --- a/tools/tests/test_native_hook_mounts.py +++ b/tools/tests/test_native_hook_mounts.py @@ -12,14 +12,54 @@ PROBE = r""" #include <dirent.h> #include <fcntl.h> #include <stdio.h> +#include <stdlib.h> #include <string.h> #include <sys/stat.h> +#include <sys/wait.h> #include <unistd.h> int main(int argc, char **argv) { char cwd[4096]; for (int i = 1; i < argc; i++) { struct stat st; + if (strncmp(argv[i], "env:", 4) == 0) { + const char *value = getenv(argv[i] + 4); + printf("%s\t%s\n", argv[i], value ? value : "-"); + continue; + } + if (strncmp(argv[i], "parent:", 7) == 0) { + char dir[4096]; + snprintf(dir, sizeof(dir), "%s", argv[i] + 7); + char *rel = strchr(dir, '|'), *want = NULL; + if (rel) *rel++ = 0; + if (rel && (want = strchr(rel, '|'))) *want++ = 0; + int fd = open(dir, O_RDONLY | O_DIRECTORY); + struct stat expected; + int ok = fd >= 0 && fstatat(fd, rel ? rel : "..", &st, 0) == 0 && stat(want ? want : "/", &expected) == 0; + printf("%s\t%d\n", argv[i], ok && st.st_dev == expected.st_dev && st.st_ino == expected.st_ino); + if (fd >= 0) close(fd); + continue; + } + if (strncmp(argv[i], "fork:", 5) == 0) { + fflush(stdout); + pid_t pid = fork(); + if (pid == 0) { + int p[2]; + char path[64], data[8] = "-"; + if (pipe(p) == 0 && write(p[1], "x", 1) == 1 && dup2(p[0], 63) == 63) { + snprintf(path, sizeof(path), "%s/63", argv[i] + 5); + int fd = open(path, O_RDONLY); + ssize_t n = fd >= 0 ? read(fd, data, sizeof(data) - 1) : -1; + if (n > 0) data[n] = 0; + if (fd >= 0) close(fd); + } + printf("%s\t%s\n", argv[i], data); + fflush(stdout); + _exit(0); + } + waitpid(pid, NULL, 0); + continue; + } if (strncmp(argv[i], "cd:", 3) == 0) { int ok = chdir(argv[i] + 3) == 0 && getcwd(cwd, sizeof(cwd)) != NULL; printf("%s\t%s\n", argv[i], ok ? cwd : "-"); @@ -76,6 +116,8 @@ class NativeHookMountTest(unittest.TestCase): cls.root = tmp / "root" cls.library = tmp / "storage/PC GAMES" (cls.root / "etc").mkdir(parents=True) + (cls.root / "deep/er/est").mkdir(parents=True) + (cls.root / "linked").symlink_to("deep/er/est") (cls.root / "etc/hostname").write_text("rootfs") (cls.root / "mnt/library/Some Game").mkdir(parents=True) (cls.root / "mnt/library/Some Game/game.txt").write_text("mount point") @@ -117,10 +159,11 @@ class NativeHookMountTest(unittest.TestCase): def tearDownClass(cls): cls.tmp.cleanup() - def run_probe(self, *args): - binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}" + def run_probe(self, *args, binds=None): + if binds is None: + binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}" hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)} - env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "LOCPATH", "GCONV_PATH")} if self.prefix: cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] else: @@ -131,6 +174,18 @@ class NativeHookMountTest(unittest.TestCase): self.assertEqual(out.returncode, 0, out.stderr) return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()} + def test_dev_fd_in_a_forked_child_names_the_child_descriptors(self): + out = self.run_probe("fork:/dev/fd", binds="/proc/self/fd:/dev/fd") + self.assertEqual(["x"], out["fork:/dev/fd"]) + + def test_a_mount_named_through_proc_self_root_reports_its_guest_path(self): + arg = f"cd:{GAME}/" + self.assertEqual(self.run_probe(arg, binds=f"/proc/self/root{self.library}:/mnt/library")[arg], [GAME]) + + def test_a_proc_mount_that_names_no_process_reports_its_guest_path(self): + arg = "cd:/mnt/sys/kernel/" + self.assertEqual(self.run_probe(arg, binds="/proc/self/root/proc/sys:/mnt/sys")[arg], ["/mnt/sys/kernel"]) + def test_drive_link_stored_as_rootfs_path_reaches_the_mount(self): path = f"/pfx/native/dosdevices/z:{GAME}/game.txt" self.assertEqual(self.run_probe(path)[path], ["1", "library"]) @@ -147,6 +202,42 @@ class NativeHookMountTest(unittest.TestCase): path = f"/pfx/guest/dosdevices/z:{GAME}/game.txt" self.assertEqual(self.run_probe(path)[path], ["1", "library"]) + def test_glibc_locale_and_iconv_data_come_from_the_rootfs(self): + result = self.run_probe("env:LOCPATH", "env:GCONV_PATH") + self.assertEqual(result["env:LOCPATH"], [f"{self.root}/usr/lib/locale"]) + self.assertEqual(result["env:GCONV_PATH"], [f"{self.root}/usr/lib/aarch64-linux-gnu/gconv"]) + + def test_parent_of_root_stays_at_root(self): + self.assertEqual(self.run_probe("parent:/")["parent:/"], ["1"]) + + def test_parent_of_root_without_mounts_stays_at_root(self): + self.assertEqual(self.run_probe("parent:/", binds="")["parent:/"], ["1"]) + + def test_parent_of_mount_ancestor_is_guest_root(self): + self.assertEqual(self.run_probe("parent:/mnt")["parent:/mnt"], ["1"]) + + def test_parent_walks_from_any_directory_stay_at_root(self): + cases = ["parent:/etc|../..", "parent:/mnt/library|../../..", "parent:/|../etc/.."] + self.assertEqual(self.run_probe(*cases), {case: ["1"] for case in cases}) + + def test_parent_walk_from_a_linked_mount_ancestor_follows_the_real_directory(self): + binds = f"{self.library}:/linked/library" + case = "parent:/linked|../..|/deep" + self.assertEqual(self.run_probe(case, binds=binds)[case], ["1"]) + + def test_absolute_paths_above_root_stay_at_root(self): + result = self.run_probe("cd:/..", "cd:/etc/../..", "/../etc/hostname") + self.assertEqual(result["cd:/.."], [str(self.root)]) + self.assertEqual(result["cd:/etc/../.."], [str(self.root)]) + self.assertEqual(result["/../etc/hostname"], ["1", "rootfs"]) + + def test_relative_parent_of_cwd_stays_in_guest(self): + result = self.run_probe("cd:/", "cd:..", "cd:./../..", "../etc/hostname", f"cd:{GAME}", "cd:../..") + self.assertEqual(result["cd:.."], [str(self.root)]) + self.assertEqual(result["cd:./../.."], [str(self.root)]) + self.assertEqual(result["cd:../.."], [str(self.root / "mnt")]) + self.assertEqual(result["../etc/hostname"], ["1", "rootfs"]) + def test_rootfs_paths_outside_mounts_are_unchanged(self): paths = ["/pfx/native/dosdevices/z:/etc/hostname", f"{self.root}/etc/hostname", "/etc/hostname"] result = self.run_probe(*paths) diff --git a/tools/tests/test_native_hook_named_semaphores.py b/tools/tests/test_native_hook_named_semaphores.py new file mode 100644 index 0000000000..09abea076b --- /dev/null +++ b/tools/tests/test_native_hook_named_semaphores.py @@ -0,0 +1,159 @@ +from pathlib import Path +import os +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <semaphore.h> +#include <stdio.h> +#include <sys/wait.h> +#include <unistd.h> + +static void show(const char *name, int ok) { printf("%s\t%d\n", name, ok); fflush(stdout); } + +int main(int argc, char **argv) { + const char *name = argv[1]; + sem_t *sem = sem_open(name, O_CREAT | O_EXCL, 0600, 1); + show("create", sem != SEM_FAILED); + show("exclusive", sem_open(name, O_CREAT | O_EXCL, 0600, 1) == SEM_FAILED && errno == EEXIST); + sem_t *again = sem_open(name, O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1); + int value = -1; + show("existing", again == sem && sem_getvalue(again, &value) == 0 && value == 1); + show("too-large", sem_open("/ddsem-absent", O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1) == SEM_FAILED && errno == EINVAL); + show("wait", sem_wait(sem) == 0 && sem_trywait(again) == -1 && errno == EAGAIN); + pid_t child = fork(); + if (child == 0) { + sem_t *other = sem_open(name, 0); + _exit(other != SEM_FAILED && sem_post(other) == 0 && sem_close(other) == 0 ? 0 : 1); + } + int status = 0; + waitpid(child, &status, 0); + show("shared", WIFEXITED(status) && WEXITSTATUS(status) == 0 && sem_trywait(sem) == 0); + show("close", sem_close(again) == 0 && sem_post(sem) == 0 && sem_close(sem) == 0 && sem_close(sem) == -1 && errno == EINVAL); + show("unlink", sem_unlink(name) == 0); + show("gone", sem_open(name, 0) == SEM_FAILED && errno == ENOENT); + return 0; +} +""" + +KEEP = r""" +#include <fcntl.h> +#include <semaphore.h> +int main(int argc, char **argv) { return sem_open(argv[1], O_CREAT | O_EXCL, 0640, 3) == SEM_FAILED; } +""" + +FORKER = r""" +#include <fcntl.h> +#include <pthread.h> +#include <semaphore.h> +#include <stdio.h> +#include <sys/wait.h> +#include <unistd.h> + +static const char *name; +static _Atomic int done; + +static void *churn(void *arg) { + while (!done) { + sem_t *sem = sem_open(name, O_CREAT, 0600, 0); + if (sem != SEM_FAILED) sem_close(sem); + } + return arg; +} + +int main(int argc, char **argv) { + name = argv[1]; + pthread_t thread; + if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1; + int finished = 0; + for (int i = 0; i < 200; i++) { + pid_t pid = fork(); + if (pid < 0) break; + if (pid == 0) { + alarm(10); + sem_t *sem = sem_open(name, O_CREAT, 0600, 0); + _exit(sem == SEM_FAILED || sem_close(sem) != 0); + } + int status; + if (waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++; + } + done = 1; + pthread_join(thread, NULL); + sem_unlink(name); + printf("finished\t%d\n", finished); + return 0; +} +""" + +CALLS = ("create", "exclusive", "existing", "too-large", "wait", "shared", "close", "unlink", "gone") + + +class NativeHookNamedSemaphoresTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.shm = tmp / "root/tmp/shm" + cls.shm.mkdir(parents=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_hooked(self, program, *args): + hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "LD_PRELOAD": str(self.hook)} + env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(program), *args], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return dict(line.split("\t") for line in out.stdout.splitlines()) + + def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self): + name = f"/ddsem-{os.getpid()}" + self.assertEqual({call: "1" for call in CALLS}, self.run_hooked(self.probe, name)) + self.assertFalse(Path(f"/dev/shm/sem.{name[1:]}").exists()) + self.assertEqual([], list(self.shm.iterdir())) + + def test_a_child_forked_while_another_thread_opens_a_semaphore_can_open_one(self): + source = self.probe.with_name("forker.c") + source.write_text(FORKER) + forker = self.probe.with_name("forker") + subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True) + self.assertEqual({"finished": "200"}, self.run_hooked(forker, f"/ddsem-fork-{os.getpid()}")) + + def test_a_created_semaphore_keeps_its_name_and_mode(self): + name = f"ddsem-kept-{os.getpid()}" + source = self.probe.with_name("keep.c") + source.write_text(KEEP) + keep = self.probe.with_name("keep") + subprocess.run([self.cc, "-O1", "-pthread", "-o", str(keep), str(source)], check=True) + self.run_hooked(keep, name) + made = self.shm / f"sem.{name}" + self.addCleanup(made.unlink) + umask = os.umask(0) + os.umask(umask) + self.assertEqual([made.name], [p.name for p in self.shm.iterdir()]) + self.assertEqual(0o640 & ~umask, made.stat().st_mode & 0o777) + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_path_syscalls.py b/tools/tests/test_native_hook_path_syscalls.py new file mode 100644 index 0000000000..be0967cbb0 --- /dev/null +++ b/tools/tests/test_native_hook_path_syscalls.py @@ -0,0 +1,189 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#define _GNU_SOURCE +#include <fcntl.h> +#include <limits.h> +#include <stddef.h> +#include <stdio.h> +#include <string.h> +#include <sys/socket.h> +#include <sys/syscall.h> +#include <sys/un.h> +#include <unistd.h> + +static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); } + +int main(int argc, char **argv) { + const char *dir = argv[1]; + char p[PATH_MAX], q[PATH_MAX], cwd[PATH_MAX]; + snprintf(p, sizeof(p), "%s/made", dir); + show("mkdirat", syscall(SYS_mkdirat, AT_FDCWD, p, 0755)); + snprintf(p, sizeof(p), "%s/made/file", dir); + long fd = syscall(SYS_openat, AT_FDCWD, p, O_WRONLY | O_CREAT | O_CLOEXEC, 0644); + show("openat", fd); + if (fd >= 0) close((int)fd); + show("truncate", syscall(SYS_truncate, p, 4)); + show("fchmodat", syscall(SYS_fchmodat, AT_FDCWD, p, 0600)); + show("utimensat", syscall(SYS_utimensat, AT_FDCWD, p, NULL, 0)); + fd = syscall(SYS_openat, AT_FDCWD, p, O_RDONLY | O_CLOEXEC); + show("futimens", fd >= 0 ? syscall(SYS_utimensat, (int)fd, NULL, NULL, 0) : -1); + if (fd >= 0) close((int)fd); + snprintf(q, sizeof(q), "%s/made/moved", dir); + show("renameat", syscall(SYS_renameat, AT_FDCWD, p, AT_FDCWD, q)); + show("renameat2", syscall(SYS_renameat2, AT_FDCWD, q, AT_FDCWD, p, 0)); + snprintf(q, sizeof(q), "%s/made/link", dir); + show("symlinkat", syscall(SYS_symlinkat, "file", AT_FDCWD, q)); + show("unlinkat", syscall(SYS_unlinkat, AT_FDCWD, q, 0)); + snprintf(q, sizeof(q), "%s/made/sock", dir); + struct sockaddr_un addr = {.sun_family = AF_UNIX}, extra = {.sun_family = AF_UNIX}; + size_t len = strlen(q); + int fits = len + sizeof("-extra") <= sizeof(addr.sun_path); + if (fits) { + memcpy(addr.sun_path, q, len); + memcpy(extra.sun_path, q, len); + memcpy(extra.sun_path + len, "-extra", sizeof("-extra")); + } + int server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + show("bind", fits ? syscall(SYS_bind, server, &addr, sizeof(addr)) : -1); + listen(server, 1); + show("connect", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1); + close(client); + close(server); + syscall(SYS_unlinkat, AT_FDCWD, q, 0); + server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + show("bind-length", fits ? syscall(SYS_bind, server, &extra, offsetof(struct sockaddr_un, sun_path) + len) : -1); + listen(server, 1); + show("connect-length", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1); + close(client); + close(server); + syscall(SYS_unlinkat, AT_FDCWD, q, 0); + snprintf(q, sizeof(q), "%s/made", dir); + show("chdir", syscall(SYS_chdir, q)); + show("cwd", getcwd(cwd, sizeof(cwd)) && strstr(cwd, "/made") ? 0 : -1); + show("unlinkat-file", syscall(SYS_unlinkat, AT_FDCWD, p, 0)); + show("unlinkat-dir", syscall(SYS_unlinkat, AT_FDCWD, q, AT_REMOVEDIR)); + return 0; +} +""" + +ALLOCATOR = r""" +#define _GNU_SOURCE +#include <fcntl.h> +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/syscall.h> +#include <unistd.h> + +extern void *__libc_malloc(size_t); +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static int ready; + +void *malloc(size_t size) { + if (!ready) { + pthread_mutex_lock(&lock); + if (!ready) { + long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/stat", O_RDONLY | O_CLOEXEC); + if (fd >= 0) close((int)fd); + ready = 1; + } + pthread_mutex_unlock(&lock); + } + return __libc_malloc(size); +} + +int main(void) { + puts("ready"); + return 0; +} +""" + +EARLY = r""" +#include <stdlib.h> + +__attribute__((constructor)) static void early(void) { free(malloc(1)); } +""" + +CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat", + "bind", "connect", "bind-length", "connect-length", "chdir", "cwd", "unlinkat-file", "unlinkat-dir") + + +class NativeHookPathSyscallsTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + (cls.root / "opt").mkdir(parents=True) + (tmp / "allocator.c").write_text(ALLOCATOR) + cls.allocator = tmp / "allocator" + subprocess.run([cls.cc, "-O1", "-rdynamic", "-pthread", "-o", str(cls.allocator), str(tmp / "allocator.c")], check=True) + (tmp / "early.c").write_text(EARLY) + cls.early = tmp / "early.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.early), str(tmp / "early.c")], check=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_program(self, argv, hook_env): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + return subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120) + + def run_probe(self, guest_dir, hook=True): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {} + out = self.run_program([str(self.probe), guest_dir], hook_env) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: int(line.split("\t")[1]) for line in out.stdout.splitlines()} + + def test_guest_paths_through_syscall_land_in_the_root(self): + results = self.run_probe("/opt") + for call in CALLS: + with self.subTest(call=call): + self.assertEqual(1, results[call]) + self.assertEqual([], list((self.root / "opt").iterdir())) + + def test_paths_already_in_the_root_are_kept(self): + results = self.run_probe(str(self.root / "opt")) + for call in CALLS: + with self.subTest(call=call): + self.assertEqual(1, results[call]) + + def test_without_the_hook_guest_paths_reach_the_host(self): + results = self.run_probe("/opt/droiddeck-hook-probe-missing", hook=False) + self.assertEqual(0, results["mkdirat"]) + self.assertEqual(0, results["openat"]) + self.assertEqual(0, results["chdir"]) + + def test_an_allocator_opening_files_before_the_hook_starts_does_not_hang(self): + hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": "/proc:/proc", + "LD_PRELOAD": f"{self.hook}:{self.early}"} + out = self.run_program([str(self.allocator)], hook_env) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual("ready", out.stdout.strip()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_proc_exe.py b/tools/tests/test_native_hook_proc_exe.py index fdf6e615ab..479c78109d 100644 --- a/tools/tests/test_native_hook_proc_exe.py +++ b/tools/tests/test_native_hook_proc_exe.py @@ -57,6 +57,16 @@ class NativeHookProcExeTest(unittest.TestCase): (cls.root / "usr/bin").mkdir(parents=True) cls.kwin = cls.root / "usr/bin/kwin_wayland" shutil.copy(tmp / "sleeper", cls.kwin) + cls.runtime = tmp / "runtime" + cls.runtime.mkdir() + cls.bound = cls.runtime / "chrome" + shutil.copy(tmp / "sleeper", cls.bound) + cls.shadowed = cls.runtime / "bin/chrome" + cls.shadowed.parent.mkdir() + shutil.copy(tmp / "sleeper", cls.shadowed) + cls.override = tmp / "override" + cls.override.mkdir() + shutil.copy(tmp / "sleeper", cls.override / "chrome") # The child's /proc/<pid>/exe must name the loader, as DroidDeck's libddexec.so does. cls.loader = tmp / "lib/libddexec.so" cls.loader.parent.mkdir() @@ -64,8 +74,8 @@ class NativeHookProcExeTest(unittest.TestCase): shutil.copy(shutil.which(cls.prefix[0]), cls.loader) cls.loader_args = list(cls.prefix[1:]) else: - ld = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p)) - shutil.copy(ld, cls.loader) + cls.ld_so = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p)) + shutil.copy(cls.ld_so, cls.loader) cls.loader_args = [] @classmethod @@ -73,11 +83,13 @@ class NativeHookProcExeTest(unittest.TestCase): cls.tmp.cleanup() def start(self, loader, real_exe=None, program=None): - env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_REAL_EXE")} - if real_exe: - env["DDNATV_REAL_EXE"] = real_exe program = program or Path(self.tmp.name) / "sleeper" cmd = ([str(self.loader), *self.loader_args] if loader else list(self.prefix)) + [str(program)] + return self.spawn(cmd, {"DDNATV_REAL_EXE": real_exe} if real_exe else {}) + + def spawn(self, cmd, extra_env): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")} + env.update(extra_env) child = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, text=True) self.addCleanup(child.stdout.close) self.addCleanup(child.wait) @@ -85,8 +97,10 @@ class NativeHookProcExeTest(unittest.TestCase): self.assertEqual("ready", child.stdout.readline().strip()) return child.pid - def readlink(self, *paths): + def readlink(self, *paths, binds=None): hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + if binds: + hook_env["DDNATV_BINDS"] = binds env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} if self.prefix: cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] @@ -108,6 +122,17 @@ class NativeHookProcExeTest(unittest.TestCase): at = f"at:/proc/{pid}" self.assertEqual("/usr/bin/kwin_wayland", self.readlink(at)[at]) + def test_a_guest_program_from_a_bind_is_named_by_its_guest_path(self): + pid = self.start(loader=True, real_exe=str(self.bound), program=self.bound) + link = f"/proc/{pid}/exe" + self.assertEqual("/app/extra/chrome", self.readlink(link, binds=f"/proc:/proc|{self.runtime}:/app/extra")[link]) + + def test_a_guest_program_shadowed_by_a_nested_bind_keeps_its_own_path(self): + pid = self.start(loader=True, real_exe=str(self.shadowed), program=self.shadowed) + link = f"/proc/{pid}/exe" + binds = f"/proc:/proc|{self.runtime}:/app|{self.override}:/app/bin" + self.assertEqual(str(self.shadowed), self.readlink(link, binds=binds)[link]) + def test_a_program_named_only_in_the_environment_is_not_believed(self): pid = self.start(loader=True, real_exe=str(self.kwin)) link = f"/proc/{pid}/exe" @@ -118,6 +143,14 @@ class NativeHookProcExeTest(unittest.TestCase): link = f"/proc/{pid}/exe" self.assertEqual(os.readlink(link), self.readlink(link)[link]) + @unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments") + def test_a_program_whose_hook_moved_its_arguments_is_still_named(self): + cmd = [self.ld_so, "--preload", str(self.hook), "--argv0", self.kwin.name, str(self.kwin)] + pid = self.spawn(cmd, {"DDNATV_ROOT": str(self.root), "DDNATV_REAL_EXE": str(self.kwin)}) + self.assertEqual(b"kwin_wayland", Path(f"/proc/{pid}/cmdline").read_bytes().rstrip(b"\0")) + link = f"/proc/{pid}/exe" + self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link]) + def test_a_loader_without_a_known_program_keeps_the_kernel_link(self): pid = self.start(loader=True) link = f"/proc/{pid}/exe" diff --git a/tools/tests/test_native_hook_readlink.py b/tools/tests/test_native_hook_readlink.py new file mode 100644 index 0000000000..ed594f6365 --- /dev/null +++ b/tools/tests/test_native_hook_readlink.py @@ -0,0 +1,106 @@ +import errno +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> + +static void show(const char *name, ssize_t len, const char *buf) { + printf("%s\t%zd\t%.*s\n", name, len, len > 0 ? (int)len : 0, buf); +} + +int main(int argc, char **argv) { + const char *link = argv[1]; + struct stat st; + if (lstat(link, &st) != 0) return 2; + char *exact = malloc((size_t)st.st_size + 1); + show("sized", readlink(link, exact, (size_t)st.st_size), exact); + char full[4096]; + show("full", readlink(link, full, sizeof(full)), full); + char small[4]; + show("small", readlink(link, small, sizeof(small)), small); + show("sized-at", readlinkat(AT_FDCWD, link, exact, (size_t)st.st_size), exact); + errno = 0; + ssize_t zero = readlink(link, full, 0); + int zero_errno = errno; + printf("zero\t%zd\t%d\n", zero, zero_errno); + errno = 0; + zero = readlinkat(AT_FDCWD, link, full, 0); + zero_errno = errno; + printf("zero-at\t%zd\t%d\n", zero, zero_errno); + return 0; +} +""" + + +class NativeHookReadlinkTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + (cls.root / "bin").mkdir(parents=True) + (cls.root / "etc/alternatives").mkdir(parents=True) + (cls.root / "bin/nano").write_text("") + os.symlink(cls.root / "bin/nano", cls.root / "etc/alternatives/editor") + os.symlink("/bin/nano", cls.root / "etc/alternatives/guest") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def read(self, link): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), link], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(0, out.returncode, out.stdout + out.stderr) + return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()} + + def test_a_buffer_sized_from_lstat_gets_the_guest_target(self): + result = self.read("/etc/alternatives/editor") + self.assertEqual(["9", "/bin/nano"], result["sized"]) + self.assertEqual(["9", "/bin/nano"], result["sized-at"]) + self.assertEqual(["9", "/bin/nano"], result["full"]) + + def test_a_short_buffer_gets_the_start_of_the_guest_target(self): + self.assertEqual(["4", "/bin"], self.read("/etc/alternatives/editor")["small"]) + + def test_a_guest_target_is_unchanged(self): + result = self.read("/etc/alternatives/guest") + self.assertEqual(["9", "/bin/nano"], result["sized"]) + self.assertEqual(["4", "/bin"], result["small"]) + + def test_a_zero_sized_buffer_is_rejected(self): + result = self.read("/etc/alternatives/editor") + self.assertEqual(["-1", str(errno.EINVAL)], result["zero"]) + self.assertEqual(["-1", str(errno.EINVAL)], result["zero-at"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_sigsys_mask.py b/tools/tests/test_native_hook_sigsys_mask.py new file mode 100644 index 0000000000..2d28c2954d --- /dev/null +++ b/tools/tests/test_native_hook_sigsys_mask.py @@ -0,0 +1,144 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#define _GNU_SOURCE +#include <pthread.h> +#include <signal.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include <sys/syscall.h> +#include <unistd.h> + +static uint64_t current(void) { + uint64_t mask = 0; + syscall(SYS_rt_sigprocmask, SIG_SETMASK, NULL, &mask, sizeof(mask)); + return mask; +} + +struct kact { void *handler; unsigned long flags; void *restorer; uint64_t mask; }; + +static void own(int sig, siginfo_t *info, void *ctx) { (void)sig; (void)info; (void)ctx; } + +static long raw_sigaction(int sig, const struct kact *act, struct kact *old) { + register long x8 __asm__("x8") = SYS_rt_sigaction; + register long x0 __asm__("x0") = sig; + register long x1 __asm__("x1") = (long)act; + register long x2 __asm__("x2") = (long)old; + register long x3 __asm__("x3") = 8; + __asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory"); + return x0; +} + +static void handlers(void) { + struct kact act = { (void *)own, SA_SIGINFO, NULL, 0 }, seen, kernel; + syscall(SYS_rt_sigaction, SIGSYS, &act, NULL, 8); + syscall(SYS_rt_sigaction, SIGSYS, NULL, &seen, 8); + raw_sigaction(SIGSYS, NULL, &kernel); + printf("sigaction\t%d\t%d\n", seen.handler == (void *)own, kernel.handler == (void *)own); + struct kact usr1 = { (void *)own, SA_SIGINFO, NULL, 0 }; + syscall(SYS_rt_sigaction, SIGUSR1, &usr1, NULL, 8); + raw_sigaction(SIGUSR1, NULL, &kernel); + printf("sigaction-usr1\t%d\n", kernel.handler == (void *)own); +} + +static void show(const char *how) { + uint64_t mask = current(); + printf("%s\t%d\t%d\n", how, !!(mask & (1ULL << (SIGSYS - 1))), !!(mask & (1ULL << (SIGUSR1 - 1)))); + uint64_t none = 0; + syscall(SYS_rt_sigprocmask, SIG_SETMASK, &none, NULL, sizeof(none)); +} + +int main(int argc, char **argv) { + uint64_t all = ~0ULL; + sigset_t set; + sigfillset(&set); + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "syscall-setmask") == 0) syscall(SYS_rt_sigprocmask, SIG_SETMASK, &all, NULL, sizeof(all)); + else if (strcmp(argv[i], "syscall-block") == 0) syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all)); + else if (strcmp(argv[i], "syscall-unblock") == 0) { + syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all)); + uint64_t usr1 = 1ULL << (SIGUSR1 - 1); + syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &usr1, NULL, sizeof(usr1)); + } + else if (strcmp(argv[i], "sigprocmask") == 0) sigprocmask(SIG_SETMASK, &set, NULL); + else if (strcmp(argv[i], "pthread_sigmask") == 0) pthread_sigmask(SIG_SETMASK, &set, NULL); + else if (strcmp(argv[i], "sigaction") == 0) { + handlers(); + continue; + } + show(argv[i]); + } + return 0; +} +""" + +WAYS = ("syscall-setmask", "syscall-block", "sigprocmask", "pthread_sigmask") + + +class NativeHookSigsysMaskTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + cls.root.mkdir() + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def masks(self, *ways, hook=True): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe), *ways], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: tuple(int(v) for v in line.split("\t")[1:]) for line in out.stdout.splitlines()} + + def test_blocking_every_signal_leaves_sigsys_open(self): + masks = self.masks(*WAYS) + for way in WAYS: + with self.subTest(way=way): + self.assertEqual((0, 1), masks[way]) + + def test_unblocking_is_unchanged(self): + self.assertEqual((0, 0), self.masks("syscall-unblock")["syscall-unblock"]) + + def test_a_sigsys_handler_set_through_syscall_keeps_the_hooks(self): + seen = self.masks("sigaction") + self.assertEqual((1, 0), seen["sigaction"]) + self.assertEqual((1,), seen["sigaction-usr1"]) + + def test_without_the_hook_a_sigsys_handler_reaches_the_kernel(self): + self.assertEqual((1, 1), self.masks("sigaction", hook=False)["sigaction"]) + + def test_without_the_hook_every_signal_is_blocked(self): + masks = self.masks(*WAYS, hook=False) + for way in WAYS: + with self.subTest(way=way): + self.assertEqual((1, 1), masks[way]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_netlink_preload.py b/tools/tests/test_netlink_preload.py index 7c47c971f9..9c52c909f3 100644 --- a/tools/tests/test_netlink_preload.py +++ b/tools/tests/test_netlink_preload.py @@ -12,7 +12,10 @@ PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" SHIM = r""" #define _GNU_SOURCE #include <dlfcn.h> +#include <errno.h> +#include <fcntl.h> #include <pthread.h> +#include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -92,6 +95,46 @@ FILE *fopen(const char *path, const char *mode) { return real(path, mode); } +static int denied(const char *path) { + const char *prefixes = getenv("NETLINK_TEST_DENIED"); + if (!prefixes || !path) return 0; + for (const char *prefix = prefixes; *prefix;) { + size_t length = strcspn(prefix, ":"); + if (length && !strncmp(path, prefix, length)) { + errno = EACCES; + return 1; + } + prefix += length + (prefix[length] == ':'); + } + return 0; +} + +int open(const char *path, int flags, ...) { + static int (*real)(const char *, int, ...); + if (!real) real = dlsym(RTLD_NEXT, "open"); + va_list ap; + va_start(ap, flags); + mode_t mode = va_arg(ap, mode_t); + va_end(ap); + return denied(path) ? -1 : real(path, flags, mode); +} + +int __open_2(const char *path, int flags) { + static int (*real)(const char *, int); + if (!real) real = dlsym(RTLD_NEXT, "__open_2"); + return denied(path) ? -1 : real(path, flags); +} + +int openat(int dirfd, const char *path, int flags, ...) { + static int (*real)(int, const char *, int, ...); + if (!real) real = dlsym(RTLD_NEXT, "openat"); + va_list ap; + va_start(ap, flags); + mode_t mode = va_arg(ap, mode_t); + va_end(ap); + return denied(path) ? -1 : real(dirfd, path, flags, mode); +} + int close_range(unsigned int first, unsigned int last, int flags) { return syscall(SYS_close_range, (long)first, (long)last, (long)flags, 0L, 0L, 0L); } @@ -137,6 +180,40 @@ static int route_socket(void) { return descriptor; } +static void proc_net_test(int denied, int sealed) { + static const char *const tables[] = {"/proc/net/tcp", "/proc/net/tcp6", "/proc/net/udp", "/proc/net/udp6"}; + char text[512], target[128], link[64]; + for (unsigned i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) { + int descriptor = i % 2 ? openat(AT_FDCWD, tables[i], O_RDONLY | O_CLOEXEC) : open(tables[i], O_RDONLY | O_CLOEXEC); + require(descriptor >= 0, "socket table opens"); + require(fcntl(descriptor, F_GETFD) & FD_CLOEXEC, "socket table keeps close-on-exec"); + snprintf(link, sizeof(link), "/proc/self/fd/%d", descriptor); + ssize_t length = readlink(link, target, sizeof(target) - 1); + require(length > 0, "socket table target"); + target[length] = 0; + require((strncmp(target, "/memfd:droiddeck-net", 20) == 0) == denied, "synthesized only when denied"); + if (denied) { + if (sealed) { + require(fcntl(descriptor, F_GET_SEALS) & F_SEAL_WRITE, "socket table is sealed"); + require(write(descriptor, "x", 1) < 0 && errno == EPERM, "sealed socket table rejects writes"); + } else { + require((fcntl(descriptor, F_GETFL) & O_ACCMODE) == O_RDONLY, "socket table is read-only"); + require(write(descriptor, "x", 1) < 0 && errno == EBADF, "socket table rejects writes"); + } + ssize_t total = read(descriptor, text, sizeof(text) - 1); + require(total > 0, "socket table read"); + text[total] = 0; + require(strstr(text, "local_address") && strchr(text, '\n') == text + total - 1, "header without sockets"); + } + close(descriptor); + } + if (denied) { + require(open("/proc/net/tcp", O_WRONLY) < 0 && errno == EACCES, "socket table writes stay denied"); + require(open("/proc/net/netstat", O_RDONLY) < 0 && errno == EACCES, "other tables stay denied"); + require(open("/proc/net/tcp", O_RDONLY | O_DIRECTORY) < 0 && errno == EACCES, "directory opens stay denied"); + } +} + static unsigned port_of(int descriptor) { struct sockaddr_nl address; socklen_t length = sizeof(address); @@ -609,6 +686,13 @@ static void batch_test(int oversized) { close(descriptor); } +static unsigned groups_of(int descriptor) { + struct sockaddr_nl address; + socklen_t length = sizeof(address); + require(getsockname(descriptor, (struct sockaddr *)&address, &length) == 0, "getsockname"); + return address.nl_groups; +} + static void inherited_test(int argc, char **argv) { require(argc == 6, "inherited arguments"); int descriptor = atoi(argv[2]), closed = atoi(argv[4]), datagram = atoi(argv[5]); @@ -616,6 +700,7 @@ static void inherited_test(int argc, char **argv) { require(fcntl(closed, F_GETFD) == -1 && errno == EBADF, "cloexec descriptor closed"); require(port_of(descriptor) == port && !(fcntl(descriptor, F_GETFD) & FD_CLOEXEC), "inherited bound port"); + require(groups_of(descriptor) == RTMGRP_LINK, "membership survives exec"); socket_info(descriptor, SOCK_RAW); socket_info(datagram, SOCK_DGRAM); require(fcntl(datagram, F_GETFL) & O_NONBLOCK, "inherited nonblocking flag"); @@ -640,6 +725,9 @@ static void exec_test(const char *program, int forked) { int enabled = 1; require(setsockopt(descriptor, SOL_NETLINK, NETLINK_CAP_ACK, &enabled, sizeof(enabled)) == 0, "inherited cap ack"); + int group = RTNLGRP_LINK; + require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0, + "inherited membership"); unsigned port = port_of(descriptor); int alias = fcntl(descriptor, F_DUPFD, 100); int closed = fcntl(descriptor, F_DUPFD_CLOEXEC, 200); @@ -718,8 +806,8 @@ static void ack_test(const char *mode) { static void options_test(void) { int descriptor = route_socket(); int group = RTNLGRP_LINK; - require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == -1 - && errno == EACCES, "membership denied"); + require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0, + "membership accepted"); require(setsockopt(descriptor, SOL_NETLINK, NETLINK_PKTINFO, &group, sizeof(group)) == -1 && errno == ENOPROTOOPT, "unsupported option"); require(setsockopt(descriptor, SOL_NETLINK, NETLINK_EXT_ACK, &group, sizeof(group)) == 0, "ext ack"); @@ -735,6 +823,44 @@ static void options_test(void) { close(descriptor); } +static void subscribe_test(void) { + unsigned wanted = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR; + int descriptor = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE); + struct sockaddr_nl address = {.nl_family = AF_NETLINK, .nl_groups = wanted}; + require(descriptor >= 0, "socket"); + require(bind(descriptor, (struct sockaddr *)&address, sizeof(address)) == 0, "bind with groups"); + require(groups_of(descriptor) == wanted, "bound groups"); + int group = RTNLGRP_IPV4_ROUTE; + require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == 0, + "add membership"); + require(groups_of(descriptor) == (wanted | RTMGRP_IPV4_ROUTE), "added group"); + group = RTNLGRP_LINK; + require(setsockopt(descriptor, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, &group, sizeof(group)) == 0, + "drop membership"); + require(groups_of(descriptor) == ((wanted & ~RTMGRP_LINK) | RTMGRP_IPV4_ROUTE), "dropped group"); + pid_t child = fork(); + require(child >= 0, "membership fork"); + if (child == 0) { + group = RTNLGRP_IPV4_ROUTE; + _exit(setsockopt(descriptor, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, &group, sizeof(group)) == 0 + && groups_of(descriptor) == (wanted & ~RTMGRP_LINK) ? 0 : 1); + } + int status; + require(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0, + "membership child"); + require(groups_of(descriptor) == (wanted & ~RTMGRP_LINK), "membership shared after fork"); + group = 0; + require(setsockopt(descriptor, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group)) == -1 + && errno == EINVAL, "group zero refused"); + struct timeval timeout = {.tv_usec = 30000}; + require(setsockopt(descriptor, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0, "receive timeout"); + unsigned char buffer[4096]; + require(recv(descriptor, buffer, sizeof(buffer), 0) == -1 + && (errno == EAGAIN || errno == EWOULDBLOCK), "no unsolicited events"); + usable(descriptor); + close(descriptor); +} + static void dump_test(void) { int descriptor = route_socket(); send_link(descriptor, 0, NLM_F_DUMP | NLM_F_ACK); @@ -1040,6 +1166,7 @@ int main(int argc, char **argv) { if (!strcmp(argv[1], "ack") || !strcmp(argv[1], "error") || !strcmp(argv[1], "capped")) ack_test(argv[1]); else if (!strcmp(argv[1], "options")) options_test(); + else if (!strcmp(argv[1], "subscribe")) subscribe_test(); else if (!strcmp(argv[1], "dump")) dump_test(); else if (!strcmp(argv[1], "send_timeout")) send_timeout_test(0); else if (!strcmp(argv[1], "nonblocking")) send_timeout_test(1); @@ -1082,6 +1209,7 @@ int main(int argc, char **argv) { } else if (!strcmp(argv[1], "range") || !strcmp(argv[1], "cloexec") || !strcmp(argv[1], "closefrom")) close_range_test(argv[1]); + else if (!strcmp(argv[1], "proc_net")) proc_net_test(argc > 2 && strcmp(argv[2], "allowed"), argc > 2 && !strcmp(argv[2], "sealed")); else if (!strcmp(argv[1], "route")) { require(argc >= 3, "route destination"); route_test(argv[2]); @@ -1129,10 +1257,12 @@ class NetlinkPreloadTest(unittest.TestCase): def tearDownClass(cls): cls.temp.cleanup() - def run_program(self, mode, *arguments, snapshot=None): + def run_program(self, mode, *arguments, snapshot=None, denied=None): env = dict(os.environ, LD_PRELOAD=f"{self.preload}:{self.shim}", NETLINK_TEST_SNAPSHOT=str(snapshot or self.snapshot), DD_SYSV_DIR=str(self.directory / "sysv")) + if denied: + env["NETLINK_TEST_DENIED"] = denied result = subprocess.run([str(self.program), mode, *arguments], env=env, capture_output=True, text=True, timeout=5) self.assertEqual(0, result.returncode, result.stdout + result.stderr) @@ -1207,9 +1337,12 @@ class NetlinkPreloadTest(unittest.TestCase): def test_cloexec_sockets_release_their_ports_after_exec(self): self.run_program("all_cloexec") - def test_subscription_is_denied_and_receive_timeout_is_applied(self): + def test_membership_is_accepted_and_receive_timeout_is_applied(self): self.run_program("options") + def test_change_listeners_subscribe_and_still_query(self): + self.run_program("subscribe") + def test_dump_keeps_multipart_completion(self): self.run_program("dump") @@ -1249,6 +1382,15 @@ class NetlinkPreloadTest(unittest.TestCase): with self.subTest(mode=mode): self.run_program(mode) + def test_denied_socket_tables_open_as_empty_tables(self): + self.run_program("proc_net", "denied", denied="/proc/net/") + + def test_denied_socket_tables_open_when_fd_reopen_is_denied(self): + self.run_program("proc_net", "sealed", denied="/proc/net/:/proc/self/fd/") + + def test_readable_socket_tables_stay_real(self): + self.run_program("proc_net") + def test_loopback_and_own_addresses_are_local_routes(self): for destination, source in (("127.0.0.2", "127.0.0.1"), ("::1", "::1"), ("192.168.1.10", "192.168.1.10"), ("2001:db8::10", "2001:db8::10")): diff --git a/tools/tests/test_output_refresh.py b/tools/tests/test_output_refresh.py index 8896d3e551..96817b2f4f 100644 --- a/tools/tests/test_output_refresh.py +++ b/tools/tests/test_output_refresh.py @@ -44,10 +44,11 @@ static struct surface surface = { .xdg_toplevel = 1, .toplevel_committed = 1 }; static int g_input_pipe[2] = {-1, -1}; static atomic_int g_output_refresh_mhz = 60000; static atomic_int g_output_refresh_pending; +static atomic_int g_panel_rates_pending; static int g_output_announced_refresh_mhz = 60000; static int g_output_w = 1920, g_output_h = 1080; static int flushes, resizes, pointers, ticks; -static int scale_changes, scale_mode, scale_alignment, renders; +static int scale_changes, scale_mode, scale_alignment, renders, rate_notifies; static void *g_display; #define WL_OUTPUT_MODE_CURRENT 1 #define WL_OUTPUT_MODE_PREFERRED 2 @@ -77,6 +78,7 @@ static void vk_present_set_scale_mode(int mode, int alignment) { scale_changes++; scale_mode = mode; scale_alignment = alignment; } static void schedule_render(void) { renders++; } +static void refresh_notify_rates(void) { rate_notifies++; } ''' CHECKS = r''' @@ -138,6 +140,11 @@ int main(void) { droiddeck_wayland_set_output_refresh_rate(90000); drain(); expect(6, 90000, 1); assert(scale_changes == 2 && scale_mode == 1 && scale_alignment == 3 && renders == 2); + atomic_store(&g_panel_rates_pending, 1); + drain(); + assert(rate_notifies == 1 && !atomic_load(&g_panel_rates_pending)); + drain(); + assert(rate_notifies == 1); close(g_input_pipe[0]); close(g_input_pipe[1]); puts("PASS"); } diff --git a/tools/tests/test_preload_wrapper_stack.py b/tools/tests/test_preload_wrapper_stack.py new file mode 100644 index 0000000000..409799921e --- /dev/null +++ b/tools/tests/test_preload_wrapper_stack.py @@ -0,0 +1,39 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" +LIMIT = 1024 +WRAPPERS = { + "descriptor.c": ("dd_descriptor_unlink", "dd_descriptor_rmdir", "dd_descriptor_remove", "dd_descriptor_rename"), + "tracer.c": ("dd_status_without_tracer",), +} + + +def frames(source, build): + obj = build / (source + ".o") + subprocess.run(["cc", "-c", "-fPIC", "-O2", "-Wall", "-fstack-usage", "-o", str(obj), str(PRELOAD / source)], + check=True) + sizes = {} + for line in obj.with_suffix(".su").read_text().splitlines(): + place, size, _ = line.split("\t") + sizes[place.rsplit(":", 1)[-1]] = int(size) + return sizes + + +@unittest.skipUnless(shutil.which("cc"), "needs a C compiler") +class PreloadWrapperStackTest(unittest.TestCase): + def test_wrappers_keep_path_buffers_off_their_frames(self): + with tempfile.TemporaryDirectory() as build: + for source, names in WRAPPERS.items(): + sizes = frames(source, Path(build)) + for name in names: + with self.subTest(function=name): + self.assertIn(name, sizes) + self.assertLess(sizes[name], LIMIT) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_render_on_commit.py b/tools/tests/test_render_on_commit.py index c0b8c436d5..66abb89d7f 100644 --- a/tools/tests/test_render_on_commit.py +++ b/tools/tests/test_render_on_commit.py @@ -26,7 +26,7 @@ static struct wl_event_source *g_render_idle, *g_fallback_timer; static int g_fallback_armed, g_dirty, g_hud_fresh, framegen; static void *g_hud_surface; static int64_t g_dirty_since_ns, g_last_vsync_ns, g_tick_vsync_ns, g_hud_last_ns, g_rendered_tick_ns; -static int g_tick_held; +static int g_tick_held, g_tick_spare, g_scene_queues; static int64_t g_hold_missed_ns; #define HOLD_RETRY_NS 1000000000LL static int64_t g_refresh_ns = 16666667; @@ -254,6 +254,15 @@ int main(void) { clock_ns += 200000000LL; schedule_render(); assert(idles_added == idles && g_fallback_armed == 1 && timers_armed == 1); + g_rendered_tick_ns = g_tick_vsync_ns; + g_tick_spare = 0; g_scene_queues = 1; + assert(!tick_takes_scene()); + g_tick_spare = 1; + assert(tick_takes_scene()); + g_scene_queues = 0; + assert(!tick_takes_scene()); + g_rendered_tick_ns = g_tick_vsync_ns - 1; + assert(tick_takes_scene()); puts("PASS"); return 0; } @@ -270,7 +279,7 @@ class RenderOnCommitTest(unittest.TestCase): render = extract_function(source, 'render_scene') self.assertIn('g_rendered_tick_ns = g_tick_vsync_ns;', render) self.assertIn('g_tick_held = 0;', render) - functions = ('scene_held_for_limit', 'commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', + functions = ('scene_held_for_limit', 'commit_renders_on', 'tick_takes_scene', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', 'bfi_blocked', 'bfi_update', 'bfi_tick', 'on_vsync') harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS with tempfile.TemporaryDirectory(prefix='droiddeck-render-on-commit-') as folder: diff --git a/tools/tests/test_runtime_inputs.py b/tools/tests/test_runtime_inputs.py index 954ea76f66..2bfbfb4dc3 100644 --- a/tools/tests/test_runtime_inputs.py +++ b/tools/tests/test_runtime_inputs.py @@ -1,6 +1,7 @@ import importlib.util import gzip import io +import json from pathlib import Path, PureWindowsPath import subprocess import tarfile @@ -122,6 +123,40 @@ class RuntimeInputsTest(unittest.TestCase): runtime.verify(self.root, stale_sources_ok=True) self.assertIn('tools/linuxfs/preload/test.c', stderr.getvalue()) + def helper(self, content): + source = self.root / 'tools/linuxfs/overlay/usr/local/bin/droiddeck-test-helper' + source.parent.mkdir(parents=True, exist_ok=True) + source.write_text(content) + staged = self.root / 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test-helper' + staged.parent.mkdir(parents=True, exist_ok=True) + staged.write_text(content) + return source, staged + + def test_an_edited_helper_script_needs_no_new_preparation(self): + self.helper('old helper') + runtime.record(self.root) + self.helper('new helper') + runtime.verify(self.root) + + def test_a_staged_helper_that_lags_its_source_is_rejected(self): + source, _ = self.helper('old helper') + runtime.record(self.root) + source.write_text('new helper') + with self.assertRaisesRegex(ValueError, 'not a current copy'): + runtime.verify(self.root, stale_sources_ok=True) + + def test_a_manifest_that_hashed_helper_scripts_still_verifies(self): + source, staged = self.helper('old helper') + runtime.record(self.root) + manifest = self.root / runtime.MANIFEST + data = json.loads(manifest.read_text()) + data['sources']['tools/linuxfs/overlay/usr/local/bin/droiddeck-test-helper'] = 'old' + data['outputs']['assets/linuxfs/usr/local/bin/droiddeck-test-helper'] = { + 'path': 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test-helper', 'sha256': 'old'} + manifest.write_text(json.dumps(data)) + self.helper('new helper') + runtime.verify(self.root) + def test_dev_loop_still_rejects_changed_outputs(self): runtime.record(self.root) (self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary') @@ -137,6 +172,19 @@ class RuntimeInputsTest(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'sources changed'): runtime.verify(self.root) + def test_cargo_output_beside_a_windows_helper_is_not_a_source(self): + crate = self.root / 'tools/epic-launcher' + (crate / 'src').mkdir(parents=True) + (crate / 'Cargo.toml').write_text('[package]\n') + (crate / 'src/lib.rs').write_text('old') + runtime.record(self.root) + (crate / 'target/debug').mkdir(parents=True) + (crate / 'target/debug/build.log').write_text('local cargo test') + runtime.verify(self.root) + (crate / 'src/lib.rs').write_text('new') + with self.assertRaisesRegex(ValueError, 'sources changed'): + runtime.verify(self.root) + def test_missing_quest_driver_cannot_be_attested(self): (self.root / 'app/build/prepared-assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst').unlink() with self.assertRaisesRegex(ValueError, 'quest1.tzst'): @@ -248,6 +296,21 @@ class RuntimeInputsTest(unittest.TestCase): runtime.check_apk(apk, self.root) runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root) + def test_an_apk_still_carrying_the_epic_parent_stand_in_is_rejected(self): + epic = self.root / 'app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic' + epic.mkdir(parents=True) + (epic / 'EpicGamesLauncher.exe').write_bytes(b'MZ parent') + self.packs() + name = 'assets/linuxfs/usr/local/lib/droiddeck-epic/EpicGamesLauncher.exe' + self.assertIn(name, runtime.outputs(self.root)) + apk = self.current_apk(self.root / 'bundled.apk', {name: b'MZ parent'}) + with self.assertRaisesRegex(ValueError, 'epic pack provides'): + runtime.check_apk(apk, self.root) + runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root) + self.pack('epic', {'EpicGamesLauncher.exe': b'MZ older parent'}) + with self.assertRaisesRegex(ValueError, 'epic is missing or has a stale'): + runtime.check_apk(self.current_apk(self.root / 'current.apk'), self.root) + def test_an_apk_still_carrying_the_powervr_runtime_is_rejected(self): apk = self.current_apk(self.root / 'bundled.apk', {'assets/hybris/runtime.tzst': b'runtime'}) with self.assertRaisesRegex(ValueError, 'powervr pack provides'): diff --git a/tools/tests/test_session_appimage.py b/tools/tests/test_session_appimage.py index 3fc5352427..295e73da3b 100644 --- a/tools/tests/test_session_appimage.py +++ b/tools/tests/test_session_appimage.py @@ -1,3 +1,4 @@ +import fcntl import os import re import shutil @@ -37,13 +38,28 @@ class AppImageExecTest(unittest.TestCase): path.chmod(0o755) return path - def launch(self): + def launch(self, **extra): script = self.dir / "exec" script.write_text(EXEC.read_text().replace(URUNTIME, str(self.uruntime)).replace(FEX, str(self.fex))) - env = {k: v for k, v in os.environ.items() if k not in ("TARGET_APPIMAGE", "APPIMAGE_EXTRACT_AND_RUN")} + env = {k: v for k, v in os.environ.items() if k not in ("TARGET_APPIMAGE", "APPIMAGE_EXTRACT_AND_RUN", "DDNATV_ROOT")} + env.update(extra) return subprocess.run(["bash", str(script), str(self.image), "--no-gui"], env=env, capture_output=True, text=True, timeout=30).stdout.splitlines() + def native(self, **extra): + return self.launch(DDNATV_ROOT=str(self.dir / "rootfs"), XDG_CACHE_HOME=str(self.cache), **extra) + + def unpacker(self, works=True, apprun=None): + self.cache = self.dir / "cache" + self.unpacks = self.dir / "unpacks" + apprun = apprun or "#!/bin/sh\nprintf '%s\\n' \"APPIMAGE=$APPIMAGE APPDIR=$APPDIR TARGET=${TARGET_APPIMAGE:-}\" apprun \"$@\"\n" + self.fex.write_text( + "#!/bin/sh\n[ \"$1\" = extract ] || exit 9\necho \"$2\" >> %s\n" % self.unpacks + + ("mkdir -p squashfs-root\ncat > squashfs-root/AppRun <<'EOF'\n%sEOF\nchmod +x squashfs-root/AppRun\n" % apprun if works else "exit 1\n")) + + def unpacked_dirs(self): + return [d for d in self.cache.glob("droiddeck-appimage/*") if d.is_dir()] + def test_an_arm64_image_runs_through_the_shipped_runtime(self): self.assertEqual(["TARGET=%s EXTRACT=1" % self.image, "uruntime", "--no-gui"], self.launch()) @@ -61,6 +77,116 @@ class AppImageExecTest(unittest.TestCase): self.fex.unlink() self.assertEqual(["TARGET=%s EXTRACT=1" % self.image, "uruntime", "--no-gui"], self.launch()) + def test_without_proot_an_arm64_image_is_unpacked_once_and_runs_from_its_apprun(self): + self.unpacker() + expected = ["== appimage: unpacking %s" % self.image] + ran = ["APPIMAGE=%s APPDIR=%s/squashfs-root TARGET=" % (self.image, "%s"), "apprun", "--no-gui"] + first = self.native() + self.assertEqual(expected, first[:1]) + [unpacked] = self.unpacked_dirs() + ran[0] = ran[0] % unpacked + self.assertEqual(ran, first[1:]) + self.assertEqual(ran, self.native()) + self.assertEqual([str(self.image)], self.unpacks.read_text().splitlines()) + + def test_without_proot_a_changed_image_is_unpacked_again(self): + self.unpacker() + self.native() + os.utime(self.image, (1, 1)) + self.assertEqual("apprun", self.native()[2]) + self.assertEqual(2, len(self.unpacks.read_text().splitlines())) + self.assertEqual(1, len(self.unpacked_dirs())) + + def test_without_proot_a_same_size_change_within_one_second_is_unpacked_again(self): + self.unpacker() + os.utime(self.image, ns=(1_000_000_100_000_000, 1_000_000_100_000_000)) + self.native() + os.utime(self.image, ns=(1_000_000_900_000_000, 1_000_000_900_000_000)) + self.assertEqual("apprun", self.native()[2]) + self.assertEqual(2, len(self.unpacks.read_text().splitlines())) + self.assertEqual(1, len(self.unpacked_dirs())) + + def hold(self, unpacked): + handle = open(unpacked / "source") + self.addCleanup(handle.close) + fcntl.flock(handle, fcntl.LOCK_SH) + return handle + + def test_without_proot_a_running_copy_survives_an_update_until_it_exits(self): + self.unpacker() + self.native() + [old] = self.unpacked_dirs() + running = self.hold(old) + os.utime(self.image, (1, 1)) + self.assertEqual("apprun", self.native()[2]) + self.assertTrue((old / "squashfs-root/AppRun").exists()) + [new] = [d for d in self.unpacked_dirs() if d != old] + running.close() + self.assertEqual("apprun", self.native()[1]) + self.assertEqual([new], self.unpacked_dirs()) + + def test_without_proot_a_running_copy_of_a_removed_image_is_kept(self): + self.unpacker() + self.native() + [old] = self.unpacked_dirs() + self.hold(old) + self.image.unlink() + self.image = self.dir / "dolphin.AppImage" + self.machine(183) + self.native() + self.assertTrue((old / "squashfs-root/AppRun").exists()) + self.assertEqual(2, len(self.unpacked_dirs())) + + def test_without_proot_the_running_application_holds_its_copy(self): + self.unpacker(apprun="#!/bin/sh\nflock -n -x \"$APPDIR/../source\" true && echo free || echo held\n") + self.assertEqual(["held"], self.native()[1:]) + + def test_without_proot_nothing_runs_when_the_cache_cannot_be_locked(self): + self.unpacker() + tools = self.dir / "tools" + tools.mkdir() + (tools / "flock").write_text("#!/bin/sh\nexit 1\n") + (tools / "flock").chmod(0o755) + self.assertEqual([], self.native(PATH="%s:%s" % (tools, os.environ["PATH"]))) + self.assertFalse(self.unpacks.exists()) + + def test_without_proot_the_unpacked_copy_of_a_removed_image_is_dropped(self): + self.unpacker() + self.native() + [old] = self.unpacked_dirs() + self.image.unlink() + self.image = self.dir / "dolphin.AppImage" + self.machine(183) + self.native() + self.assertFalse(old.exists()) + self.assertEqual(1, len(self.unpacked_dirs())) + + def test_without_proot_a_linked_cache_entry_and_its_target_survive(self): + self.unpacker() + outside = self.dir / "outside" + outside.mkdir() + (outside / "source").write_text("%s\n" % (self.dir / "gone.AppImage")) + (outside / "keep").write_text("data") + link = self.cache / "droiddeck-appimage" / "linked" + link.parent.mkdir(parents=True) + link.symlink_to(outside, target_is_directory=True) + self.assertEqual("apprun", self.native()[2]) + self.assertTrue(link.is_symlink()) + self.assertEqual("data", (outside / "keep").read_text()) + + def test_without_proot_an_image_that_cannot_be_unpacked_runs_nothing(self): + self.unpacker(works=False) + out = self.native() + self.assertNotIn("uruntime", out) + self.assertNotIn("apprun", out) + self.assertEqual([], self.unpacked_dirs()) + self.assertEqual([], list(self.cache.glob("droiddeck-appimage/.unpack.*"))) + + def test_without_proot_an_x86_image_still_starts_under_fex(self): + self.machine(62) + self.cache = self.dir / "cache" + self.assertEqual(["TARGET= EXTRACT=1", "fex", "run", "--mode", "on", "--", str(self.image), "--no-gui"], self.native()) + def test_the_session_starts_images_through_the_shared_launcher(self): script = ("set -u\n" "run_program() { printf '%%s\\n' \"$@\"; exit 0; }\n" diff --git a/tools/tests/test_session_assets.py b/tools/tests/test_session_assets.py index 5f7f8675d1..563ea1212e 100644 --- a/tools/tests/test_session_assets.py +++ b/tools/tests/test_session_assets.py @@ -50,3 +50,10 @@ class SessionAssetsTest(unittest.TestCase): mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/sub/login1"' self.assertEqual(['not extracted at session start: usr/local/bin/droiddeck-login1'], assets.check_extraction(self.overlay, mapping)) + + def test_stage_refreshes_a_changed_helper(self): + target = self.root / 'main' + assets.stage(target, self.overlay) + self.helper.write_bytes(b'new helper') + assets.stage(target, self.overlay) + self.assertEqual(b'new helper', (target / self.name).read_bytes()) diff --git a/tools/tests/test_steam_games.py b/tools/tests/test_steam_games.py index 08ffc90935..6218bf3be0 100644 --- a/tools/tests/test_steam_games.py +++ b/tools/tests/test_steam_games.py @@ -261,6 +261,27 @@ class ImportsTest(unittest.TestCase): imports.watch(str(self.steam), str(listing)) identify.assert_not_called() + def test_another_program_of_a_steam_install_stays_a_shortcut_beside_the_steam_app(self): + game, library = self.steam_install() + other = dict(game, name='Mod Launcher', exe=str(Path(game['folder']) / 'ModLauncher.exe'), + appid=0x87654322, route=False) + Path(other['exe']).write_bytes(b'mod') + imports.save_json(self.acct / 'config' / imports.STATE, + dict(account='123', owned={'42': True}, candidates={game['folder']: 42}, + sources={game['folder']: imports.source_stamp(game)})) + games, routes = imports.route(self.steam, self.acct, [game, other]) + self.assertEqual([other], games) + self.assertEqual({str(game['appid']): 42}, routes) + link = self.steam / 'steamapps/compatdata' / str(other['appid'] & 0xFFFFFFFF) + self.assertEqual(library / 'steamapps/compatdata/42', link.resolve()) + + def test_watch_never_looks_up_programs_that_are_not_the_steam_apps_own(self): + listing = self.root / 'games.json' + listing.write_text(json.dumps([dict(self.game, route=False)])) + with patch.object(imports, 'identify') as identify: + imports.watch(str(self.steam), str(listing)) + identify.assert_not_called() + def test_native_programs_stay_shortcuts_and_are_never_looked_up(self): self.snapshot() game = dict(self.game, native=True) @@ -692,6 +713,21 @@ class ImportsTest(unittest.TestCase): self.assert_not_imported_as(480) self.assertEqual(b'game', self.exe.read_bytes()) + def test_spacewar_import_is_released_for_a_program_that_is_not_the_steam_apps_own(self): + self.import_as(480) + other = dict(self.game, appid=0x87654322, route=False) + with patch('builtins.print'): + self.assertEqual(([other], {}), imports.route(self.steam, self.acct, [other])) + self.assert_not_imported_as(480) + self.assertEqual(b'game', self.exe.read_bytes()) + + def test_a_steam_import_stays_when_another_program_of_the_install_is_listed(self): + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + other = dict(self.game, appid=0x87654322, route=False) + imports.route(self.steam, self.acct, [other]) + self.assertTrue((self.steam / 'steamapps/appmanifest_42.acf').is_file()) + def test_import_follows_the_app_the_files_name_now(self): self.snapshot() imports.route(self.steam, self.acct, [self.game]) diff --git a/tools/tests/test_steam_install.py b/tools/tests/test_steam_install.py index f888b7ed13..b575a81d22 100644 --- a/tools/tests/test_steam_install.py +++ b/tools/tests/test_steam_install.py @@ -2,8 +2,10 @@ import hashlib import os from pathlib import Path import shutil +import signal import subprocess import tempfile +import time import unittest import zipfile @@ -12,6 +14,8 @@ SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/dr class SteamInstallTest(unittest.TestCase): + parallel = '1' + def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) @@ -47,19 +51,29 @@ if host_fail and host_fail in url: action = [] plan = os.environ.get('TEST_PLAN') if plan and os.path.exists(plan): - lines = open(plan).read().splitlines() - for n, line in enumerate(lines): - if line.split()[0] == name: - action = line.split()[1:] - del lines[n] - open(plan, 'w').write(''.join(l + '\\n' for l in lines)) - break + import fcntl + with open(plan + '.lock', 'w') as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + lines = open(plan).read().splitlines() + for n, line in enumerate(lines): + if line.split()[0] == name: + action = line.split()[1:] + del lines[n] + open(plan, 'w').write(''.join(l + '\\n' for l in lines)) + break if action[:1] == ['fail']: done(int(action[1]), '000') if action[:1] == ['http']: done(22, action[1]) +if action[:1] == ['killworker']: + import signal + os.kill(os.getppid(), signal.SIGKILL) + import time + time.sleep(6) if action[:1] == ['norange'] and offset: done(33) +import time +time.sleep(float(os.environ.get('TEST_SLEEP', '0'))) data = open(os.path.join(os.environ['TEST_CDN'], name), 'rb').read() end = int(action[1]) if action[:1] == ['cut'] else len(data) with open(out, 'ab' if offset else 'wb') as target: @@ -79,7 +93,8 @@ done(28 if end < len(data) else 0) self.env = dict(os.environ, HOME=str(self.home), XDG_DATA_HOME=str(self.data), PATH=str(self.bin) + os.pathsep + os.environ['PATH'], TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests), - TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0') + TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0', + DD_STEAM_PARALLEL=self.parallel) for channel in ('steamdeck_publicbeta', 'steamdeck_stable'): archive = self.cdn / (channel + '.zip') with zipfile.ZipFile(archive, 'w') as package: @@ -92,9 +107,13 @@ done(28 if end < len(data) else 0) f'\t\t"file" "{archive.name}"\n\t\t"sha2" "{digest}"\n' '\t}\n}\n') - def install(self, fail_host=None, *args, **extra): + def install(self, fail_host=None, *args, timeout=None, **extra): env = self.env if fail_host is None else dict(self.env, TEST_FAIL_HOST=fail_host) - return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True) + try: + return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True, + timeout=timeout) + except subprocess.TimeoutExpired: + self.fail(f'the installer did not finish within {timeout} s') def channel(self, **extra): result = self.install(None, '--channel', **extra) @@ -314,6 +333,130 @@ done(28 if end < len(data) else 0) def download(self): return self.steam / 'package/droiddeck-download' + def cache_manifest(self): + plain = b'plain-package' + packed = b'packed-package' + (self.cdn / 'a.zip.1111').write_bytes(plain) + (self.cdn / 'b.zip.vz.2222_14').write_bytes(packed) + (self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text( + '"linuxarm64"\n{\n\t"version" "123456"\n' + '\t"a_all"\n\t{\n' + f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(plain)}"\n\t\t"sha2" "{hashlib.sha256(plain).hexdigest()}"\n' + '\t}\n' + '\t"b_all"\n\t{\n' + '\t\t"file" "b.zip.9999"\n\t\t"size" "99"\n\t\t"sha2" "00"\n' + '\t\t"zipvz" "b.zip.vz.2222_14"\n' + f'\t\t"sha2vz" "{hashlib.sha256(packed).hexdigest()}"\n' + '\t}\n}\n') + + def test_the_cache_pass_keeps_every_package_under_the_names_steam_looks_for(self): + self.cache_manifest() + result = self.install(None, '--cache') + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes()) + self.assertEqual(b'packed-package', (package / 'b.zip.vz.2222_14').read_bytes()) + self.assertFalse((package / 'b.zip.9999').exists()) + self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text()) + + PREAPPLY = SCRIPT.with_name('droiddeck-steam-preapply') + + def real_cache_manifest(self): + import io + out = io.BytesIO() + with zipfile.ZipFile(out, 'w') as z: + z.writestr('steamrtarm64/steam', b'client') + data = out.getvalue() + (self.cdn / 'a.zip.1111').write_bytes(data) + (self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text( + '"linuxarm64"\n{\n\t"version" "123456"\n\t"a_all"\n\t{\n' + f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(data)}"\n\t\t"sha2" "{hashlib.sha256(data).hexdigest()}"\n' + '\t}\n}\n') + + def test_the_cache_pass_applies_the_update_so_steam_has_nothing_to_extract(self): + self.real_cache_manifest() + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY)) + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + name = 'steam_client_steamdeck_publicbeta_linuxarm64' + self.assertEqual(b'client', (self.steam / 'steamrtarm64/steam').read_bytes()) + self.assertTrue(os.access(self.steam / 'steamrtarm64/steam', os.X_OK)) + self.assertIn('steamrtarm64/steam,6;', (package / (name + '.installed')).read_text()) + self.assertEqual((self.cdn / name).read_text(), (package / (name + '.manifest')).read_text()) + self.assertFalse((package / 'a.zip.1111').exists()) + self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text()) + + def test_an_applied_update_finishes_the_install_without_fetching_the_plain_packages_again(self): + self.real_cache_manifest() + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY)) + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + self.assertEqual('123456\n', (package / 'droiddeck-installed').read_text()) + self.assertEqual('steamdeck_publicbeta\n', (package / 'beta').read_text()) + self.assertEqual((self.steam / 'linuxarm64').resolve(), (self.home / '.steam/sdkarm64').resolve()) + self.assertEqual(['steam_client_steamdeck_publicbeta_linuxarm64', 'a.zip.1111'], self.requested()) + again = self.install(None) + self.assertEqual(0, again.returncode, again.stderr) + self.assertEqual(2, len(self.requested())) + + def test_a_failed_apply_clears_the_cache_marker_and_the_old_record_so_it_is_retried(self): + self.real_cache_manifest() + package = self.steam / 'package' + package.mkdir(parents=True) + name = 'steam_client_steamdeck_publicbeta_linuxarm64' + (package / (name + '.installed')).write_text('old\n') + failing = self.root / 'failing-apply' + failing.write_text('import sys\nsys.exit(1)\n') + failing.chmod(0o755) + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(failing)) + self.assertEqual(0, result.returncode, result.stderr) + self.assertFalse((package / (name + '.installed')).exists()) + self.assertFalse((package / 'droiddeck-cached').exists()) + self.assertEqual((self.cdn / 'a.zip.1111').read_bytes(), (package / 'a.zip.1111').read_bytes()) + + def test_cancelling_the_cache_pass_stops_the_apply_helper(self): + self.real_cache_manifest() + pidfile = self.root / 'apply.pid' + slow = self.root / 'slow-apply' + slow.write_text(f'import os, time\nopen({str(pidfile)!r}, "w").write(str(os.getpid()))\ntime.sleep(30)\n') + slow.chmod(0o755) + process = subprocess.Popen(['bash', str(SCRIPT), '--cache'], env=dict(self.env, DD_STEAM_PREAPPLY=str(slow)), + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(100): + if pidfile.exists() and pidfile.read_text().strip(): + break + time.sleep(0.1) + helper = int(pidfile.read_text()) + process.terminate() + process.wait(timeout=10) + time.sleep(0.3) + with self.assertRaises(ProcessLookupError): + os.kill(helper, 0) + self.assertFalse((self.steam / 'package/droiddeck-cached').exists()) + + def test_a_cache_pass_that_cannot_apply_the_update_keeps_the_packages_for_steam(self): + self.cache_manifest() + result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY)) + self.assertEqual(0, result.returncode, result.stderr) + package = self.steam / 'package' + self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes()) + self.assertFalse(list(package.glob('*.installed'))) + self.assertFalse(list(package.glob('*.manifest'))) + + def test_the_cache_pass_is_not_repeated_for_the_same_client_version(self): + self.cache_manifest() + self.assertEqual(0, self.install(None, '--cache').returncode) + requests = len(self.requests.read_text().splitlines()) + self.assertEqual(0, self.install(None, '--cache').returncode) + self.assertEqual(requests + 1, len(self.requests.read_text().splitlines())) + + def test_a_cached_package_is_not_fetched_again(self): + self.cache_manifest() + (self.steam / 'package').mkdir(parents=True) + (self.steam / 'package/a.zip.1111').write_bytes(b'plain-package') + self.assertEqual(0, self.install(None, '--cache').returncode) + self.assertNotIn('a.zip.1111', self.requests.read_text()) + def test_progress_is_counted_in_megabytes_across_parts(self): self.two_parts() result = self.install() @@ -415,5 +558,212 @@ done(28 if end < len(data) else 0) self.assertFalse(self.download.exists()) +class SteamInstallParallelTest(SteamInstallTest): + """The same behaviour with several connections at once.""" + parallel = '4' + test_progress_is_counted_in_megabytes_across_parts = None + + def many_parts(self, count=10): + return self.publish(**{f'p{i}_all': 300_000 for i in range(count)}) + + def test_many_parts_arrive_and_unpack_together(self): + self.many_parts() + result = self.install() + self.assertEqual(0, result.returncode, result.stderr) + for i in range(10): + self.assertTrue((self.steam / f'parts/p{i}_all').is_file(), i) + self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text()) + self.assertFalse(self.download.exists()) + + def test_every_part_is_requested_once_when_several_arrive_together(self): + files = self.many_parts() + self.assertEqual(0, self.install().returncode) + requested = self.requested() + for name in files.values(): + self.assertEqual(1, requested.count(name), name) + + def test_one_part_that_no_cdn_has_fails_the_install_and_leaves_no_ready_marker(self): + files = self.many_parts() + missing = files['p4_all'] + self.plan_for(missing, 'http 404', 'http 404', 'http 404') + result = self.install() + self.assertNotEqual(0, result.returncode) + self.assertFalse((self.steam / 'package/droiddeck-installed').exists()) + self.assertIn('failed on every CDN', result.stderr) + + def test_a_retry_after_a_failure_finishes_what_is_left(self): + files = self.many_parts() + self.plan_for(files['p4_all'], 'http 404', 'http 404', 'http 404') + self.assertNotEqual(0, self.install().returncode) + self.assertEqual(0, self.install().returncode) + self.assertTrue((self.steam / 'parts/p4_all').is_file()) + self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text()) + + def test_progress_is_reported_while_several_parts_arrive(self): + self.many_parts() + result = self.install(TEST_SLEEP='1.2', **{}) + self.assertEqual(0, result.returncode, result.stderr) + lines = [line for line in result.stdout.splitlines() if 'downloading Steam:' in line and ' of ' in line] + self.assertGreaterEqual(len(lines), 2, result.stdout) + self.assertIn(' MB', lines[-1]) + + def test_packages_are_unpacked_one_at_a_time(self): + source = SCRIPT.read_text() + region = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')] + self.assertNotIn('unzip -qo', region) + self.assertIn('unzip_alone', region) + self.assertIn('"$flock_command" 9', source) + + def unzip_alone_script(self): + source = SCRIPT.read_text() + start = source.index('unzip_alone() {') + function = source[start:source.index('\n}\n', start) + 3] + return 'state=$1\nsteam_root=$2\nflock_command=flock\n' + function + '\nunzip_alone "$3"\n' + + def unzip_alone_archive(self, name='one.zip', entry='steamrtarm64/steam'): + archive = self.root / name + with zipfile.ZipFile(archive, 'w') as package: + package.writestr(entry, 'client') + self.steam.mkdir(parents=True, exist_ok=True) + (self.root / 'state').mkdir(exist_ok=True) + return archive + + def run_unzip_alone(self, archive, timeout, env=None): + arguments = ['bash', '-c', self.unzip_alone_script(), 'bash', str(self.root / 'state'), str(self.steam), str(archive)] + try: + return subprocess.run(arguments, text=True, capture_output=True, timeout=timeout, env=env) + except subprocess.TimeoutExpired: + return None + + def hold_the_lock(self): + """Starts a process that holds the unzip lock and returns once it says it has it.""" + ready = self.root / 'holder-ready' + holder = subprocess.Popen( + ['flock', str(self.root / 'state/unzip.lock'), 'sh', '-c', f'touch {ready}; sleep 60'], start_new_session=True) + self.addCleanup(lambda: os.killpg(holder.pid, signal.SIGKILL) if holder.poll() is None else None) + deadline = time.monotonic() + 10 + while not ready.exists(): + self.assertLess(time.monotonic(), deadline, 'the holder never took the lock') + time.sleep(0.05) + return holder + + @unittest.skipUnless(shutil.which('flock'), 'needs flock') + def test_a_package_waits_for_a_worker_that_is_unpacking(self): + archive = self.unzip_alone_archive() + self.hold_the_lock() + self.assertIsNone(self.run_unzip_alone(archive, timeout=4), 'unzip_alone did not wait for the holder') + self.assertFalse((self.steam / 'steamrtarm64/steam').exists()) + + @unittest.skipUnless(shutil.which('flock'), 'needs flock') + def test_a_worker_killed_while_unpacking_hands_the_lock_on(self): + archive = self.unzip_alone_archive() + holder = self.hold_the_lock() + os.killpg(holder.pid, signal.SIGKILL) + holder.wait() + result = self.run_unzip_alone(archive, timeout=20) + self.assertIsNotNone(result, 'the lock of a killed worker was never handed on') + self.assertEqual(0, result.returncode, result.stderr) + self.assertTrue((self.steam / 'steamrtarm64/steam').is_file()) + + @unittest.skipUnless(shutil.which('flock'), 'needs flock') + def test_several_workers_never_unpack_at_the_same_moment(self): + log = self.root / 'unzip.log' + fake = self.bin / 'unzip' + fake.write_text('''#!/usr/bin/env python3 +import os, sys, time +log = os.environ['TEST_UNZIP_LOG'] +with open(log, 'a') as out: + out.write(f'start {os.getpid()}\\n') +time.sleep(0.3) +with open(log, 'a') as out: + out.write(f'end {os.getpid()}\\n') +''') + fake.chmod(0o755) + archive = self.unzip_alone_archive() + env = dict(self.env, TEST_UNZIP_LOG=str(log)) + arguments = ['bash', '-c', self.unzip_alone_script(), 'bash', str(self.root / 'state'), str(self.steam), str(archive)] + workers = [subprocess.Popen(arguments, env=env) for _ in range(8)] + for worker in workers: + self.assertEqual(0, worker.wait(timeout=60)) + lines = log.read_text().split() + events = lines[0::2] + self.assertEqual(['start', 'end'] * 8, events, 'two workers unpacked at the same time') + + def test_without_flock_the_downloads_go_one_at_a_time(self): + self.two_parts() + result = self.install(DD_STEAM_FLOCK='flock-that-is-not-installed') + self.assertEqual(0, result.returncode, result.stderr) + # Only the sequential path counts parts as (1/2) and (2/2). + self.assertIn('downloading Steam: a_all (1/2), 0 of 2 MB\n', result.stdout) + self.assertIn('downloading Steam: client_linuxarm64_linuxarm64 (2/2), 1 of 2 MB\n', result.stdout) + + def test_workers_do_not_claim_packages_with_mkdir(self): + source = SCRIPT.read_text() + region = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')] + self.assertNotIn('mkdir "$state/claim', region) + self.assertIn('claim_next', region) + + @unittest.skipUnless(shutil.which('flock'), 'needs flock') + def test_racing_workers_never_get_the_same_package(self): + source = SCRIPT.read_text() + start = source.index('claim_next() {') + function = source[start:source.index('\n}\n', start) + 3] + state = self.root / 'claims' + state.mkdir() + (state / 'next').write_text('1\n') + script = 'state=$1\ncount=$2\nflock_command=flock\n' + function + 'while :; do n=$(claim_next); [ "$n" -gt 0 ] || exit 0; echo "$n"; done\n' + workers = [subprocess.Popen(['bash', '-c', script, 'bash', str(state), '300'], stdout=subprocess.PIPE, text=True) + for _ in range(8)] + claimed = [] + for worker in workers: + out, _ = worker.communicate(timeout=120) + self.assertEqual(0, worker.returncode) + claimed += [int(n) for n in out.split()] + self.assertEqual(sorted(claimed), list(range(1, 301)), 'a package was claimed twice or never') + + @unittest.skipUnless(shutil.which('flock'), 'needs flock') + def test_a_counter_that_cannot_be_used_fails_the_claim(self): + source = SCRIPT.read_text() + start = source.index('claim_next() {') + function = source[start:source.index('\n}\n', start) + 3] + for broken in ('directory', 'empty', 'text'): + state = self.root / f'claims-{broken}' + state.mkdir() + if broken == 'directory': + (state / 'next').mkdir() + else: + (state / 'next').write_text('' if broken == 'empty' else 'abc\n') + script = 'state=$1\ncount=5\nflock_command=flock\n' + function + 'n=$(claim_next) && echo "claimed $n" || echo failed\n' + result = subprocess.run(['bash', '-c', script, 'bash', str(state)], text=True, capture_output=True, timeout=30) + self.assertEqual('failed', result.stdout.strip(), f'{broken}: {result.stdout!r} {result.stderr!r}') + + def test_a_claim_that_fails_fails_the_install_instead_of_leaving_packages_unclaimed(self): + self.many_parts() + # false is found like a flock would be, but it never takes the lock, so every claim fails. + result = self.install(DD_STEAM_FLOCK='false', timeout=60) + self.assertNotEqual(0, result.returncode, result.stdout) + self.assertFalse((self.steam / 'package/droiddeck-installed').exists()) + + def test_the_parallel_workers_use_no_process_substitution(self): + source = SCRIPT.read_text() + region = source[source.index('fetch_one() {'):source.index('fetch_manifest() {')] + self.assertNotIn('<(', region) + reporter = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')] + self.assertNotIn('kill -0', reporter) + + def test_a_worker_killed_from_outside_fails_the_install_instead_of_hanging_it(self): + files = self.many_parts() + self.plan_for(files['p3_all'], 'killworker') + result = self.install(timeout=40, DD_STEAM_STALL='3') + self.assertNotEqual(0, result.returncode) + self.assertFalse((self.steam / 'package/droiddeck-installed').exists()) + + def test_the_cache_pass_with_several_connections_keeps_every_package(self): + self.cache_manifest() + result = self.install(None, '--cache') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('123456\n', (self.steam / 'package/droiddeck-cached').read_text()) + + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/test_steam_preapply.py b/tools/tests/test_steam_preapply.py new file mode 100644 index 0000000000..9300b1bcce --- /dev/null +++ b/tools/tests/test_steam_preapply.py @@ -0,0 +1,157 @@ +import hashlib +import io +import lzma +from pathlib import Path +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import zipfile +import zlib + + +SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply' +NAME = 'steam_client_steamdeck_publicbeta_linuxarm64' + + +def zip_bytes(entries): + out = io.BytesIO() + with zipfile.ZipFile(out, 'w') as z: + for name, data, mode, stamp in entries: + info = zipfile.ZipInfo(name, stamp) + info.external_attr = mode << 16 + z.writestr(info, data) + return out.getvalue() + + +def vzip(data): + packer = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[ + {'id': lzma.FILTER_LZMA1, 'dict_size': 1 << 20, 'lc': 3, 'lp': 0, 'pb': 2}]) + body = packer.compress(data) + packer.flush() + props = (2 * 5 + 0) * 9 + 3 + return (b'VZa' + b'\0\0\0\0' + bytes([props]) + struct.pack('<I', 1 << 20) + body + + struct.pack('<II', zlib.crc32(data) & 0xFFFFFFFF, len(data)) + b'zv') + + +class SteamPreapplyTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + root = Path(self.temp.name) + self.packages = root / 'packages' + self.packages.mkdir() + self.steam = root / 'Steam' + self.manifest = root / 'manifest' + + def write_manifest(self, blocks): + text = '"linuxarm64"\n{\n\t"version"\t\t"42"\n' + for block, attrs in blocks.items(): + text += f'\t"{block}"\n\t{{\n' + for key, value in attrs.items(): + text += f'\t\t"{key}"\t\t"{value}"\n' + text += '\t}\n' + self.manifest.write_text(text + '}\n') + + def run_script(self): + return subprocess.run([sys.executable, '-I', str(SCRIPT), str(self.packages), str(self.steam), + str(self.manifest), NAME], text=True, capture_output=True) + + def installed(self): + return (self.steam / 'package' / (NAME + '.installed')).read_text().split('\n') + + def prepare(self): + stamp = (2025, 5, 17, 10, 30, 0) + plain = zip_bytes([ + ('bin/', b'', 0o40755, stamp), + ('bin/Tool', b'tool', 0o100755, stamp), + ('bin\\Backslash.txt', b'bs', 0o100644, stamp), + ('lib/libx.so.1', b'libx', 0o100644, stamp), + ('lib/libx.so', b'libx.so.1', 0o120777, stamp), + ]) + packed = zip_bytes([('data/z_file', b'zed', 0o100644, stamp), ('data/A_file', b'aaa', 0o100644, stamp)]) + (self.packages / 'a.zip.1111').write_bytes(plain) + (self.packages / 'b.zip.vz.2222_14').write_bytes(vzip(packed)) + self.write_manifest({ + 'a_all': {'file': 'a.zip.1111', 'size': len(plain), 'sha2': '00'}, + 'b_all': {'file': 'b.zip.9999', 'size': 99, 'sha2': '00', 'zipvz': 'b.zip.vz.2222_14', 'sha2vz': '00'}, + }) + + def test_extracts_every_package_including_packed_ones(self): + self.prepare() + result = self.run_script() + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual(b'tool', (self.steam / 'bin/Tool').read_bytes()) + self.assertTrue(os.access(self.steam / 'bin/Tool', os.X_OK)) + self.assertEqual(b'bs', (self.steam / 'bin/Backslash.txt').read_bytes()) + self.assertEqual('libx.so.1', os.readlink(self.steam / 'lib/libx.so')) + self.assertEqual(b'zed', (self.steam / 'data/z_file').read_bytes()) + + def test_records_what_steams_updater_records(self): + self.prepare() + self.assertEqual(0, self.run_script().returncode) + stamp = 1747477800 + 28800 + crc = lambda data: zlib.crc32(data) & 0xFFFFFFFF + lines = self.installed() + self.assertEqual([ + f'bin/,-1;{stamp};0', + f'bin/Backslash.txt,2;{stamp};{crc(b"bs")}', + f'bin/Tool,4;{stamp};{crc(b"tool")}', + f'data/A_file,3;{stamp};{crc(b"aaa")}', + f'data/z_file,3;{stamp};{crc(b"zed")}', + f'lib/libx.so,-2;{stamp};{crc(b"libx.so.1")}', + f'lib/libx.so.1,4;{stamp};{crc(b"libx")}', + 'OSVER=-184', + 'VERSION=3', + ], lines[:-2]) + body = ''.join(line + '\n' for line in lines[:-2]) + self.assertEqual('SHA1=' + hashlib.sha1(body.encode()).hexdigest().upper(), lines[-2]) + self.assertEqual('', lines[-1]) + + def test_a_missing_package_leaves_no_record_so_steam_extracts_for_itself(self): + self.prepare() + (self.packages / 'b.zip.vz.2222_14').unlink() + result = self.run_script() + self.assertNotEqual(0, result.returncode) + self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists()) + + def test_a_corrupt_package_leaves_no_record(self): + self.prepare() + packed = (self.packages / 'b.zip.vz.2222_14').read_bytes() + (self.packages / 'b.zip.vz.2222_14').write_bytes(packed[:-12] + b'\0' * 12) + self.assertNotEqual(0, self.run_script().returncode) + self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists()) + + + def package_with(self, entries): + (self.packages / 'a.zip.1111').write_bytes(zip_bytes(entries)) + self.write_manifest({'a_all': {'file': 'a.zip.1111', 'size': 1, 'sha2': '00'}}) + + def test_a_path_that_leaves_the_steam_root_is_refused(self): + stamp = (2025, 5, 17, 10, 30, 0) + for name in ('../outside', '/abs/outside', 'a/../../outside'): + with self.subTest(name=name): + self.package_with([(name, b'x', 0o100644, stamp)]) + self.assertNotEqual(0, self.run_script().returncode) + self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists()) + self.assertFalse((Path(self.temp.name) / 'outside').exists()) + + def test_a_file_cannot_be_written_through_a_symlink_that_leaves_the_steam_root(self): + stamp = (2025, 5, 17, 10, 30, 0) + target = Path(self.temp.name) / 'elsewhere' + target.mkdir() + self.package_with([('link', str(target).encode(), 0o120777, stamp), ('link/file', b'x', 0o100644, stamp)]) + self.assertNotEqual(0, self.run_script().returncode) + self.assertFalse((target / 'file').exists()) + + def test_a_symlink_inside_the_steam_root_still_carries_files(self): + stamp = (2025, 5, 17, 10, 30, 0) + self.package_with([('real/', b'', 0o40755, stamp), ('alias', b'real', 0o120777, stamp), + ('alias/file', b'x', 0o100644, stamp)]) + self.assertEqual(0, self.run_script().returncode) + self.assertEqual(b'x', (self.steam / 'real/file').read_bytes()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_steam_presentation.py b/tools/tests/test_steam_presentation.py index 801c1d4688..48508786db 100644 --- a/tools/tests/test_steam_presentation.py +++ b/tools/tests/test_steam_presentation.py @@ -12,7 +12,7 @@ SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/d class SteamPresentationTest(unittest.TestCase): def launch(self, enabled=None, inherited=None): source = SESSION.read_text() - begin = source.index(" dd_steam_path=$PATH") + begin = source.index(" dd_steam_path=") end = source.index("\n decky_loader=", begin) command = source.index(' PATH="$dd_steam_path"') command_end = source.index("\n rc=$?", command) @@ -41,7 +41,7 @@ class SteamPresentationTest(unittest.TestCase): env=env, capture_output=True, text=True, timeout=5) self.assertEqual(result.returncode, 0, result.stderr) launch = json.loads(result.stdout.splitlines()[-1]) - self.assertEqual(enabled == "1", launch["path"].startswith("/usr/local/libexec/droiddeck-steam:")) + self.assertEqual(launch["path"], "/usr/local/libexec/droiddeck-steam:" + env["PATH"]) self.assertEqual(launch["helper"], str(Path(tmp) / "steamrtarm64/steamwebhelper")) return launch diff --git a/tools/tests/test_steam_shortcuts.py b/tools/tests/test_steam_shortcuts.py index a927d4db07..74396e3221 100644 --- a/tools/tests/test_steam_shortcuts.py +++ b/tools/tests/test_steam_shortcuts.py @@ -1,6 +1,7 @@ import importlib.machinery import importlib.util import json +import os from pathlib import Path import subprocess import tempfile @@ -20,7 +21,15 @@ def load(name): shortcuts = load('droiddeck-steam-shortcuts') APPID = 0x87654321 -GUEST = '/root/Games/PC/Example' +GUEST = os.path.join(tempfile.mkdtemp(prefix='droiddeck-shortcuts-'), 'Games/PC/Example') + + +def installed(*paths): + """Creates the files the writer checks, so a Steam edit to one of them is kept.""" + for path in paths: + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).touch() + return paths[0] class ShortcutsTest(unittest.TestCase): @@ -34,7 +43,7 @@ class ShortcutsTest(unittest.TestCase): self.listing = self.root / 'added-games.json' def game(self, exe='Example.exe', seen=0, appid=APPID, name='Example'): - path = GUEST + '/' + exe + path = installed(GUEST + '/' + exe) return dict(name=name, exe=path, folder=GUEST, dir=path.rsplit('/', 1)[0], appid=appid, seen=seen) def run_writer(self, *games): @@ -54,10 +63,32 @@ class ShortcutsTest(unittest.TestCase): if value['appid'] & 0xFFFFFFFF == appid: value.update(fields) path.write_bytes(shortcuts.write({'shortcuts': data})) + if fields.get('Exe'): + target = Path(shortcuts.unquoted(fields['Exe'])) + target.parent.mkdir(parents=True, exist_ok=True) + target.touch() def record(self): return json.loads((self.config / shortcuts.RECORD).read_text()) + def patched(self, **constants): + for name, value in constants.items(): + old = getattr(shortcuts, name) + setattr(shortcuts, name, value) + self.addCleanup(setattr, shortcuts, name, old) + + def merge_target(self, exe, **edits): + """Runs merge against a Steam-edited target, with the app's exe recorded as the base.""" + fresh = shortcuts.shortcut(self.game()) + current = dict(fresh, Exe=exe, **edits) + state = { + 'app': {field: fresh[field] for field in shortcuts.FIELDS}, + 'steam': {field: current.get(field, '') for field in ('AppName', 'Exe', 'StartDir', 'LaunchOptions')}, + 'rev': 1, + } + entry, _ = shortcuts.merge(fresh, current, state, 0) + return entry + def test_settings_changed_in_steam_survive_its_restart(self): self.run_writer(self.game()) edits = dict(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s"' % GUEST, LaunchOptions='DXVK_HUD=1 %command%', @@ -82,6 +113,68 @@ class ShortcutsTest(unittest.TestCase): self.run_writer(self.game()) self.assertEqual(1, self.record()['games'][str(APPID)]['rev']) + def test_a_steam_target_whose_file_is_gone_goes_back_to_the_apps(self): + self.run_writer(self.game()) + self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s/data"' % GUEST) + Path(shortcuts.unquoted('"%s/bin/Other.exe"' % GUEST)).unlink() + entry = self.run_writer(self.game())[APPID] + self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe']) + self.assertEqual('"%s"' % GUEST, entry['StartDir']) + self.assertEqual('"%s/Example.exe"' % GUEST, self.record()['games'][str(APPID)]['steam']['Exe']) + + def test_a_steam_target_whose_internal_folder_is_gone_goes_back_to_the_apps(self): + games = self.root / 'games' + (games / 'Stores').mkdir(parents=True) + self.patched(INTERNAL_ROOTS=(str(games / 'Stores'),)) + entry = self.merge_target('"%s/old-version/Other.exe"' % (games / 'Stores'), StartDir='"%s/data"' % GUEST) + self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe']) + self.assertEqual('"%s"' % GUEST, entry['StartDir']) + + def test_a_steam_target_on_an_unmounted_card_is_kept(self): + card = self.root / 'card' + card.mkdir() + self.patched(REMOVABLE_ROOTS=(str(card),)) + entry = self.merge_target('"%s/steamapps/common/Other.exe"' % card) + self.assertEqual('"%s/steamapps/common/Other.exe"' % card, entry['Exe']) + self.assertEqual('"%s"' % GUEST, entry['StartDir']) + + def test_a_steam_target_under_a_bare_card_mountpoint_is_kept(self): + card = self.root / 'card' + card.mkdir() + self.patched(REMOVABLE_ROOTS=(str(card),)) + entry = self.merge_target('"%s/Other.exe"' % card, StartDir='"%s/data"' % GUEST) + self.assertEqual('"%s/Other.exe"' % card, entry['Exe']) + self.assertEqual('"%s/data"' % GUEST, entry['StartDir']) + + def test_a_steam_target_is_classified_by_its_resolved_path(self): + games = self.root / 'games' + stores = games / 'Stores' + stores.mkdir(parents=True) + card = self.root / 'card' + card.mkdir() + self.patched(INTERNAL_ROOTS=(str(stores),), REMOVABLE_ROOTS=(str(card),)) + target = '"%s/../../card/Other.exe"' % stores + entry = self.merge_target(target, StartDir='"%s/data"' % GUEST) + self.assertEqual(target, entry['Exe']) + self.assertEqual('"%s/data"' % GUEST, entry['StartDir']) + + def test_a_steam_target_under_a_bare_store_mountpoint_is_kept(self): + stores = self.root / 'stores' + mount = stores / 'abcd1234' + mount.mkdir(parents=True) + self.patched(REMOVABLE_FAMILIES=(str(stores),)) + entry = self.merge_target('"%s/Other.exe"' % mount, StartDir='"%s/data"' % GUEST) + self.assertEqual('"%s/Other.exe"' % mount, entry['Exe']) + self.assertEqual('"%s/data"' % GUEST, entry['StartDir']) + + def test_a_steam_target_under_a_mounted_card_goes_back_to_the_apps(self): + card = self.root / 'card' + (card / 'steamapps').mkdir(parents=True) + self.patched(REMOVABLE_ROOTS=(str(card),)) + entry = self.merge_target('"%s/Other.exe"' % card, StartDir='"%s/data"' % GUEST) + self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe']) + self.assertEqual('"%s"' % GUEST, entry['StartDir']) + def test_the_app_taking_steams_target_keeps_steams_start_in(self): self.run_writer(self.game()) self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s/data"' % GUEST) diff --git a/tools/tests/test_steam_ui_scale.py b/tools/tests/test_steam_ui_scale.py index 5440dcd497..9a65305e2b 100644 --- a/tools/tests/test_steam_ui_scale.py +++ b/tools/tests/test_steam_ui_scale.py @@ -16,6 +16,8 @@ initialize_native_resolution = MODULE['initialize_native_resolution'] NATIVE_RESOLUTION = MODULE['NATIVE_RESOLUTION'] seed_no_screensaver_in_game = MODULE['seed_no_screensaver_in_game'] initialize_screensaver = MODULE['initialize_screensaver'] +seed_bouncing_logo = MODULE['seed_bouncing_logo'] +initialize_screensaver_choice = MODULE['initialize_screensaver_choice'] class SteamUiScaleTest(unittest.TestCase): @@ -182,6 +184,16 @@ class SteamScreensaverTest(unittest.TestCase): self.assertEqual('0', screensaver.get('WhileInGame')) self.assertIn('\t\t\t"WhileInGame"\t\t"0"\n\t\t}\n', updated) + def test_fresh_client_gets_the_bouncing_logo(self): + self.assertTrue(initialize_screensaver_choice(self.root)) + screensaver = parse(self.config.read_text()).get('InstallConfigStore').get('Customization').get('Screensaver') + self.assertEqual('steam-bouncinglogo', screensaver.get('CurrentScreensaver')) + self.assertTrue(self.config.with_name('droiddeck-screensaver-choice-initialized').exists()) + + def test_a_screensaver_already_picked_is_kept(self): + text = '"InstallConfigStore" { "Customization" { "Screensaver" { "CurrentScreensaver" "other" } } }' + self.assertEqual((text, False), seed_bouncing_logo(text)) + def test_users_choice_is_kept(self): text = '"InstallConfigStore" { "Customization" { "Screensaver" { "WhileInGame" "1" } } }' self.assertEqual((text, False), seed_no_screensaver_in_game(text)) diff --git a/tools/tests/test_steam_x64_thunk_appconfigs.py b/tools/tests/test_steam_x64_thunk_appconfigs.py new file mode 100644 index 0000000000..a949a5d753 --- /dev/null +++ b/tools/tests/test_steam_x64_thunk_appconfigs.py @@ -0,0 +1,89 @@ +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-x64' +SOURCE = SCRIPT.read_text() +FUNCTION = re.search(r'^x64_thunk_appconfigs\(\) \{\n.*?^\}\n', SOURCE, re.M | re.S).group() +CFG = '{"ThunksDB": {"GL": 1, "Vulkan": 1}}' + + +class SteamX64ThunkAppConfigsTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + root = Path(self.temp.name) + self.src = root / 'global' + self.dst = root / 'local' + self.src.mkdir() + + def write_global(self, name, data): + (self.src / name).write_text(json.dumps(data)) + + def run_fn(self, on): + shell = FUNCTION + 'x64_thunk_appconfigs "$SRC" "$DST" "$CFG" "$ON"\n' + env = dict(os.environ, SRC=str(self.src), DST=str(self.dst), CFG=CFG, ON=on) + result = subprocess.run(['bash', '-eu', '-c', shell], env=env, capture_output=True, text=True, timeout=20) + self.assertEqual(0, result.returncode, result.stderr) + + def test_program_with_a_disabled_thunk_gets_the_session_thunks(self): + self.write_global('anyprogram.json', {'Comment': 'x', 'ThunksDB': {'GL': 0}}) + self.run_fn('1') + self.assertEqual(json.loads(CFG), json.loads((self.dst / 'anyprogram.json').read_text())) + + def test_disabled_vulkan_counts_too(self): + self.write_global('other.json', {'ThunksDB': {'Vulkan': 0}}) + self.run_fn('1') + self.assertTrue((self.dst / 'other.json').exists()) + + def test_programs_without_a_thunk_opt_out_are_untouched(self): + self.write_global('client.json', {'Config': {'HideHypervisorBit': '1'}}) + self.write_global('enabled.json', {'ThunksDB': {'GL': 1}}) + self.write_global('unrelated.json', {'ThunksDB': {'asound': 0}}) + self.run_fn('1') + self.assertFalse(self.dst.exists()) + + def test_user_override_is_kept(self): + self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}}) + self.dst.mkdir() + user = {'ThunksDB': {'GL': 0}, 'Config': {'Multiblock': '0'}} + (self.dst / 'anyprogram.json').write_text(json.dumps(user)) + self.run_fn('1') + self.assertEqual(user, json.loads((self.dst / 'anyprogram.json').read_text())) + self.run_fn('0') + self.assertEqual(user, json.loads((self.dst / 'anyprogram.json').read_text())) + + def test_software_mode_removes_only_the_written_file(self): + self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}}) + self.run_fn('1') + self.run_fn('0') + self.assertFalse((self.dst / 'anyprogram.json').exists()) + + def test_software_mode_writes_nothing(self): + self.write_global('anyprogram.json', {'ThunksDB': {'GL': 0}}) + self.run_fn('0') + self.assertFalse(self.dst.exists()) + + def test_broken_global_configs_do_not_fail(self): + (self.src / 'broken.json').write_text('{') + self.write_global('list.json', [1, 2]) + self.run_fn('1') + self.assertFalse(self.dst.exists()) + + def test_missing_global_dir_does_not_fail(self): + self.src = self.src / 'missing' + self.run_fn('1') + self.assertFalse(self.dst.exists()) + + def test_launcher_applies_it_to_the_fex_app_config_dirs(self): + self.assertIn('x64_thunk_appconfigs /usr/local/share/fex-emu/AppConfig "$X64_HOME/.config/fex-emu/AppConfig" "$thunk_cfg" "$client_thunks"', SOURCE) + self.assertIn('''printf '%s\\n' "$thunk_cfg" > "$X64_HOME/thunks.json"''', SOURCE) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_store_launch_rockstar.py b/tools/tests/test_store_launch_rockstar.py index 277d2a9f2b..ccd12e24d5 100644 --- a/tools/tests/test_store_launch_rockstar.py +++ b/tools/tests/test_store_launch_rockstar.py @@ -292,5 +292,150 @@ class RockstarLaunch(unittest.TestCase): self.assertIn('Grand Theft Auto: Vice City', text) +SDK_FILES = {'socialclub.dll': b'sdk dll', 'socialclub.pak': b'sdk pak', 'SocialClubHelper.exe': b'sdk helper'} + + +class EpicRockstarLaunch(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.folder = self.root / 'Grand Theft Auto V' + self.folder.mkdir() + (self.folder / 'PlayGTAV.exe').write_bytes(b'MZ') + self.sidecar = {'store': 'epic', 'id': '9d2d0eb64d5c44529cece33fe2a46482', 'title': 'Grand Theft Auto V', 'exe': 'PlayGTAV.exe'} + (self.folder / '.droiddeck-store.json').write_text(json.dumps(self.sidecar)) + self.prefix = self.root / 'prefix' + (self.prefix / 'pfx').mkdir(parents=True) + (self.prefix / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n') + (self.prefix / 'pfx/system.reg').write_text('WINE REGISTRY Version 2\n') + self.sdk = self.prefix / 'pfx/drive_c/Program Files/Rockstar Games/Social Club' + self.unpacked = [] + + def unpacker(self, command, **kwargs): + if command[1] == 'l': + listing = ''.join('Path = x64/%s\nSize = %d\n\n' % (name, len(data)) for name, data in SDK_FILES.items()) + return type('Listing', (), {'returncode': 0, 'stdout': listing.encode()})() + self.unpacked.append(Path(command[-2])) + out = Path(next(arg[2:] for arg in command if arg.startswith('-o'))) / 'x64' + out.mkdir(parents=True) + for name, data in SDK_FILES.items(): + (out / name).write_bytes(data + b' from ' + Path(command[-2]).read_bytes()) + return type('Done', (), {'returncode': 0})() + + def stage(self): + with patch.object(store.shutil, 'which', return_value='/bin/7z'), patch.object(store.subprocess, 'run', side_effect=self.unpacker), \ + patch.object(store, 'wait_for_server', return_value=True), \ + patch.object(store, 'create_prefix', side_effect=AssertionError('the prefix already exists')): + return store.epic_rockstar_sdk(self.folder, self.sidecar, str(self.prefix), '') + + def test_the_launchers_own_sdk_installer_is_staged_so_it_never_runs_it(self): + setup = self.prefix / 'pfx' / store.EPIC_SDK_SETUP + setup.parent.mkdir(parents=True) + setup.write_bytes(b'launcher setup') + (self.folder / 'Installers').mkdir() + (self.folder / 'Installers/Social-Club-Setup.exe').write_bytes(b'older game setup') + self.assertEqual('installed', self.stage()) + self.assertEqual([setup], self.unpacked) + self.assertEqual(b'sdk dll from launcher setup', (self.sdk / 'socialclub.dll').read_bytes()) + text = (self.prefix / 'pfx/system.reg').read_text() + self.assertIn(r'[Software\\Wow6432Node\\Rockstar Games\\Rockstar Games Social Club]', text) + self.assertIn(r'"InstallFolder"="C:\\Program Files\\Rockstar Games\\Social Club"', text) + self.assertNotIn(r'Rockstar Games\\Launcher]', text) + self.assertEqual('present', self.stage()) + self.assertEqual([setup], self.unpacked) + + def test_an_updated_launcher_installer_is_staged_again(self): + setup = self.prefix / 'pfx' / store.EPIC_SDK_SETUP + setup.parent.mkdir(parents=True) + setup.write_bytes(b'launcher setup') + self.assertEqual('installed', self.stage()) + setup.write_bytes(b'newer launcher setup') + self.assertEqual('installed', self.stage()) + self.assertEqual(b'sdk dll from newer launcher setup', (self.sdk / 'socialclub.dll').read_bytes()) + + def test_before_the_launcher_is_installed_the_games_installer_is_used(self): + (self.folder / 'Redistributables').mkdir() + (self.folder / 'Redistributables/Social-Club-Setup.exe').write_bytes(b'game setup') + self.assertEqual('installed', self.stage()) + self.assertEqual(b'sdk dll from game setup', (self.sdk / 'socialclub.dll').read_bytes()) + self.assertNotIn(r'Rockstar Games\\Launcher]', (self.prefix / 'pfx/system.reg').read_text()) + + def test_other_epic_games_are_left_alone(self): + self.assertIsNone(self.stage()) + self.assertEqual([], self.unpacked) + self.assertFalse(self.sdk.exists()) + self.assertEqual('WINE REGISTRY Version 2\n', (self.prefix / 'pfx/system.reg').read_text()) + + def test_an_installer_linked_from_outside_the_game_is_ignored(self): + outside = self.root / 'outside.exe' + outside.write_bytes(b'not the game') + (self.folder / 'Installers').mkdir() + (self.folder / 'Installers/Social-Club-Setup.exe').symlink_to(outside) + self.assertIsNone(self.stage()) + self.assertEqual([], self.unpacked) + + def game_environment(self, shared=None, games=None): + config = self.root / 'home/.config/droiddeck/game-environment.json' + config.parent.mkdir(parents=True, exist_ok=True) + config.write_text(json.dumps({'version': 1, 'shared': shared or {}, 'games': games or {}})) + + def launch(self, bat, parent, compat_data=''): + (self.folder / '.droiddeck-launch.bat').write_text(bat) + calls = [] + env = {'DD_LAUNCH_DIR': str(self.root / 'launch'), 'STEAM_COMPAT_DATA_PATH': compat_data, 'HOME': str(self.root / 'home'), + 'DD_EPIC_PARENT': ''} + with patch.dict(os.environ, env), patch.object(store, 'EPIC_PARENT', parent), \ + patch.object(store, 'client_wanted', return_value=False), \ + patch.object(store, 'ask', side_effect=lambda channel, request, timeout=0, claim=False: calls.append((request['op'], timeout)) or {'ok': False}): + store.main([str(self.folder / '.droiddeck-launch.bat')]) + return calls + + def test_a_title_that_needs_the_parent_fetches_the_stand_in_before_its_code(self): + bat = '@echo off\r\nsetlocal\r\nset "DD_P=1"\r\n' + calls = self.launch(bat, self.root / 'missing/EpicGamesLauncher.exe') + self.assertEqual([('store-service', store.EPIC_SERVICE_WAIT), 'epic-code', 'cloud-down'], + [calls[0]] + [op for op, _ in calls[1:]]) + staged = self.root / 'EpicGamesLauncher.exe' + staged.write_bytes(b'MZ') + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch(bat, staged)]) + + def test_other_epic_games_do_not_fetch_the_stand_in(self): + bat = '@echo off\r\nsetlocal\r\nset "DD_P="\r\nif "%DD_EPIC_PARENT%"=="1" set "DD_P=1"\r\n' + calls = self.launch(bat, self.root / 'missing/EpicGamesLauncher.exe') + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in calls]) + + def test_the_games_own_switch_decides_whether_the_stand_in_is_fetched(self): + compat_data = str(self.root / 'compatdata/4089453117') + missing = self.root / 'missing/EpicGamesLauncher.exe' + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '1'}}) + self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P="\r\n', missing, compat_data)[0][0]) + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '0'}}) + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)]) + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': None}}, shared={'DD_EPIC_PARENT': '0'}) + self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)[0][0]) + + def test_the_sidecars_own_environment_wins_like_it_does_in_the_batch(self): + compat_data = str(self.root / 'compatdata/4089453117') + missing = self.root / 'missing/EpicGamesLauncher.exe' + sidecar = self.folder / '.droiddeck-store.json' + sidecar.write_text(json.dumps(dict(self.sidecar, env={'DD_EPIC_PARENT': '1'}))) + self.assertEqual('store-service', self.launch('@echo off\r\nset "DD_P="\r\n', missing, compat_data)[0][0]) + self.game_environment(games={'4089453117': {'DD_EPIC_PARENT': '1'}}) + sidecar.write_text(json.dumps(dict(self.sidecar, env={'DD_EPIC_PARENT': '"0"'}))) + self.assertEqual(['epic-code', 'cloud-down'], [op for op, _ in self.launch('@echo off\r\nset "DD_P=1"\r\n', missing, compat_data)]) + + def test_the_switch_is_read_the_way_the_game_will_see_it(self): + env = {'HOME': str(self.root / 'home'), 'STEAM_COMPAT_DATA_PATH': str(self.root / 'compatdata/4089453117')} + self.assertEqual('', store.epic_parent_switch({}, env)) + self.assertEqual('1', store.epic_parent_switch({}, dict(env, DD_EPIC_PARENT='1'))) + self.game_environment(shared={'DD_EPIC_PARENT': '1'}, games={'4089453117': {'DD_EPIC_PARENT': '0'}, '7': {'DD_EPIC_PARENT': '1'}}) + self.assertEqual('0', store.epic_parent_switch({}, env)) + self.assertEqual('1', store.epic_parent_switch({'env': {'DD_EPIC_PARENT': '1'}}, env)) + self.assertEqual('1', store.epic_parent_switch({}, dict(env, STEAM_COMPAT_DATA_PATH=str(self.root / 'compatdata/12')))) + (self.root / 'home/.config/droiddeck/game-environment.json').write_text('{"version": 9}') + self.assertEqual('1', store.epic_parent_switch({}, dict(env, DD_EPIC_PARENT='1'))) + + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/test_stretch_game_screen.py b/tools/tests/test_stretch_game_screen.py new file mode 100644 index 0000000000..0c2a2eef37 --- /dev/null +++ b/tools/tests/test_stretch_game_screen.py @@ -0,0 +1,56 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session' +OUTPUT = '2184x1968' +GAME = '3498x1968' + + +class StretchGameScreenTest(unittest.TestCase): + def call(self, value): + source = SESSION.read_text() + start = source.index('dd_stretch_game_screen() {') + end = source.index('\n}\n', start) + 3 + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / 'xprop.log' + fake = Path(directory) / 'xprop' + fake.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> "$XPROP_LOG"\n') + fake.chmod(0o755) + env = dict(os.environ, XPROP_LOG=str(log), PATH=directory + os.pathsep + os.environ['PATH']) + script = source[start:end] + f'dd_stretch_game_screen "{value}" {OUTPUT} {GAME}\n' + result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=5) + written = log.read_text().splitlines() if log.exists() else [] + return result.returncode, written + + def test_the_game_screen_the_client_sizes_to_the_output_is_given_the_stretched_size(self): + status, written = self.call('1, 2184, 1968, 0') + self.assertEqual(0, status) + self.assertEqual(['-root -f GAMESCOPE_XWAYLAND_MODE_CONTROL 32c -set GAMESCOPE_XWAYLAND_MODE_CONTROL 1, 3498, 1968, 1'], written) + + def test_a_game_resolution_chosen_in_steam_is_kept(self): + status, written = self.call('1, 1280, 720, 0') + self.assertNotEqual(0, status) + self.assertEqual([], written) + + def test_the_clients_own_screen_is_left_alone(self): + status, written = self.call('0, 2184, 1968, 0') + self.assertNotEqual(0, status) + self.assertEqual([], written) + + def test_the_stretched_size_is_not_rewritten_again(self): + status, written = self.call('1, 3498, 1968, 1') + self.assertNotEqual(0, status) + self.assertEqual([], written) + + def test_a_missing_property_is_ignored(self): + status, written = self.call('') + self.assertNotEqual(0, status) + self.assertEqual([], written) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_udevmon_preload.py b/tools/tests/test_udevmon_preload.py new file mode 100644 index 0000000000..ae100ecfbb --- /dev/null +++ b/tools/tests/test_udevmon_preload.py @@ -0,0 +1,112 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +PROGRAM = r""" +#define _GNU_SOURCE +#include <dlfcn.h> +#include <fcntl.h> +#include <linux/netlink.h> +#include <poll.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/socket.h> +#include <unistd.h> + +int main(int argc, char **argv) { + unsigned groups = argc > 1 ? (unsigned)atoi(argv[1]) : 2; + const char *mode = argc > 2 ? argv[2] : ""; + if (!strcmp(mode, "churn")) { + for (int i = 0; i < 16; i++) { + int closed = socket(AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT); + struct sockaddr_nl unsubscribed = {.nl_family = AF_NETLINK}; + if (closed < 0 || bind(closed, (struct sockaddr *)&unsubscribed, sizeof(unsubscribed)) != 0) return 3; + close(closed); + if (open("/dev/null", O_RDONLY) != closed) return 4; + } + } + int fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT); + if (fd < 0) { printf("socket failed\n"); return 2; } + struct sockaddr_nl nl = {.nl_family = AF_NETLINK, .nl_groups = groups}; + printf("bind %d\n", bind(fd, (struct sockaddr *)&nl, sizeof(nl))); + if (!strcmp(mode, "rebind")) { + nl.nl_pid = (unsigned)getpid() + 1; + printf("rebind %d\n", bind(fd, (struct sockaddr *)&nl, sizeof(nl))); + } + printf("cloexec %d nonblock %d\n", (fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (fcntl(fd, F_GETFL) & O_NONBLOCK) != 0); + int (*inject)(const char *, const char *, const char *, const char *, unsigned, unsigned) = + (int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned))dlsym(RTLD_DEFAULT, "dd_udevmon_inject"); + int sent = inject("add", "/devices/droiddeck/usb4/4-1:1.3/0003:054C:09CC.0005/hidraw/hidraw20", "hidraw", + "/dev/hidraw20", 245, 20); + printf("sent %d\n", sent); + struct pollfd p = {.fd = fd, .events = POLLIN}; + if (sent > 0 && poll(&p, 1, 1000) == 1) { + char buf[2048]; + struct sockaddr_nl from; + struct iovec iov = {.iov_base = buf, .iov_len = sizeof(buf)}; + struct msghdr msg = {.msg_name = &from, .msg_namelen = sizeof(from), .msg_iov = &iov, .msg_iovlen = 1}; + ssize_t n = recvmsg(fd, &msg, 0); + int found = 0; + for (ssize_t i = 0; n > 0 && i < n; i += (ssize_t)strlen(buf + i) + 1) + if (!strcmp(buf + i, "ACTION=add") || !strcmp(buf + i, "DEVNAME=/dev/hidraw20")) found++; + printf("received %s fields %d\n", n > 0 && !memcmp(buf, "libudev", 8) ? "libudev" : "nothing", found); + } + return 0; +} +""" + + +@unittest.skipUnless(shutil.which("gcc") and os.uname().machine == "x86_64", "needs gcc on an x86-64 host") +class UdevMonitorPreloadTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = Path(tempfile.mkdtemp()) + cls.library = cls.tmp / "libudevmon.so" + subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-DUDEVMON_TEST", "-DBINFMT_TEST", + '-DBINFMT_HANDLER="/bin/false"', "-o", str(cls.library), "-pthread"] + + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "perms.c", "webhelper.c")] + + [str(Path(__file__).with_name("netlink_stubs.c")), "-ldl"], check=True) + source = cls.tmp / "program.c" + source.write_text(PROGRAM) + cls.program = cls.tmp / "program" + subprocess.run(["gcc", "-O2", "-o", str(cls.program), str(source), "-ldl"], check=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, True) + + def run_program(self, *args, refuse=False): + env = dict(os.environ, LD_PRELOAD=str(self.library)) + env.pop("DD_UDEVMON_REFUSE", None) + if refuse: + env["DD_UDEVMON_REFUSE"] = "1" + return subprocess.run([str(self.program), *args], env=env, capture_output=True, text=True, check=True).stdout.splitlines() + + def test_a_monitor_the_system_will_not_subscribe_hears_the_sessions_events(self): + out = self.run_program(refuse=True) + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out) + + def test_a_monitor_the_system_subscribes_stays_on_the_real_socket(self): + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 0"], self.run_program()) + + def test_a_monitor_bound_without_groups_hears_the_sessions_events(self): + out = self.run_program("0") + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out) + + def test_failed_rebind_leaves_the_original_subscription_in_place(self): + out = self.run_program("2", "rebind") + self.assertEqual(["bind 0", "rebind -1", "cloexec 1 nonblock 1", "sent 0"], out) + + def test_closed_monitors_do_not_exhaust_stand_in_slots(self): + out = self.run_program("0", "churn") + self.assertEqual(["bind 0", "cloexec 1 nonblock 1", "sent 1", "received libudev fields 2"], out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_unwrap_dwarfs.py b/tools/tests/test_unwrap_dwarfs.py new file mode 100644 index 0000000000..0c2676eaa9 --- /dev/null +++ b/tools/tests/test_unwrap_dwarfs.py @@ -0,0 +1,45 @@ +import struct +import subprocess +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/unwrap-dwarfs.sh" + + +class UnwrapDwarfsTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + self.output = self.dir / "dwarfsextract" + + def wrapper(self, payload, magic=b"SQUEEZE!", packed=None): + compressed = subprocess.run(["zstd", "-q", "-c"], input=payload, capture_output=True, check=True).stdout + size = len(compressed) if packed is None else packed + path = self.dir / "wrapper" + path.write_bytes(b"\x7fELF stub" * 100 + compressed + magic + struct.pack("<QQQ", len(payload), size, 0)) + return path + + def unwrap(self, wrapper): + return subprocess.run(["bash", str(SCRIPT), str(wrapper), str(self.output)], capture_output=True, text=True) + + def test_the_payload_behind_the_stub_is_unpacked(self): + payload = b"\x7fELF" + bytes(range(256)) * 64 + run = self.unwrap(self.wrapper(payload)) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertEqual(self.output.read_bytes(), payload) + + def test_a_file_without_the_trailer_is_refused(self): + run = self.unwrap(self.wrapper(b"payload", magic=b"NOTSQZ!!")) + self.assertNotEqual(run.returncode, 0) + self.assertIn("no SQUEEZE! trailer", run.stderr) + + def test_a_payload_size_beyond_the_file_is_refused(self): + run = self.unwrap(self.wrapper(b"payload", packed=1 << 40)) + self.assertNotEqual(run.returncode, 0) + self.assertIn("bad payload size", run.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_vdec_emulator.py b/tools/tests/test_vdec_emulator.py index bf16a3fc39..3fd3091542 100644 --- a/tools/tests/test_vdec_emulator.py +++ b/tools/tests/test_vdec_emulator.py @@ -113,12 +113,12 @@ int main(void) { f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 736; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12; if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.num_planes != 1) return 14; uint32_t bpl = f.fmt.pix_mp.plane_fmt[0].bytesperline, size = f.fmt.pix_mp.plane_fmt[0].sizeimage; - if (bpl != 1280 || size != 1280 * 736 * 3 / 2) return 15; + if (bpl != 4096 || size != 4096 * 2304 * 3 / 2) return 15; r = (struct v4l2_requestbuffers){ .count = 3, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .memory = V4L2_MEMORY_DMABUF }; if (call(VIDIOC_REQBUFS, &r) || r.count != 3) return 16; int out[3]; for (int i = 0; i < 3; i++) { - struct create_dumb c = { .height = 736, .width = 1280, .bpp = 16 }; + struct create_dumb c = { .height = 2304, .width = 4096, .bpp = 16 }; if (drm_ioctl(card, 0xc02064b2, &c) || !c.handle || c.size < size) return 17; struct prime_handle h = { .handle = c.handle, .flags = O_CLOEXEC }; if (drm_ioctl(card, 0xc00c642d, &h)) return 18; @@ -148,7 +148,7 @@ int main(void) { struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &cp }; if (call(VIDIOC_DQBUF, &cb)) return 25; unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, out[cb.index], 0); - printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 736], cp.bytesused == size); + printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 2304], cp.bytesused == size); munmap(m, size); pf = (struct pollfd){ .fd = vfd, .events = 0x306 }; if (poll(&pf, 1, 0) != 1) return 26; @@ -166,7 +166,7 @@ int main(void) { size = f.fmt.pix_mp.plane_fmt[0].sizeimage; r = (struct v4l2_requestbuffers){ .count = 1, .type = types[1], .memory = V4L2_MEMORY_DMABUF }; if (call(VIDIOC_REQBUFS, &r)) return 31; - struct create_dumb big = { .height = 1088, .width = 1920, .bpp = 16 }; + struct create_dumb big = { .height = 2304, .width = 4096, .bpp = 16 }; if (drm_ioctl(card, 0xc02064b2, &big)) return 32; struct prime_handle bh = { .handle = big.handle, .flags = O_CLOEXEC }; if (drm_ioctl(card, 0xc00c642d, &bh)) return 33; @@ -183,7 +183,7 @@ int main(void) { struct v4l2_buffer db = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &dp }; if (call(VIDIOC_DQBUF, &db)) return 37; unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0); - printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]); + printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)4096 * 2304]); dd_vdec_closed(vfd); return 0; } @@ -261,7 +261,7 @@ class VdecEmulatorTest(unittest.TestCase): self.assertEqual(done.stdout.split('\n')[:6], ['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu']) self.assertEqual([c[1:6] for c in server.configs], - [(1, 1280, 720, 1280, 736), (1, 1280, 720, 1920, 1088)]) + [(1, 1280, 720, 4096, 2304), (1, 1280, 720, 4096, 2304)]) self.assertEqual([p[:3] for p in server.packets], [(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)]) diff --git a/tools/tests/test_vdec_stream_size.py b/tools/tests/test_vdec_stream_size.py new file mode 100644 index 0000000000..4bf5fca3f3 --- /dev/null +++ b/tools/tests/test_vdec_stream_size.py @@ -0,0 +1,140 @@ +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +VDEC = ROOT / 'tools/linuxfs/preload/vdec.c' + + +class Bits: + def __init__(self): + self.bits = [] + + def u(self, value, count): + self.bits += [(value >> (count - 1 - i)) & 1 for i in range(count)] + + def ue(self, value): + value += 1 + length = value.bit_length() + self.u(0, length - 1) + self.u(value, length) + + def bytes(self): + bits = self.bits + [1] + while len(bits) % 8: + bits.append(0) + raw = bytes(int(''.join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8)) + out = bytearray() + for i, byte in enumerate(raw): + if len(out) >= 2 and out[-1] == 0 and out[-2] == 0 and byte <= 3: + out.append(3) + out.append(byte) + return bytes(out) + + +def sps(width_mbs, height_units, profile=100, frame_mbs_only=1, poc_type=2): + b = Bits() + b.u(profile, 8) + b.u(0, 8) + b.u(51, 8) + b.ue(0) + if profile in (100, 110, 122, 244): + b.ue(1) + b.ue(0) + b.ue(0) + b.u(0, 1) + b.u(0, 1) + b.ue(0) + b.ue(poc_type) + if poc_type == 0: + b.ue(4) + b.ue(1) + b.u(0, 1) + b.ue(width_mbs - 1) + b.ue(height_units - 1) + b.u(frame_mbs_only, 1) + if not frame_mbs_only: + b.u(0, 1) + b.u(1, 1) + b.u(0, 1) + return b'\x00\x00\x00\x01\x67' + b.bytes() + b'\x00\x00\x00\x01\x65\x88\x84\x00' + + +def hevc_sps(width, height, sub_layers_minus1=0): + b = Bits() + b.u(0, 4) + b.u(sub_layers_minus1, 3) + b.u(1, 1) + b.u(0, 88) + b.u(93, 8) + for _ in range(sub_layers_minus1): + b.u(0, 2) + if sub_layers_minus1: + for _ in range(sub_layers_minus1, 8): + b.u(0, 2) + b.ue(0) + b.ue(1) + b.ue(width) + b.ue(height) + b.u(0, 1) + return b'\x00\x00\x00\x01\x42\x01' + b.bytes() + b'\x00\x00\x00\x01\x26\x01\xaf' + + +DRIVER = r''' +#include "vdec.c" +#include <stdio.h> + +int main(int argc, char **argv) { + FILE *f = fopen(argv[1], "rb"); + static uint8_t data[4096]; + size_t n = fread(data, 1, sizeof data, f); + uint32_t w = 0, h = 0; + int rc = argc > 2 ? vd_stream_size_h265(data, n, &w, &h) : vd_stream_size_h264(data, n, &w, &h); + printf("%d %u %u\n", rc, w, h); + return 0; +} +''' + + +class StreamSizeTest(unittest.TestCase): + def run_driver(self, data, hevc=False): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / 'driver.c').write_text(DRIVER) + (tmp / 'stream.bin').write_bytes(data) + exe = tmp / 'driver' + subprocess.run(['gcc', '-std=gnu11', '-DDD_VDEC_ANY_ARCH', '-I', str(VDEC.parent), '-o', str(exe), str(tmp / 'driver.c'), str(VDEC.parent / 'venc.c'), '-ldl', '-lpthread'], + check=True, capture_output=True, text=True) + return subprocess.run([str(exe), str(tmp / 'stream.bin')] + (['h265'] if hevc else []), check=True, capture_output=True, text=True).stdout.split() + + def test_reads_an_ultrawide_stream_size(self): + self.assertEqual(['0', '3440', '1440'], self.run_driver(sps(215, 90))) + + def test_reads_a_small_stream_size(self): + self.assertEqual(['0', '800', '464'], self.run_driver(sps(50, 29))) + + def test_interlaced_streams_double_the_height(self): + self.assertEqual(['0', '1920', '1088'], self.run_driver(sps(120, 34, frame_mbs_only=0))) + + def test_baseline_profile_has_no_chroma_fields(self): + self.assertEqual(['0', '1280', '720'], self.run_driver(sps(80, 45, profile=66))) + + def test_emulation_prevention_bytes_are_removed(self): + self.assertEqual(['0', '256', '256'], self.run_driver(sps(16, 16, profile=66))) + + def test_reads_an_h265_stream_size(self): + self.assertEqual(['0', '3440', '1440'], self.run_driver(hevc_sps(3440, 1440), hevc=True)) + + def test_h265_sizes_round_up_to_sixteen(self): + self.assertEqual(['0', '1920', '1088'], self.run_driver(hevc_sps(1920, 1080, sub_layers_minus1=2), hevc=True)) + + def test_a_truncated_sps_is_rejected(self): + self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x67\x64\x00\x33\xac\xb4\x02\x80\x2d')[0]) + + def test_a_stream_without_an_sps_is_left_alone(self): + self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x65\x88\x84\x00\x00\x01')[0]) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_vk_layer_ahb_import.py b/tools/tests/test_vk_layer_ahb_import.py new file mode 100644 index 0000000000..53d2ba40fa --- /dev/null +++ b/tools/tests/test_vk_layer_ahb_import.py @@ -0,0 +1,227 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_vk_pending_completion import function + +SRC = Path(__file__).resolve().parents[2] / "app/src/main/cpp/waylandcomp/src" + +HARNESS = r''' +#include <assert.h> +#include <stddef.h> +#include <stdint.h> + +#define VKP_VENDOR_QUALCOMM 0x5143 +static int dev_state; +static uint32_t g_vendor_id; +static char *g_library_name; +static int g_ahb_import; +static struct { void *GetAndroidHardwareBufferPropertiesANDROID; } g_vk; +static int dev_init(void) { return dev_state; } +static int properties_stub; + +%(can_import)s + +static int can(uint32_t vendor, char *library, int ext) { + dev_state = 0; + g_vendor_id = vendor; + g_library_name = library; + g_ahb_import = ext; + g_vk.GetAndroidHardwareBufferPropertiesANDROID = ext ? &properties_stub : NULL; + return vkp_can_import_ahb(); +} + +int main(void) { + char radv[] = "libvulkan_radeon.so"; + char panvk[] = "libvulkan_panfrost.so"; + const uint32_t samsung = 0x144d, arm = 0x13b5, imagination = 0x1010; + + assert(can(samsung, NULL, 1)); + assert(can(arm, NULL, 1)); + assert(can(imagination, NULL, 1)); + + assert(!can(samsung, radv, 1)); + assert(!can(arm, panvk, 1)); + + assert(!can(VKP_VENDOR_QUALCOMM, NULL, 1)); + assert(!can(samsung, NULL, 0)); + + dev_state = -1; + g_vendor_id = samsung; g_library_name = NULL; g_ahb_import = 1; + g_vk.GetAndroidHardwareBufferPropertiesANDROID = &properties_stub; + assert(!vkp_can_import_ahb()); + return 0; +} +''' + + +POOL_HARNESS = r''' +#define _GNU_SOURCE +#include <assert.h> +#include <stddef.h> +#include <stdint.h> +#include <stdio.h> +#include <sys/types.h> + +#define FOURCC(a, b, c, d) ((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24)) +#define DRM_ABGR8888 FOURCC('A', 'B', '2', '4') +#define DRM_ABGR2101010 FOURCC('A', 'B', '3', '0') +#define AHB_RGBA8 1u +#define AHB_RGB10A2 0x2bu +#define MOD_LINEAR 0ULL +#define MOD_QCOM_COMPRESSED 0x0500000000000001ULL +#define SC_MOD_GRALLOC (~0ULL - 1) +#define SC_LAYER_AHB_USAGE_VENDOR_UBWC (1ULL << 28) +#define AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT (1ULL << 9) +#define AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE (1ULL << 8) +#define AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY (1ULL << 11) +#define AHARDWAREBUFFER_USAGE_CPU_READ_RARELY 2ULL + +typedef struct AHardwareBuffer AHardwareBuffer; +typedef struct { + uint32_t width, height, layers, format; + uint64_t usage; + uint32_t stride, rfu0; + uint64_t rfu1; +} AHardwareBuffer_Desc; +struct droiddeck_native_handle { int version; int numFds; int numInts; int data[4]; }; +struct vkp_image { int unused; }; +struct slot { AHardwareBuffer *ahb; struct vkp_image *img; int w, h; uint32_t fmt; int release_fd; int busy; }; +struct layer { + const char *name; + int pool_n; + int alloc_tier; + unsigned import_failed_fmts; + uint64_t pool_modifier; + int logged_w, logged_h, logged_tier; + uint32_t logged_fmt; + uint64_t logged_mod; +}; + +enum { TIER_UBWC, TIER_PLAIN, TIER_LINEAR }; +static int g_alloc_failed; +static uint32_t g_hdr_pool_fmt = AHB_RGB10A2; + +static struct droiddeck_native_handle handle = {.numFds = 1, .data = {3}}; +static AHardwareBuffer *buffer = (AHardwareBuffer *)&handle; +static struct vkp_image image; +static int allocations, imports_10_bit, imports_8_bit, accept_10_bit, accept_8_bit; + +static int AHardwareBuffer_allocate(const AHardwareBuffer_Desc *d, AHardwareBuffer **out) { + (void)d; allocations++; *out = buffer; return 0; +} +static void AHardwareBuffer_describe(const AHardwareBuffer *b, AHardwareBuffer_Desc *d) { + (void)b; d->stride = 1920; d->usage = 0; +} +static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; } +static const void *native_handle(const AHardwareBuffer *b) { (void)b; return &handle; } +static struct { const void *(*getNativeHandle)(const AHardwareBuffer *); } api = {native_handle}; +static int sniff_modifier(const struct droiddeck_native_handle *h, uint64_t *mod) { (void)h; (void)mod; return 0; } +static int vkp_can_import_ahb(void) { return 0; } +static struct vkp_image *vkp_image_import_ahb(AHardwareBuffer *b, char *info, size_t n) { + (void)b; (void)info; (void)n; return NULL; +} +static struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm, uint64_t mod, int w, int h, uint32_t pitch, + uint32_t offset, int planes) { + (void)fd; (void)mod; (void)w; (void)h; (void)pitch; (void)offset; (void)planes; + if (drm == DRM_ABGR2101010) { imports_10_bit++; return accept_10_bit ? &image : NULL; } + imports_8_bit++; + return accept_8_bit ? &image : NULL; +} +static int handle_fd(const struct droiddeck_native_handle *h, off_t need, int *which) { + (void)need; *which = 0; return h->data[0]; +} +static void describe_handle(const struct droiddeck_native_handle *h, char *out, size_t n) { (void)h; snprintf(out, n, "-"); } +static const char *pool_kind(uint64_t mod) { return mod == SC_MOD_GRALLOC ? "gralloc-laid-out" : "linear"; } +static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; } + +%(tier_name)s +%(alloc_slot)s + +static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait_fd) { + struct slot s = {0}; + *wait_fd = -1; + g_alloc_failed = 0; + return alloc_slot(l, &s, w, h, fmt) == 0 ? 0 : -1; +} + +%(take_hdr_slot)s + +static int frame(struct layer *l) { + int fd; + return take_hdr_slot(l, 1920, 1080, &fd); +} + +static void reset(int ten, int eight) { + g_hdr_pool_fmt = AHB_RGB10A2; + allocations = imports_10_bit = imports_8_bit = 0; + accept_10_bit = ten; + accept_8_bit = eight; +} + +int main(void) { + struct layer ten_bit_refused = {.name = "game", .pool_n = 3}; + reset(0, 1); + assert(frame(&ten_bit_refused) == 0); + assert(g_hdr_pool_fmt == AHB_RGBA8); + assert(imports_10_bit == 1 && imports_8_bit == 1); + assert(ten_bit_refused.alloc_tier == TIER_LINEAR); + assert(frame(&ten_bit_refused) == 0); + assert(imports_10_bit == 1 && imports_8_bit == 2); + + struct layer ten_bit_works = {.name = "game", .pool_n = 3}; + reset(1, 1); + assert(frame(&ten_bit_works) == 0); + assert(g_hdr_pool_fmt == AHB_RGB10A2); + assert(imports_10_bit == 1 && imports_8_bit == 0); + + struct layer nothing_imports = {.name = "game", .pool_n = 3}; + reset(0, 0); + assert(frame(¬hing_imports) == -1 && g_alloc_failed); + assert(imports_10_bit == 1 && imports_8_bit == 1); + const int tried = allocations; + assert(frame(¬hing_imports) == -1 && g_alloc_failed); + assert(frame(¬hing_imports) == -1 && g_alloc_failed); + assert(allocations == tried); + assert(imports_10_bit == 1 && imports_8_bit == 1); + return 0; +} +''' + +class LayerAhbImportTest(unittest.TestCase): + def test_only_the_system_driver_imports_gralloc_layouts(self): + compiler = shutil.which(os.environ.get("CC", "cc")) + if not compiler: + self.fail("A C compiler is required for the layer AHardwareBuffer import test") + body = function((SRC / "vk_present.c").read_text(), "vkp_can_import_ahb") + with tempfile.TemporaryDirectory(prefix="droiddeck-layer-ahb-") as tmp: + source = Path(tmp) / "layer_ahb_import_test.c" + source.write_text(HARNESS % {"can_import": body}) + program = Path(tmp) / "layer-ahb-import" + built = subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror", "-UNDEBUG", str(source), + "-o", str(program)], capture_output=True, text=True) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30) + self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) + + def test_a_failed_10_bit_pool_still_falls_back_to_8_bit_and_failures_are_latched_per_format(self): + compiler = shutil.which(os.environ.get("CC", "cc")) + if not compiler: + self.fail("A C compiler is required for the layer pool fallback test") + text = (SRC / "sc_layer.c").read_text() + functions = {name: function(text, name) for name in ("tier_name", "alloc_slot", "take_hdr_slot")} + with tempfile.TemporaryDirectory(prefix="droiddeck-layer-pool-") as tmp: + source = Path(tmp) / "layer_pool_fallback_test.c" + source.write_text(POOL_HARNESS % functions) + program = Path(tmp) / "layer-pool-fallback" + built = subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", + "-UNDEBUG", str(source), "-o", str(program)], capture_output=True, text=True) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30) + self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_vk_linear_dmabuf.py b/tools/tests/test_vk_linear_dmabuf.py new file mode 100644 index 0000000000..08c4a24577 --- /dev/null +++ b/tools/tests/test_vk_linear_dmabuf.py @@ -0,0 +1,156 @@ +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_vk_external_image_sync import vulkan_include_args +from tools.tests.test_vk_pending_completion import function + +TESTS = Path(__file__).resolve().parent +SRC = TESTS.parents[1] / "app/src/main/cpp/waylandcomp/src" + +LAYER_HARNESS = r''' +#include <assert.h> +#include <stdint.h> +#include <vulkan/vulkan.h> +#include "vk_external_image_sync.h" +#include "vk_linear_dmabuf.h" + +typedef struct AHardwareBuffer AHardwareBuffer; +%(image)s +struct vkp_draw { + struct vkp_image *img; + float sx, sy, sw, sh; + int dx, dy, dw, dh; + int blend; +}; +struct draw_list { struct vkp_draw *d; int n, cap; }; +static const uint32_t g_qfam = 2; +%(foreign)s +%(is_dmabuf)s +%(width)s +%(height)s +static int black_fill_below(const struct draw_list *dl, int n) { (void)dl; (void)n; return 0; } +%(candidate)s + +static int candidate(struct vkp_image *img) { + struct vkp_draw d = {.img = img, .sw = 1560, .sh = 720, .dw = 1560, .dh = 720}; + struct draw_list dl = {.d = &d, .n = 1, .cap = 1}; + return layer_candidate(&dl, 1560, 720); +} + +static int foreign_pair(struct vkp_image *img) { + struct vkp_external_client_barrier_pair pair; + return vkp_external_client_barrier_pair(img->image, g_qfam, foreign_image(img), img->blit_dst, &pair); +} + +int main(void) { + struct vkp_image staged = {.w = 1560, .h = 720, .dmabuf = 1, .staged = 1}; + assert(candidate(&staged) == 0); + assert(!foreign_pair(&staged)); + + struct vkp_image client = {.w = 1560, .h = 720, .dmabuf = 1}; + assert(candidate(&client) == 0); + assert(foreign_pair(&client)); + + struct vkp_image shm = {.w = 1560, .h = 720}; + assert(candidate(&shm) == -1); + assert(!foreign_pair(&shm)); + + struct vkp_image layer = {.w = 1560, .h = 720, .dmabuf = 1, .blit_dst = 1}; + assert(candidate(&layer) == -1); + assert(!foreign_pair(&layer)); + return 0; +} +''' + + +def compile_and_run(test, source, tmp, name): + compiler = shutil.which(os.environ.get("CC", "cc")) + if not compiler: + test.fail("A C compiler is required for the linear dma-buf regression tests") + program = Path(tmp) / name + command = [ + compiler, + "-std=c11", + "-Wall", + "-Wextra", + "-Werror", + "-UNDEBUG", + "-I", + str(SRC), + *vulkan_include_args(), + str(source), + "-o", + str(program), + ] + built = subprocess.run(command, capture_output=True, text=True) + test.assertEqual(built.returncode, 0, built.stdout + built.stderr) + ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30) + test.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) + + +class VkLinearDmabufTest(unittest.TestCase): + def test_linear_dmabuf_copy(self): + with tempfile.TemporaryDirectory(prefix="droiddeck-vk-linear-") as tmp: + compile_and_run(self, TESTS / "vk_linear_dmabuf_test.c", tmp, "vk-linear-dmabuf") + + def test_readback_orders_general_transition_after_staging_copy(self): + body = function((SRC / "vk_present.c").read_text(), "vkp_image_readback") + stage = body.index("stage_linear_dmabuf(cmd, src);") + barrier = body.index("vkp_linear_dmabuf_readback_stage(src->in_general)") + self.assertLess(stage, barrier) + self.assertIn(".srcAccessMask = vkp_linear_dmabuf_readback_access(src->in_general)", body[stage:barrier]) + self.assertNotIn("CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT", body) + + def test_modifier_query_needs_drm_modifier_extension(self): + body = function((SRC / "vk_present.c").read_text(), "vkp_image_import_dmabuf") + query = re.search(r"const int modifier_sampled = (.*?);", body, re.S) + self.assertIsNotNone(query, "modifier_sampled not found in vkp_image_import_dmabuf") + terms = [t.strip() for t in query.group(1).split("&&")] + self.assertIn("g_drm_modifiers", terms) + self.assertLess(terms.index("g_drm_modifiers"), terms.index("modifier_importable(img->fmt, modifier, sampled_usage)")) + self.assertIn("!as_blit_dst", terms) + self.assertIn("g_vk.GetPhysicalDeviceImageFormatProperties2", terms) + + def test_staged_client_image_stays_layer_candidate(self): + vk = (SRC / "vk_present.c").read_text() + comp = (SRC / "compositor.c").read_text() + image = re.search(r"^struct vkp_image \{.*?^\};", vk, re.M | re.S) + self.assertIsNotNone(image, "struct vkp_image not found in vk_present.c") + harness = LAYER_HARNESS % { + "image": image.group(0), + "foreign": function(vk, "foreign_image"), + "is_dmabuf": function(vk, "vkp_image_is_dmabuf"), + "width": function(vk, "vkp_image_width"), + "height": function(vk, "vkp_image_height"), + "candidate": function(comp, "layer_candidate"), + } + with tempfile.TemporaryDirectory(prefix="droiddeck-vk-linear-layer-") as tmp: + source = Path(tmp) / "layer_candidate_test.c" + source.write_text(harness) + compile_and_run(self, source, tmp, "vk-linear-layer") + + def test_layer_import_failure_requests_compositor_fallback(self): + source = (SRC / "sc_layer.c").read_text() + for name in ("sc_layer_present", "sc_layer_present_overlay"): + with self.subTest(layer=name): + body = function(source, name) + self.assertRegex(body, r"if \(idx < 0\) \{ log_drop\(l\); return g_alloc_failed \? -1 : 0; \}") + + def test_layer_blits_use_the_imported_output_row_pitch(self): + source = (SRC / "vk_present.c").read_text() + blit = function(source, "blit_to_layer") + copy = blit.index("CmdCopyImageToBuffer") + self.assertLess(blit.index("VkBufferImageCopy copy = dst->linear_copy"), copy) + self.assertLess(blit.index("VK_ACCESS_TRANSFER_WRITE_BIT, 1"), copy) + self.assertGreater(blit.index("VK_ACCESS_TRANSFER_WRITE_BIT, 0"), copy) + for name in ("vkp_blit_image", "pass_finish"): + self.assertIn("blit_to_layer(", function(source, name)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_vk_pending_completion.py b/tools/tests/test_vk_pending_completion.py index d0a4ad594c..8f3dc48eb0 100644 --- a/tools/tests/test_vk_pending_completion.py +++ b/tools/tests/test_vk_pending_completion.py @@ -56,16 +56,20 @@ static VkResult wait_fn(uintptr_t dev, unsigned n, const VkFence *f, int all, ui static void unmap_fn(uintptr_t dev, uintptr_t mem) { (void)dev; (void)mem; ++unmapped; } static void destroy_fn(uintptr_t dev, uintptr_t img, void *allocator) { (void)dev; (void)img; (void)allocator; ++destroyed; } static void free_fn(uintptr_t dev, uintptr_t mem, void *allocator) { (void)dev; (void)mem; (void)allocator; ++freed_memory; } +static unsigned destroyed_buffers; +static void destroy_buffer_fn(uintptr_t dev, uintptr_t buf, void *allocator) { (void)dev; (void)buf; (void)allocator; ++destroyed_buffers; } +#define VK_NULL_HANDLE 0 static struct { VkResult (*WaitForFences)(uintptr_t, unsigned, const VkFence *, int, uint64_t); void (*UnmapMemory)(uintptr_t, uintptr_t); void (*DestroyImage)(uintptr_t, uintptr_t, void *); void (*FreeMemory)(uintptr_t, uintptr_t, void *); -} g_vk = {wait_fn, unmap_fn, destroy_fn, free_fn}; + void (*DestroyBuffer)(uintptr_t, uintptr_t, void *); +} g_vk = {wait_fn, unmap_fn, destroy_fn, free_fn, destroy_buffer_fn}; typedef struct AHardwareBuffer AHardwareBuffer; static int released_buffers; static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; ++released_buffers; } -struct vkp_image { uintptr_t image, mem; void *map; AHardwareBuffer *android_buffer; }; +struct vkp_image { uintptr_t image, mem; void *map; AHardwareBuffer *android_buffer; uintptr_t linear_buf, linear_mem; int staged, in_general; }; static void blendp_forget_image(uintptr_t image) { (void)image; ++forgotten; } /* PRODUCTION_FUNCTIONS */ static struct vkp_image *image(void) { @@ -173,7 +177,7 @@ class VkPendingCompletionTest(unittest.TestCase): self.assertEqual(ran.returncode,0,ran.stdout+ran.stderr) def test_unknown_completion_retains_gpu_resources(self): - self.compile_and_run(HARNESS, ['quarantine_pending_work', 'timed_wait', 'vkp_image_destroy']) + self.compile_and_run(HARNESS, ['quarantine_pending_work', 'timed_wait', 'destroy_image_objects', 'vkp_image_destroy']) def test_failed_device_idle_does_not_destroy_swapchain(self): # LOGE's arguments must be evaluated as real production logging does. diff --git a/tools/tests/test_webhelper_preload.py b/tools/tests/test_webhelper_preload.py index 3847e9988f..5b530566c1 100644 --- a/tools/tests/test_webhelper_preload.py +++ b/tools/tests/test_webhelper_preload.py @@ -15,8 +15,11 @@ int main(int argc, char **argv) { const char *mode = getenv("TEST_NODE_MODE_CHILD"); static char node[64]; snprintf(node, sizeof node, "ELECTRON_RUN_AS_NODE=%s", mode ? mode : ""); - char *node_env[] = {node, NULL}; - char *plain_env[] = {"PATH=/usr/bin", NULL}; + const char *x = getenv("TEST_DISPLAY"); + static char display[64]; + snprintf(display, sizeof display, "DISPLAY=%s", x ? x : ""); + char *node_env[] = {node, x ? display : NULL, NULL}; + char *plain_env[] = {"PATH=/usr/bin", x ? display : NULL, NULL}; char *const *envp = mode ? node_env : plain_env; char *const *out = dd_webhelper_argv(argv[1], argv + 1, (char *const *)envp); for (int i = 0; out[i]; i++) printf("%s\n", out[i]); @@ -42,8 +45,10 @@ class WebhelperPreloadTest(unittest.TestCase): def tearDownClass(cls): shutil.rmtree(cls.tmp, ignore_errors=True) - def argv(self, *args, spec=None, node_child=False, parent_node=False): - env = {k: v for k, v in os.environ.items() if k != "DD_WEBHELPER_ARGS"} + def argv(self, *args, spec=None, node_child=False, parent_node=False, display=None): + env = {k: v for k, v in os.environ.items() if k not in ("DD_WEBHELPER_ARGS", "TEST_DISPLAY")} + if display is not None: + env["TEST_DISPLAY"] = display env.pop("ELECTRON_RUN_AS_NODE", None) if spec is not None: env["DD_WEBHELPER_ARGS"] = spec @@ -104,6 +109,50 @@ class WebhelperPreloadTest(unittest.TestCase): chrome = self.chromium("chromium-parent-mode", "chrome") self.assertEqual(self.argv(chrome, parent_node=True), [chrome, "--no-sandbox"]) + def test_a_link_to_an_electron_app_gets_the_sandbox_flag(self): + app = self.chromium("vesktop", "vesktop") + link = self.tmp / "bin-vesktop" + link.symlink_to(app) + self.assertEqual(self.argv(str(link), "%U"), [str(link), "--no-sandbox", "%U"]) + + def test_an_app_whose_sandbox_helper_is_one_folder_up_gets_the_flag(self): + root = self.tmp / "nested" + (root / "bin").mkdir(parents=True) + (root / "chrome-sandbox").touch() + (root / "bin/app").touch() + self.assertEqual(self.argv(str(root / "bin/app")), [str(root / "bin/app"), "--no-sandbox"]) + + def test_a_chromium_app_starting_a_program_from_its_own_folder_leaves_it_alone(self): + handler = self.chromium("chrome-app", "chrome_crashpad_handler") + browser = self.tmp / "chrome-app/chrome" + shutil.copy(self.program, browser) + out = subprocess.run([str(browser), handler, "--database=/tmp/x"], env={"TEST_DISPLAY": ":0"}, + capture_output=True, text=True, check=True).stdout.splitlines() + self.assertEqual([handler, "--database=/tmp/x"], out) + + def test_a_chromium_app_starting_another_chromium_app_still_flags_it(self): + other = self.chromium("other-app", "chrome") + editor = self.tmp / "editor-app/code" + self.chromium("editor-app", "code") + shutil.copy(self.program, editor) + out = subprocess.run([str(editor), other], env={}, capture_output=True, text=True, check=True).stdout.splitlines() + self.assertEqual([other, "--no-sandbox"], out) + + def test_with_an_x_display_chromium_apps_use_x11(self): + chrome = self.chromium("chromium-x11", "chrome") + self.assertEqual(self.argv(chrome, "--new-window", display=":0"), + [chrome, "--no-sandbox", "--ozone-platform=x11", "--new-window"]) + self.assertEqual(self.argv(chrome, "--no-sandbox", display=":0"), + [chrome, "--ozone-platform=x11", "--no-sandbox"]) + + def test_an_explicit_platform_and_sandbox_choice_is_kept(self): + chrome = self.chromium("chromium-own-flags", "chrome") + own = [chrome, "--no-sandbox", "--ozone-platform=wayland"] + self.assertEqual(self.argv(*own, display=":0"), own) + + def test_other_programs_with_an_x_display_are_left_alone(self): + self.assertEqual(self.argv("/usr/bin/steam", display=":0"), ["/usr/bin/steam"]) + def test_stock_turns_it_off(self): args = [WEBHELPER, "--enable-features=A"] self.assertEqual(self.argv(*args, spec="stock"), args) diff --git a/tools/tests/test_zram_preload.py b/tools/tests/test_zram_preload.py index bf1e8391cd..8a9f813480 100644 --- a/tools/tests/test_zram_preload.py +++ b/tools/tests/test_zram_preload.py @@ -18,7 +18,14 @@ PROGRAM = r""" #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <dirent.h> +#include <linux/filter.h> +#include <linux/seccomp.h> +#include <sched.h> +#include <stddef.h> #include <sys/mman.h> +#include <sys/prctl.h> +#include <sys/resource.h> #include <sys/syscall.h> #include <sys/wait.h> #include <time.h> @@ -31,14 +38,15 @@ static unsigned char *shared; static volatile sig_atomic_t urg_tid; static volatile sig_atomic_t usr_tid; static int urg_count, usr_count; -static int worker_tid; static int worker_delivery; _Static_assert(__atomic_always_lock_free(sizeof(int), 0), "signal state must be lock-free"); static void signal_tid(int sig) { sig_atomic_t tid = (sig_atomic_t)syscall(SYS_gettid); - if (tid == __atomic_load_n(&worker_tid, __ATOMIC_RELAXED)) + char name[16] = {0}; + prctl(PR_GET_NAME, name, 0, 0, 0); + if (!strcmp(name, "zr-worker")) __atomic_store_n(&worker_delivery, 1, __ATOMIC_RELAXED); if (sig == SIGURG) { __atomic_store_n(&urg_tid, tid, __ATOMIC_RELAXED); @@ -123,6 +131,75 @@ static long trim(char mode, long kb) { exit(5); } +static int workers(void) { + DIR *dir = opendir("/proc/self/task"); + struct dirent *entry; + int count = 0; + while (dir && (entry = readdir(dir)) != NULL) { + if (entry->d_name[0] == '.') continue; + char path[64], name[32] = {0}; + snprintf(path, sizeof(path), "/proc/self/task/%s/comm", entry->d_name); + FILE *comm = fopen(path, "r"); + if (comm && fgets(name, sizeof(name), comm) && !strcmp(name, "zr-worker\n")) count++; + if (comm) fclose(comm); + } + if (dir) closedir(dir); + return count; +} + +static void without_threads(void) { + struct rlimit limit; + if (getrlimit(RLIMIT_NPROC, &limit)) _exit(15); + limit.rlim_cur = 0; + if (setrlimit(RLIMIT_NPROC, &limit)) _exit(15); +} + +static void *park(void *arg) { + (void)arg; + for (;;) pause(); + return NULL; +} + +static void parked(void) { + pthread_t thread; + sigset_t urg, previous; + sigemptyset(&urg); + sigaddset(&urg, SIGURG); + pthread_sigmask(SIG_BLOCK, &urg, &previous); + if (pthread_create(&thread, NULL, park, NULL)) _exit(16); + pthread_sigmask(SIG_SETMASK, &previous, NULL); +} + +static void filter_clone(unsigned long allowed) { + struct sock_filter rules[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_clone, 0, 3), + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, args[0])), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, allowed, 1, 0), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + }; + struct sock_fprog program = {sizeof(rules) / sizeof(rules[0]), rules}; + if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program)) _exit(17); +} + +static volatile int sandbox_ready; + +static void *sandbox(void *arg) { + (void)arg; + sigset_t urg; + sigemptyset(&urg); + sigaddset(&urg, SIGURG); + filter_clone(0); + pthread_sigmask(SIG_UNBLOCK, &urg, NULL); + sandbox_ready = 1; + for (;;) pause(); + return NULL; +} + +static const unsigned long thread_clone = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | + CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID; + static uint64_t sum(const unsigned char *p, size_t n) { uint64_t s = 0; for (size_t i = 0; i < n; i += 64) s = s * 31 + p[i]; @@ -155,6 +232,7 @@ int main(int argc, char **argv) { memset(shared, 0, size); pthread_t t[2]; for (uintptr_t i = 0; i < 2; i++) pthread_create(&t[i], NULL, writer, (void *)i); + parked(); struct sigaction sa; sigaction(SIGURG, NULL, &sa); printf("handler %d\n", (sa.sa_flags & SA_SIGINFO) ? 1 : 0); @@ -164,27 +242,21 @@ int main(int argc, char **argv) { memset(&signal_action, 0, sizeof(signal_action)); signal_action.sa_handler = signal_tid; sigemptyset(&signal_action.sa_mask); - sigaction(SIGURG, &signal_action, NULL); sigaction(SIGUSR1, &signal_action, NULL); + int fd = open(ctl, O_WRONLY | O_TRUNC); + if (fd < 0 || write(fd, "1", 1) != 1) return 10; + close(fd); printf("ready %d\n", getpid()); fflush(stdout); - int id; - if (scanf("%d", &id) != 1) return 10; - __atomic_store_n(&worker_tid, id, __ATOMIC_RELAXED); - printf("armed 1\n"); - fflush(stdout); for (int round = 1; round <= 100; round++) { int i; - for (i = 0; i < 5000 && - (__atomic_load_n(&urg_count, __ATOMIC_ACQUIRE) < round || - __atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round); i++) usleep(1000); + for (i = 0; i < 5000 && __atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round; i++) usleep(1000); if (i == 5000) return 11; printf("received %d\n", round); fflush(stdout); } stop = 1; for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); - printf("urg %d\n", __atomic_load_n(&urg_tid, __ATOMIC_RELAXED)); printf("usr %d\n", __atomic_load_n(&usr_tid, __ATOMIC_RELAXED)); printf("worker %d\n", __atomic_load_n(&worker_delivery, __ATOMIC_RELAXED)); return 0; @@ -199,6 +271,13 @@ int main(int argc, char **argv) { int status_code; waitpid(child, &status_code, 0); printf("childack %d\n", WIFEXITED(status_code) && WEXITSTATUS(status_code) == 0); + } else if (!strcmp(argv[4], "threads")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + printf("idle %d\n", workers()); + request('1'); + printf("after %d\n", workers()); + return 0; } else if (!strcmp(argv[4], "trim")) { stop = 1; for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); @@ -271,8 +350,47 @@ int main(int argc, char **argv) { _exit(0); } waitpid(child, NULL, 0); + child = fork(); + if (child < 0) exit(6); + if (child == 0) { + parked(); + without_threads(); + for (size_t i = 0; i < size; i += page) data[i]++; + printf("nothread_trim %ld\n", trim('2', 1L << 30)); + fflush(stdout); + _exit(0); + } + waitpid(child, NULL, 0); printf("worker_trim %ld\n", trim('2', 1L << 30)); return 0; + } else if (!strcmp(argv[4], "sandboxed")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + filter_clone(thread_clone); + printf("sandboxed_trim %ld\n", trim('2', 1L << 30)); + return 0; + } else if (!strcmp(argv[4], "thread-sandboxed")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + sigset_t urg; + sigemptyset(&urg); + sigaddset(&urg, SIGURG); + pthread_sigmask(SIG_BLOCK, &urg, NULL); + pthread_t thread; + if (pthread_create(&thread, NULL, sandbox, NULL)) exit(16); + while (!sandbox_ready) usleep(1000); + printf("thread_sandboxed_trim %ld\n", trim('2', 1L << 30)); + return 0; + } else if (!strcmp(argv[4], "filtered")) { + fflush(stdout); + filter_clone(thread_clone); + execl("/proc/self/exe", argv[0], argv[1], argv[2], "0", "filtered-trim", (char *)NULL); + return 18; + } else if (!strcmp(argv[4], "filtered-trim")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + printf("filtered_trim %ld\n", trim('2', 1L << 30)); + return 0; } else if (!strcmp(argv[4], "burst")) { send_request('0'); usleep(10000); @@ -283,6 +401,7 @@ int main(int argc, char **argv) { pid_t child = fork(); if (child < 0) exit(8); if (child == 0) { + without_threads(); if (!strcmp(argv[4], "timed-inline-single")) { if (munmap(data, size) || munmap(shared, size)) _exit(12); data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); @@ -431,6 +550,11 @@ class ZramPreloadTest(unittest.TestCase): self.assertEqual([1], out["intact"]) self.assertEqual(6, len(out["out"])) + def test_a_process_keeps_no_extra_thread_while_nothing_is_paged_out(self): + out = self.run_program(None, 8, 0, "threads") + self.assertEqual([0], out["idle"]) + self.assertEqual([0], out["after"]) + def test_process_signals_do_not_reach_zram_worker(self): environment = dict(os.environ, LD_PRELOAD=str(self.lib)) process = subprocess.Popen([str(self.steam), str(self.ctl), "1", "0", "signals"], @@ -439,30 +563,16 @@ class ZramPreloadTest(unittest.TestCase): process.stdout.readline() ready = process.stdout.readline().split() self.assertEqual("ready", ready[0]) - worker = None - task_dir = Path("/proc") / ready[1] / "task" - for task in task_dir.iterdir(): - if (task / "comm").read_text().strip() == "zr-worker": - worker = int(task.name) - break - self.assertIsNotNone(worker) - self.assertEqual(os.sched_getscheduler(process.pid), os.sched_getscheduler(worker)) - process.stdin.write(f"{worker}\n") - process.stdin.flush() - self.assertEqual("armed 1", process.stdout.readline().strip()) - for _ in range(100): + for round in range(100): os.kill(process.pid, signal.SIGURG) os.kill(process.pid, signal.SIGUSR1) - self.assertEqual(f"received {_ + 1}", process.stdout.readline().strip()) + self.assertEqual(f"received {round + 1}", process.stdout.readline().strip()) process.stdin.close() process.wait(timeout=10) output = process.stdout.read() values = dict(line.split() for line in output.splitlines()) - self.assertNotEqual(0, int(values["urg"])) self.assertNotEqual(0, int(values["usr"])) self.assertEqual(0, int(values["worker"])) - self.assertNotEqual(worker, int(values["urg"])) - self.assertNotEqual(worker, int(values["usr"])) finally: if process.poll() is None: process.kill() @@ -537,10 +647,33 @@ class ZramPreloadTest(unittest.TestCase): @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") def test_process_without_a_worker_trims_in_small_steps(self): + if os.geteuid() == 0: + self.skipTest("the thread limit does not apply to root") + out = self.run_program(None, 48, 0, "trim-fork") + self.assertTrue(16 * 1024 < out["nothread_trim"][0] <= 32 * 1024, out) + self.assertGreater(out["worker_trim"][0], 64 * 1024, out) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_a_single_threaded_process_trims_without_starting_a_thread(self): out = self.run_program(None, 48, 0, "trim-fork") self.assertTrue(16 * 1024 < out["inline_trim"][0] <= 32 * 1024, out) self.assertGreater(out["worker_trim"][0], 64 * 1024, out) + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_a_process_that_sandboxed_itself_trims_without_starting_a_thread(self): + out = self.run_program(None, 48, 0, "sandboxed") + self.assertTrue(16 * 1024 < out["sandboxed_trim"][0] <= 32 * 1024, out) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_a_thread_that_sandboxed_itself_trims_without_starting_a_thread(self): + out = self.run_program(None, 48, 0, "thread-sandboxed") + self.assertTrue(16 * 1024 < out["thread_sandboxed_trim"][0] <= 32 * 1024, out) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_the_worker_passes_a_filter_that_only_allows_thread_clones(self): + out = self.run_program(None, 48, 0, "filtered") + self.assertGreater(out["filtered_trim"][0], 40 * 1024, out) + def test_worker_acknowledges_back_to_back_requests(self): out = self.run_program(None, 48, 0, "burst") self.assertEqual([1], out["burstack"]) diff --git a/tools/tests/vk_linear_dmabuf_test.c b/tools/tests/vk_linear_dmabuf_test.c new file mode 100644 index 0000000000..380dfa5c16 --- /dev/null +++ b/tools/tests/vk_linear_dmabuf_test.c @@ -0,0 +1,124 @@ +#include <assert.h> +#include <stdint.h> +#include <string.h> + +#include "vk_linear_dmabuf.h" + +static void check_padded_rows(void) { + VkBufferImageCopy copy; + memset(©, 0xa5, sizeof(copy)); + const VkDeviceSize need = vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6400, 0, ©); + assert(copy.bufferRowLength == 1600); + assert(copy.bufferRowLength != 1560); + assert(copy.bufferOffset == 0); + assert(copy.bufferImageHeight == 720); + assert(copy.imageSubresource.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT); + assert(copy.imageSubresource.mipLevel == 0); + assert(copy.imageSubresource.baseArrayLayer == 0); + assert(copy.imageSubresource.layerCount == 1); + assert(copy.imageOffset.x == 0 && copy.imageOffset.y == 0 && copy.imageOffset.z == 0); + assert(copy.imageExtent.width == 1560); + assert(copy.imageExtent.height == 720); + assert(copy.imageExtent.depth == 1); + assert(need == (VkDeviceSize)6400 * 719 + 1560 * 4); +} + +static void check_offset_and_wide_texels(void) { + VkBufferImageCopy copy; + const VkDeviceSize need = vkp_linear_dmabuf_copy(VK_FORMAT_R16G16B16A16_SFLOAT, 1920, 1080, 15360, 4096, ©); + assert(copy.bufferRowLength == 1920); + assert(copy.bufferOffset == 4096); + assert(need == 4096 + (VkDeviceSize)15360 * 1079 + 1920 * 8); + + assert(vkp_linear_dmabuf_copy(VK_FORMAT_B8G8R8A8_UNORM, 1, 1, 64, 0, ©) == 4); + assert(copy.bufferRowLength == 16); +} + +static void check_rejected_layouts(void) { + VkBufferImageCopy copy; + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6236, 0, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6402, 0, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6400, 2, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R16G16B16A16_SFLOAT, 1560, 720, 6240, 0, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 0, 720, 6400, 0, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 0, 6400, 0, ©) == 0); + assert(vkp_linear_dmabuf_copy(VK_FORMAT_R8G8B8A8_UNORM, 1560, 720, 6400, 0, NULL) == 0); +} + +static void check_path_choice(void) { + const uint64_t linear = 0; + const uint64_t qcom_compressed = 0x0500000000000001ULL; + assert(vkp_linear_dmabuf_through_buffer(0, linear, 0)); + assert(!vkp_linear_dmabuf_through_buffer(1, linear, 0)); + assert(!vkp_linear_dmabuf_through_buffer(1, qcom_compressed, 0)); + assert(!vkp_linear_dmabuf_through_buffer(0, qcom_compressed, 0)); + assert(!vkp_linear_dmabuf_through_buffer(0, linear, 1)); + assert(!vkp_linear_dmabuf_through_buffer(1, linear, 1)); +} + +static void check_foreign_image(void) { + assert(vkp_linear_dmabuf_foreign_image(1, 0)); + assert(!vkp_linear_dmabuf_foreign_image(1, 1)); + assert(!vkp_linear_dmabuf_foreign_image(0, 0)); + assert(!vkp_linear_dmabuf_foreign_image(0, 1)); +} + +static void check_padded_layer_targets(void) { + const VkFormat rgba = VK_FORMAT_R8G8B8A8_UNORM; + const uint64_t qcom_compressed = 0x0500000000000001ULL; + assert(vkp_padded_linear_target_needs_layout(0, 0, rgba, 720, 3072, 0)); + assert(vkp_padded_linear_target_needs_layout(0, 0, rgba, 720, 2880, 64)); + assert(!vkp_padded_linear_target_needs_layout(0, 0, rgba, 1280, 5120, 0)); + assert(!vkp_padded_linear_target_needs_layout(1, 0, rgba, 720, 3072, 0)); + assert(!vkp_padded_linear_target_needs_layout(0, qcom_compressed, rgba, 720, 3072, 0)); +} + +static void check_readback_order(void) { + assert(vkp_linear_dmabuf_readback_stage(1) & VK_PIPELINE_STAGE_TRANSFER_BIT); + assert(vkp_linear_dmabuf_readback_access(1) & VK_ACCESS_TRANSFER_WRITE_BIT); + assert(vkp_linear_dmabuf_readback_stage(0) == VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT); + assert(vkp_linear_dmabuf_readback_access(0) == 0); +} + +static void check_ownership(void) { + const VkBuffer buffer = (VkBuffer)(uintptr_t)0x4321; + const uint32_t queue_family = 3; + const VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_READ_BIT, 1); + assert(acquire.sType == VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER); + assert(acquire.pNext == NULL); + assert(acquire.srcQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT); + assert(acquire.dstQueueFamilyIndex == queue_family); + assert(acquire.srcAccessMask == 0); + assert(acquire.dstAccessMask == VK_ACCESS_TRANSFER_READ_BIT); + assert(acquire.buffer == buffer); + assert(acquire.offset == 0); + assert(acquire.size == VK_WHOLE_SIZE); + + const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_READ_BIT, 0); + assert(release.sType == VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER); + assert(release.srcQueueFamilyIndex == queue_family); + assert(release.dstQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT); + assert(release.srcAccessMask == VK_ACCESS_TRANSFER_READ_BIT); + assert(release.dstAccessMask == 0); + assert(release.buffer == buffer); + assert(release.size == VK_WHOLE_SIZE); + + const VkBufferMemoryBarrier write = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_WRITE_BIT, 1); + const VkBufferMemoryBarrier written = vkp_linear_dmabuf_ownership(buffer, queue_family, VK_ACCESS_TRANSFER_WRITE_BIT, 0); + assert(write.srcQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT); + assert(write.dstAccessMask == VK_ACCESS_TRANSFER_WRITE_BIT); + assert(written.dstQueueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT); + assert(written.srcAccessMask == VK_ACCESS_TRANSFER_WRITE_BIT); +} + +int main(void) { + check_padded_rows(); + check_offset_and_wide_texels(); + check_rejected_layouts(); + check_path_choice(); + check_padded_layer_targets(); + check_foreign_image(); + check_readback_order(); + check_ownership(); + return 0; +} diff --git a/tools/tests/vk_terminal_callers_test.c b/tools/tests/vk_terminal_callers_test.c index 2398608bd2..374c049a6f 100644 --- a/tools/tests/vk_terminal_callers_test.c +++ b/tools/tests/vk_terminal_callers_test.c @@ -110,7 +110,7 @@ struct damage_list { int n; }; struct surface { struct vkp_image *shm_img; struct wl_resource *resource; - int buf_w, buf_h, buf_alpha, has_content; + int buf_w, buf_h, buf_alpha, has_content, black_fill; /* Read by take_shm's game-frame detection; with no damage it stays off here. */ int src_set; float src[4]; struct damage_list damage_buf, damage_local; @@ -123,7 +123,8 @@ static int64_t now_ns(void) { return 0; } static struct surface *g_hud_surface, *g_hud_shm; static int64_t g_hud_shm_ns, g_hud_last_ns; static int g_hud_new; -static void droiddeck_on_game_frame(void) {} +static void __attribute__((unused)) droiddeck_on_game_frame(void) {} +static void __attribute__((unused)) droiddeck_on_compositor_frame(void) {} struct client_info { int asked_feedback, shm_frames; }; struct wl_shm_buffer { int w, h, stride; const void *data; }; #define WL_SHM_FORMAT_ARGB8888 0 diff --git a/tools/venus/layer/bc.c b/tools/venus/layer/bc.c index 328b68169d..3948126fd1 100644 --- a/tools/venus/layer/bc.c +++ b/tools/venus/layer/bc.c @@ -799,7 +799,11 @@ static void recycle_command_buffer(struct device *dev, VkCommandBuffer cmd) VKAPI_ATTR VkResult VKAPI_CALL BeginCommandBuffer(VkCommandBuffer cmd, const VkCommandBufferBeginInfo *info) { struct device *dev = device_from_handle(cmd); - recycle_command_buffer(dev, cmd); + if (dev->emulated & GAP_BC) + recycle_command_buffer(dev, cmd); + /* Dynamic state does not carry over from one recording to the next. */ + if (dev->emulated & GAP_DEPTH_OP) + depth_state_forget(dev, cmd); return dev->BeginCommandBuffer(cmd, info); } diff --git a/tools/venus/layer/draw.c b/tools/venus/layer/draw.c index f3621355b2..5d0dc4a13e 100644 --- a/tools/venus/layer/draw.c +++ b/tools/venus/layer/draw.c @@ -8,6 +8,8 @@ * stand-ins the layer owns. robustBufferAccess2 itself maps to robustBufferAccess (layer.c). * A null texel-buffer view gets an RGBA8 (uniform) or R32_UINT (storage) view of the stand-in * buffer: its format is not known here, but Zink leaves them unbound and never reads them. + * - depthCompareOp with the depth test off (GAP_DEPTH_OP): the driver is given ALWAYS while a + * command buffer has the test off, and the application's op again once it turns the test on. */ #include <stdlib.h> #include <string.h> @@ -450,3 +452,49 @@ VKAPI_ATTR void VKAPI_CALL CmdBindVertexBuffers2(VkCommandBuffer cmd, uint32_t f } dev->CmdBindVertexBuffers2(cmd, first, count, fixed, fixed_offsets, sizes ? fixed_sizes : NULL, strides); } + +/* --- depthCompareOp while the depth test is off --- */ + +/* Per command buffer, packed into the map's value pointer so it is never NULL: bit 0 always set, + * bit 1 the test enable is known, bit 2 the test is on, bit 3 an op was set, bits 4 and up that op. */ +enum { DEPTH_VALID = 1, DEPTH_KNOWN = 2, DEPTH_ON = 4, DEPTH_OP = 8 }; + +static uintptr_t depth_state(struct device *dev, VkCommandBuffer cmd) +{ + uintptr_t state = (uintptr_t)map_get(&dev->depth_states, (uint64_t)(uintptr_t)cmd); + return state ? state : DEPTH_VALID; +} + +void depth_state_forget(struct device *dev, VkCommandBuffer cmd) +{ + pthread_mutex_lock(&dev->lock); + map_remove(&dev->depth_states, (uint64_t)(uintptr_t)cmd); + pthread_mutex_unlock(&dev->lock); +} + +VKAPI_ATTR void VKAPI_CALL CmdSetDepthTestEnable(VkCommandBuffer cmd, VkBool32 enable) +{ + struct device *dev = device_from_handle(cmd); + dev->CmdSetDepthTestEnable(cmd, enable); + pthread_mutex_lock(&dev->lock); + uintptr_t state = depth_state(dev, cmd); + uintptr_t next = (state & ~(uintptr_t)DEPTH_ON) | DEPTH_KNOWN | (enable ? DEPTH_ON : 0); + map_put(&dev->depth_states, (uint64_t)(uintptr_t)cmd, (void *)next); + pthread_mutex_unlock(&dev->lock); + if (!enable) + dev->CmdSetDepthCompareOp(cmd, VK_COMPARE_OP_ALWAYS); + else if (state & DEPTH_OP) + dev->CmdSetDepthCompareOp(cmd, (VkCompareOp)(state >> 4)); +} + +VKAPI_ATTR void VKAPI_CALL CmdSetDepthCompareOp(VkCommandBuffer cmd, VkCompareOp op) +{ + struct device *dev = device_from_handle(cmd); + pthread_mutex_lock(&dev->lock); + uintptr_t state = depth_state(dev, cmd); + uintptr_t next = (state & (uintptr_t)(DEPTH_VALID | DEPTH_KNOWN | DEPTH_ON)) | DEPTH_OP | ((uintptr_t)op << 4); + map_put(&dev->depth_states, (uint64_t)(uintptr_t)cmd, (void *)next); + pthread_mutex_unlock(&dev->lock); + bool off = (state & DEPTH_KNOWN) && !(state & DEPTH_ON); + dev->CmdSetDepthCompareOp(cmd, off ? VK_COMPARE_OP_ALWAYS : op); +} diff --git a/tools/venus/layer/layer.c b/tools/venus/layer/layer.c index 2f1e7ccd7d..9aeb0bcf0e 100644 --- a/tools/venus/layer/layer.c +++ b/tools/venus/layer/layer.c @@ -60,9 +60,11 @@ static uint64_t hash(uint64_t key) return key; } +/* Key 0 marks an empty slot, so VK_NULL_HANDLE is never looked up, stored or removed. Destroying a + * null handle is valid Vulkan, and map_remove(0) would otherwise match an empty slot and drop count. */ void *map_get(const struct handle_map *map, uint64_t key) { - if (!map->capacity) + if (!map->capacity || !key) return NULL; for (uint32_t i = hash(key) & (map->capacity - 1);; i = (i + 1) & (map->capacity - 1)) { if (map->keys[i] == key) @@ -90,6 +92,8 @@ static void map_grow(struct handle_map *map) void map_put(struct handle_map *map, uint64_t key, void *value) { + if (!key) + return; if ((map->count + 1) * 4 > map->capacity * 3) map_grow(map); uint32_t i = hash(key) & (map->capacity - 1); @@ -103,7 +107,7 @@ void map_put(struct handle_map *map, uint64_t key, void *value) void *map_remove(struct handle_map *map, uint64_t key) { - if (!map->capacity) + if (!map->capacity || !key) return NULL; uint32_t mask = map->capacity - 1; uint32_t i = hash(key) & mask; @@ -602,7 +606,7 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev dev->key = dispatch_key(*device); dev->handle = *device; dev->gdpa = gdpa; - dev->emulated = requested; + dev->emulated = requested | (gaps ? GAP_DEPTH_OP : 0); pthread_mutex_init(&dev->lock, NULL); #define LOAD(name) \ dev->name = (PFN_vk##name)gdpa(*device, "vk" #name); \ @@ -615,6 +619,7 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev inst->GetPhysicalDeviceMemoryProperties(physical_device, &dev->memory_properties); VkPhysicalDeviceProperties properties; inst->GetPhysicalDeviceProperties(physical_device, &properties); + dev->active = inst->active && (requested != 0 || properties.apiVersion >= VK_API_VERSION_1_2); uint32_t components = properties.limits.maxVertexOutputComponents; if (properties.limits.maxFragmentInputComponents < components) components = properties.limits.maxFragmentInputComponents; @@ -637,6 +642,8 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev (requested & GAP_NULL_DESCRIPTOR) ? " nullDescriptor" : "", (requested & GAP_DUAL_SRC_BLEND) ? " dualSrcBlend" : "", properties.deviceName); } + if (dev->emulated & GAP_DEPTH_OP) + layer_log("depthCompareOp becomes ALWAYS while the depth test is off"); return VK_SUCCESS; } @@ -664,6 +671,7 @@ static VKAPI_ATTR void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocat } } map_free(&dev->shader_modules); + map_free(&dev->depth_states); pthread_mutex_destroy(&dev->lock); free(dev); } @@ -672,15 +680,18 @@ struct hook { const char *name; PFN_vkVoidFunction function; uint32_t gaps; + bool always; }; -#define HOOK(name, gaps) {"vk" #name, (PFN_vkVoidFunction)name, gaps} -#define HOOK_ALIAS(name, alias, gaps) {"vk" #alias, (PFN_vkVoidFunction)name, gaps} +#define HOOK(name, gaps) {"vk" #name, (PFN_vkVoidFunction)name, gaps, false} +#define HOOK_ALIAS(name, alias, gaps) {"vk" #alias, (PFN_vkVoidFunction)name, gaps, false} +#define HOOK_ALWAYS(name) {"vk" #name, (PFN_vkVoidFunction)name, 0, true} static const struct hook device_hooks[] = { - HOOK(CreateShaderModule, GAPS_SHADER | GAP_DUAL_SRC_BLEND), - HOOK(DestroyShaderModule, GAPS_SHADER | GAP_DUAL_SRC_BLEND), - HOOK(CreateGraphicsPipelines, GAPS_PIPELINE), + HOOK_ALWAYS(CreateShaderModule), + HOOK_ALWAYS(DestroyShaderModule), + HOOK_ALWAYS(CreateGraphicsPipelines), + HOOK_ALWAYS(CreateComputePipelines), HOOK(CmdSetViewport, GAP_MULTI_VIEWPORT), HOOK(CmdSetScissor, GAP_MULTI_VIEWPORT), HOOK(CmdSetViewportWithCount, GAP_MULTI_VIEWPORT), @@ -688,6 +699,10 @@ static const struct hook device_hooks[] = { HOOK(CmdSetScissorWithCount, GAP_MULTI_VIEWPORT), HOOK_ALIAS(CmdSetScissorWithCount, CmdSetScissorWithCountEXT, GAP_MULTI_VIEWPORT), HOOK(CmdSetColorBlendEquationEXT, GAP_DUAL_SRC_BLEND), + HOOK(CmdSetDepthTestEnable, GAP_DEPTH_OP), + HOOK_ALIAS(CmdSetDepthTestEnable, CmdSetDepthTestEnableEXT, GAP_DEPTH_OP), + HOOK(CmdSetDepthCompareOp, GAP_DEPTH_OP), + HOOK_ALIAS(CmdSetDepthCompareOp, CmdSetDepthCompareOpEXT, GAP_DEPTH_OP), HOOK(CreateImage, GAP_BC), HOOK(DestroyImage, GAP_BC), HOOK(CreateImageView, GAP_BC), @@ -719,7 +734,7 @@ static const struct hook device_hooks[] = { HOOK_ALIAS(UnmapMemory2, UnmapMemory2KHR, GAP_BC), HOOK(AllocateCommandBuffers, GAP_BC), HOOK(FreeCommandBuffers, GAP_BC), - HOOK(BeginCommandBuffer, GAP_BC), + HOOK(BeginCommandBuffer, GAP_BC | GAP_DEPTH_OP), HOOK(ResetCommandBuffer, GAP_BC), HOOK(ResetCommandPool, GAP_BC), HOOK(DestroyCommandPool, GAP_BC), @@ -756,7 +771,8 @@ static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice devic if (!next) return NULL; for (size_t i = 0; i < sizeof(device_hooks) / sizeof(device_hooks[0]); i++) { - if ((dev->emulated & device_hooks[i].gaps) && !strcmp(name, device_hooks[i].name)) + bool installed = device_hooks[i].always ? dev->active : (dev->emulated & device_hooks[i].gaps) != 0; + if (installed && !strcmp(name, device_hooks[i].name)) return device_hooks[i].function; } return next; diff --git a/tools/venus/layer/mali_compat.h b/tools/venus/layer/mali_compat.h index a785eaff4a..073907f41a 100644 --- a/tools/venus/layer/mali_compat.h +++ b/tools/venus/layer/mali_compat.h @@ -30,6 +30,10 @@ enum gap { GAP_DEPTH_CLIP = 1u << 7, /* VK_EXT_depth_clip_enable: depthClipEnable off becomes depth clamp */ GAP_NULL_DESCRIPTOR = 1u << 8, /* VK_EXT_robustness2 missing entirely: nullDescriptor stand-ins */ GAP_DUAL_SRC_BLEND = 1u << 9, + /* A driver bug, not a missing feature: the Mali-G610 driver behind Venus applies depthCompareOp + * with the depth test off, so Zink's NEVER discards every fragment. On for every device with + * gaps; ALWAYS for a disabled test changes nothing on a driver that follows the spec. */ + GAP_DEPTH_OP = 1u << 10, }; #define GAPS_SHADER (GAP_CLIP_DISTANCE | GAP_CULL_DISTANCE) @@ -89,6 +93,7 @@ struct instance { X(CreateShaderModule) \ X(DestroyShaderModule) \ X(CreateGraphicsPipelines) \ + X(CreateComputePipelines) \ X(CmdSetViewport) \ X(CmdSetScissor) \ X(CmdSetViewportWithCount) \ @@ -137,7 +142,9 @@ struct instance { X(CmdPushDescriptorSetWithTemplate) \ X(CmdBindVertexBuffers) \ X(CmdBindVertexBuffers2) \ - X(CmdSetColorBlendEquationEXT) + X(CmdSetColorBlendEquationEXT) \ + X(CmdSetDepthTestEnable) \ + X(CmdSetDepthCompareOp) struct staging_block; @@ -145,6 +152,7 @@ struct device { void *key; VkDevice handle; PFN_vkGetDeviceProcAddr gdpa; + bool active; /* The gaps the application enabled a made-up feature for. */ uint32_t emulated; /* Locations a clip distance varying may use, from the vertex output and fragment input limits. */ @@ -161,6 +169,7 @@ struct device { struct handle_map command_buffers; /* VkCommandBuffer -> struct command_buffer */ struct staging_block *free_staging; struct handle_map templates; /* VkDescriptorUpdateTemplate -> struct template_info (draw.c) */ + struct handle_map depth_states; /* VkCommandBuffer -> packed depth test state (draw.c) */ /* nullDescriptor stand-ins (draw.c): 0 not made yet, 1 ready, -1 failed. */ int null_ready; VkBuffer null_buffer; @@ -185,6 +194,8 @@ struct spirv_code { bool spirv_uses_distances(const uint32_t *words, size_t count); /* The module with clip and cull distances taken out; false when it cannot be rewritten. */ bool spirv_strip_distances(const uint32_t *words, size_t count, struct spirv_code *out); +uint32_t spirv_version(const uint32_t *words, size_t count); +bool spirv_cap_version(const uint32_t *words, size_t count, struct spirv_code *out); bool spirv_uses_dual_source(const uint32_t *words, size_t count); bool spirv_strip_dual_source(const uint32_t *words, size_t count, struct spirv_code *out); @@ -213,6 +224,9 @@ VKAPI_ATTR void VKAPI_CALL DestroyShaderModule(VkDevice device, VkShaderModule m VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelines(VkDevice device, VkPipelineCache cache, uint32_t count, const VkGraphicsPipelineCreateInfo *infos, const VkAllocationCallbacks *allocator, VkPipeline *pipelines); +VKAPI_ATTR VkResult VKAPI_CALL CreateComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t count, + const VkComputePipelineCreateInfo *infos, + const VkAllocationCallbacks *allocator, VkPipeline *pipelines); VKAPI_ATTR void VKAPI_CALL CmdSetViewport(VkCommandBuffer cmd, uint32_t first, uint32_t count, const VkViewport *viewports); VKAPI_ATTR void VKAPI_CALL CmdSetScissor(VkCommandBuffer cmd, uint32_t first, uint32_t count, @@ -304,4 +318,7 @@ VKAPI_ATTR void VKAPI_CALL CmdPushDescriptorSetWithTemplate(VkCommandBuffer cmd, VKAPI_ATTR void VKAPI_CALL CmdBindVertexBuffers(VkCommandBuffer cmd, uint32_t first, uint32_t count, const VkBuffer *buffers, const VkDeviceSize *offsets); VKAPI_ATTR void VKAPI_CALL CmdBindVertexBuffers2(VkCommandBuffer cmd, uint32_t first, uint32_t count, const VkBuffer *buffers, const VkDeviceSize *offsets, const VkDeviceSize *sizes, const VkDeviceSize *strides); void null_resources_destroy(struct device *dev); +VKAPI_ATTR void VKAPI_CALL CmdSetDepthTestEnable(VkCommandBuffer cmd, VkBool32 enable); +VKAPI_ATTR void VKAPI_CALL CmdSetDepthCompareOp(VkCommandBuffer cmd, VkCompareOp op); +void depth_state_forget(struct device *dev, VkCommandBuffer cmd); #endif diff --git a/tools/venus/layer/pipeline.c b/tools/venus/layer/pipeline.c index 906ef27d26..01236be5b7 100644 --- a/tools/venus/layer/pipeline.c +++ b/tools/venus/layer/pipeline.c @@ -5,6 +5,13 @@ #define HANDLE(h) ((uint64_t)(uintptr_t)(h)) #define MAX_STAGES 8 +#define MAX_LINKS 8 + +static void log_spirv_version(const char *what, const uint32_t *words, size_t count) +{ + uint32_t version = spirv_version(words, count); + layer_log("shader module: SPIR-V %u.%u %s (%zu words)", (version >> 16) & 0xff, (version >> 8) & 0xff, what, count); +} /* A module with distances goes to the driver without them; its original stays here, for the * pipeline that can emulate its clip distances. */ @@ -12,49 +19,57 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateShaderModule(VkDevice device, const VkShade const VkAllocationCallbacks *allocator, VkShaderModule *module) { struct device *dev = device_from_handle(device); - VkShaderModuleCreateInfo copy = *info; size_t count = info->codeSize / sizeof(uint32_t); + struct spirv_code capped = {0}; + bool have_capped = spirv_cap_version(info->pCode, count, &capped); + if (have_capped) + log_spirv_version("lowered to 1.3", info->pCode, count); + else if (spirv_version(info->pCode, count) > 0x00010300u) + log_spirv_version("left as it is", info->pCode, count); + const uint32_t *code = have_capped ? capped.words : info->pCode; + size_t words = have_capped ? capped.count : count; + struct spirv_code single = {0}; - if ((dev->emulated & GAP_DUAL_SRC_BLEND) && spirv_uses_dual_source(info->pCode, count)) { - if (spirv_strip_dual_source(info->pCode, count, &single)) { - copy.pCode = single.words; - copy.codeSize = single.count * sizeof(uint32_t); - count = single.count; + if ((dev->emulated & GAP_DUAL_SRC_BLEND) && spirv_uses_dual_source(code, words)) { + if (spirv_strip_dual_source(code, words, &single)) { + code = single.words; + words = single.count; } else { layer_log("could not take the second blend source out of a shader module"); } } - if (!(dev->emulated & GAPS_SHADER) || !spirv_uses_distances(copy.pCode, count)) { - VkResult result = dev->CreateShaderModule(device, ©, allocator, module); - free(single.words); - return result; - } - struct spirv_code stripped; - if (!spirv_strip_distances(copy.pCode, count, &stripped)) { - layer_log("could not take the clip and cull distances out of a shader module"); - VkResult result = dev->CreateShaderModule(device, ©, allocator, module); - free(single.words); - return result; + struct spirv_code stripped = {0}; + bool have_stripped = false; + if ((dev->emulated & GAPS_SHADER) && spirv_uses_distances(code, words)) { + have_stripped = spirv_strip_distances(code, words, &stripped); + if (!have_stripped) + layer_log("could not take the clip and cull distances out of a shader module"); } - struct spirv_code *original = malloc(sizeof(*original)); - original->count = count; - original->words = malloc(copy.codeSize); - memcpy(original->words, copy.pCode, copy.codeSize); - free(single.words); - copy.pCode = stripped.words; - copy.codeSize = stripped.count * sizeof(uint32_t); + if (!have_stripped && code == info->pCode) + return dev->CreateShaderModule(device, info, allocator, module); + + VkShaderModuleCreateInfo copy = *info; + copy.pCode = have_stripped ? stripped.words : code; + copy.codeSize = (have_stripped ? stripped.count : words) * sizeof(uint32_t); VkResult result = dev->CreateShaderModule(device, ©, allocator, module); - free(stripped.words); - if (result != VK_SUCCESS) { - free(original->words); - free(original); + if (result != VK_SUCCESS || !have_stripped) { + free(capped.words); + free(single.words); + free(stripped.words); return result; } + struct spirv_code *original = malloc(sizeof(*original)); + original->count = words; + original->words = malloc(words * sizeof(uint32_t)); + memcpy(original->words, code, words * sizeof(uint32_t)); pthread_mutex_lock(&dev->lock); map_put(&dev->shader_modules, HANDLE(*module), original); pthread_mutex_unlock(&dev->lock); + free(capped.words); + free(single.words); + free(stripped.words); return VK_SUCCESS; } @@ -76,9 +91,10 @@ struct stage_code { const uint32_t *words; size_t count; /* The application's own, when the code comes inline in the stage. */ - VkShaderModuleCreateInfo *inline_info; + const VkShaderModuleCreateInfo *inline_info; /* A module whose distances were already taken out at creation. */ bool stripped_module; + struct spirv_code capped; }; static void find_stage_code(struct device *dev, const VkPipelineShaderStageCreateInfo *stage, struct stage_code *code) @@ -86,9 +102,16 @@ static void find_stage_code(struct device *dev, const VkPipelineShaderStageCreat memset(code, 0, sizeof(*code)); for (const VkBaseInStructure *s = stage->pNext; s; s = s->pNext) { if (s->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) { - code->inline_info = (VkShaderModuleCreateInfo *)s; + code->inline_info = (const VkShaderModuleCreateInfo *)s; code->words = code->inline_info->pCode; code->count = code->inline_info->codeSize / sizeof(uint32_t); + if (spirv_cap_version(code->words, code->count, &code->capped)) { + log_spirv_version("lowered to 1.3", code->words, code->count); + code->words = code->capped.words; + code->count = code->capped.count; + } else if (spirv_version(code->words, code->count) > 0x00010300u) { + log_spirv_version("left as it is", code->words, code->count); + } return; } } @@ -104,6 +127,15 @@ static void find_stage_code(struct device *dev, const VkPipelineShaderStageCreat } } +union stage_link { + VkBaseInStructure base; + VkDebugUtilsObjectNameInfoEXT name; + VkPipelineRobustnessCreateInfo robustness; + VkPipelineShaderStageModuleIdentifierCreateInfoEXT identifier; + VkPipelineShaderStageRequiredSubgroupSizeCreateInfo subgroup; + VkShaderModuleValidationCacheCreateInfoEXT validation_cache; +}; + struct pipeline_rewrite { VkPipelineRasterizationStateCreateInfo rasterization; VkPipelineColorBlendStateCreateInfo blend; @@ -111,17 +143,77 @@ struct pipeline_rewrite { /* VK_EXT_depth_clip_enable's state, taken out of the application's chain for the call. */ VkBaseOutStructure *clip_prev, *clip_node; VkPipelineViewportStateCreateInfo viewport; + VkPipelineDepthStencilStateCreateInfo depth_stencil; VkPipelineShaderStageCreateInfo stages[MAX_STAGES]; VkShaderModuleCreateInfo modules[MAX_STAGES]; struct spirv_code code[MAX_STAGES]; struct spirv_code single[MAX_STAGES]; VkShaderModule temporary[MAX_STAGES]; - /* Rewritten where they are, when they are not first in their stage's chain. */ - VkShaderModuleCreateInfo *in_place[MAX_STAGES]; - const uint32_t *in_place_code[MAX_STAGES]; - size_t in_place_size[MAX_STAGES]; + union stage_link links[MAX_STAGES][MAX_LINKS]; }; +static size_t link_size(VkStructureType type) +{ + switch (type) { + case VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT: + return sizeof(VkDebugUtilsObjectNameInfoEXT); + case VK_STRUCTURE_TYPE_PIPELINE_ROBUSTNESS_CREATE_INFO: + return sizeof(VkPipelineRobustnessCreateInfo); + case VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_MODULE_IDENTIFIER_CREATE_INFO_EXT: + return sizeof(VkPipelineShaderStageModuleIdentifierCreateInfoEXT); + case VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO: + return sizeof(VkPipelineShaderStageRequiredSubgroupSizeCreateInfo); + case VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT: + return sizeof(VkShaderModuleValidationCacheCreateInfoEXT); + default: + return 0; + } +} + +static bool link_inline_code(VkPipelineShaderStageCreateInfo *stage, struct pipeline_rewrite *rw, + const struct stage_code *code, uint32_t i) +{ + union stage_link *links = rw->links[i]; + const VkBaseInStructure **next = (const VkBaseInStructure **)&stage->pNext; + uint32_t used = 0; + for (const VkBaseInStructure *s = stage->pNext; s != (const VkBaseInStructure *)code->inline_info; + s = s->pNext) { + size_t size = link_size(s->sType); + if (!size || used == MAX_LINKS) + return false; + memcpy(&links[used], s, size); + *next = &links[used].base; + next = (const VkBaseInStructure **)&links[used].base.pNext; + used++; + } + rw->modules[i] = *code->inline_info; + rw->modules[i].pCode = rw->code[i].words; + rw->modules[i].codeSize = rw->code[i].count * sizeof(uint32_t); + *next = (const VkBaseInStructure *)&rw->modules[i]; + return true; +} + +static void use_stage_code(struct device *dev, VkPipelineShaderStageCreateInfo *stage, struct pipeline_rewrite *rw, + const struct stage_code *code, uint32_t i) +{ + const struct spirv_code *out = &rw->code[i]; + if (code->inline_info) { + const void *app_chain = stage->pNext; + if (!link_inline_code(stage, rw, code, i)) { + stage->pNext = app_chain; + layer_log("could not rewrite a pipeline stage's inline shader code"); + } + } else { + VkShaderModuleCreateInfo module_info = { + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = out->count * sizeof(uint32_t), + .pCode = out->words, + }; + if (dev->CreateShaderModule(dev->handle, &module_info, NULL, &rw->temporary[i]) == VK_SUCCESS) + stage->module = rw->temporary[i]; + } +} + static void use_code(struct device *dev, VkGraphicsPipelineCreateInfo *info, struct pipeline_rewrite *rw, const struct stage_code *code, uint32_t i) { @@ -129,27 +221,7 @@ static void use_code(struct device *dev, VkGraphicsPipelineCreateInfo *info, str memcpy(rw->stages, info->pStages, info->stageCount * sizeof(*rw->stages)); info->pStages = rw->stages; } - const struct spirv_code *out = &rw->code[i]; - if (code->inline_info && rw->stages[i].pNext == code->inline_info) { - rw->modules[i] = *code->inline_info; - rw->modules[i].pCode = out->words; - rw->modules[i].codeSize = out->count * sizeof(uint32_t); - rw->stages[i].pNext = &rw->modules[i]; - } else if (code->inline_info) { - rw->in_place[i] = code->inline_info; - rw->in_place_code[i] = code->inline_info->pCode; - rw->in_place_size[i] = code->inline_info->codeSize; - code->inline_info->pCode = out->words; - code->inline_info->codeSize = out->count * sizeof(uint32_t); - } else { - VkShaderModuleCreateInfo module_info = { - .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, - .codeSize = out->count * sizeof(uint32_t), - .pCode = out->words, - }; - if (dev->CreateShaderModule(dev->handle, &module_info, NULL, &rw->temporary[i]) == VK_SUCCESS) - rw->stages[i].module = rw->temporary[i]; - } + use_stage_code(dev, &rw->stages[i], rw, code, i); } static int stage_index(const VkGraphicsPipelineCreateInfo *info, VkShaderStageFlagBits stage) @@ -174,6 +246,7 @@ static void rewrite_shaders(struct device *dev, VkGraphicsPipelineCreateInfo *in struct stage_code code[MAX_STAGES]; bool uses[MAX_STAGES]; bool any = false; + bool distances = (dev->emulated & GAPS_SHADER) != 0; for (uint32_t i = 0; i < n; i++) { find_stage_code(dev, &info->pStages[i], &code[i]); if ((dev->emulated & GAP_DUAL_SRC_BLEND) && code[i].inline_info && @@ -185,40 +258,40 @@ static void rewrite_shaders(struct device *dev, VkGraphicsPipelineCreateInfo *in layer_log("could not take the second blend source out of a pipeline's shader"); } } - uses[i] = (dev->emulated & GAPS_SHADER) && code[i].words && spirv_uses_distances(code[i].words, code[i].count); - any |= uses[i] || rw->single[i].words; + uses[i] = distances && code[i].words && spirv_uses_distances(code[i].words, code[i].count); + any |= uses[i]; } - if (!any) - return; - int producer = stage_index(info, VK_SHADER_STAGE_GEOMETRY_BIT); - if (producer < 0) - producer = stage_index(info, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT); - if (producer < 0) - producer = stage_index(info, VK_SHADER_STAGE_VERTEX_BIT); - int consumer = stage_index(info, VK_SHADER_STAGE_FRAGMENT_BIT); - bool emulate = (dev->emulated & GAP_CLIP_DISTANCE) && producer >= 0 && consumer >= 0 && uses[producer] && - code[consumer].words; - for (uint32_t i = 0; i < n && emulate; i++) { - if ((int)i != producer && (int)i != consumer && uses[i]) - emulate = false; - } - if (emulate) { - struct clip_info produced, consumed; - spirv_clip_info(code[producer].words, code[producer].count, CLIP_PRODUCER, &produced); - spirv_clip_info(code[consumer].words, code[consumer].count, CLIP_CONSUMER, &consumed); - uint32_t location = produced.locations_used > consumed.locations_used ? produced.locations_used - : consumed.locations_used; - emulate = produced.has_clip && location != UINT32_MAX && - location + produced.clip_count <= dev->max_varying_locations && - spirv_emulate_clip(code[producer].words, code[producer].count, CLIP_PRODUCER, location, - produced.clip_count, &rw->code[producer]) && - spirv_emulate_clip(code[consumer].words, code[consumer].count, CLIP_CONSUMER, location, - produced.clip_count, &rw->code[consumer]); - if (!emulate) { - free(rw->code[producer].words); - free(rw->code[consumer].words); - rw->code[producer] = rw->code[consumer] = (struct spirv_code){0}; + if (any) { + int producer = stage_index(info, VK_SHADER_STAGE_GEOMETRY_BIT); + if (producer < 0) + producer = stage_index(info, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT); + if (producer < 0) + producer = stage_index(info, VK_SHADER_STAGE_VERTEX_BIT); + int consumer = stage_index(info, VK_SHADER_STAGE_FRAGMENT_BIT); + bool emulate = (dev->emulated & GAP_CLIP_DISTANCE) && producer >= 0 && consumer >= 0 && uses[producer] && + code[consumer].words; + for (uint32_t i = 0; i < n && emulate; i++) { + if ((int)i != producer && (int)i != consumer && uses[i]) + emulate = false; + } + if (emulate) { + struct clip_info produced, consumed; + spirv_clip_info(code[producer].words, code[producer].count, CLIP_PRODUCER, &produced); + spirv_clip_info(code[consumer].words, code[consumer].count, CLIP_CONSUMER, &consumed); + uint32_t location = produced.locations_used > consumed.locations_used ? produced.locations_used + : consumed.locations_used; + emulate = produced.has_clip && location != UINT32_MAX && + location + produced.clip_count <= dev->max_varying_locations && + spirv_emulate_clip(code[producer].words, code[producer].count, CLIP_PRODUCER, location, + produced.clip_count, &rw->code[producer]) && + spirv_emulate_clip(code[consumer].words, code[consumer].count, CLIP_CONSUMER, location, + produced.clip_count, &rw->code[consumer]); + if (!emulate) { + free(rw->code[producer].words); + free(rw->code[consumer].words); + rw->code[producer] = rw->code[consumer] = (struct spirv_code){0}; + } } } @@ -231,8 +304,13 @@ static void rewrite_shaders(struct device *dev, VkGraphicsPipelineCreateInfo *in rw->code[i] = rw->single[i]; rw->single[i] = (struct spirv_code){0}; } + if (!rw->code[i].words && code[i].capped.words) { + rw->code[i] = code[i].capped; + code[i].capped.words = NULL; + } if (rw->code[i].words) use_code(dev, info, rw, &code[i], i); + free(code[i].capped.words); } } @@ -324,13 +402,25 @@ static void rewrite_pipeline(struct device *dev, VkGraphicsPipelineCreateInfo *i rw->viewport.scissorCount = 1; info->pViewportState = &rw->viewport; } + if ((dev->emulated & GAP_DEPTH_OP) && info->pDepthStencilState && !info->pDepthStencilState->depthTestEnable && + info->pDepthStencilState->depthCompareOp != VK_COMPARE_OP_ALWAYS) { + bool dynamic = false; + for (uint32_t i = 0; info->pDynamicState && i < info->pDynamicState->dynamicStateCount; i++) { + VkDynamicState state = info->pDynamicState->pDynamicStates[i]; + dynamic |= state == VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE || state == VK_DYNAMIC_STATE_DEPTH_COMPARE_OP; + } + if (!dynamic) { + rw->depth_stencil = *info->pDepthStencilState; + rw->depth_stencil.depthCompareOp = VK_COMPARE_OP_ALWAYS; + info->pDepthStencilState = &rw->depth_stencil; + } + } if (dev->emulated & GAP_DUAL_SRC_BLEND) { rewrite_blend(info, rw); if (rw->attachments) info->pColorBlendState = &rw->blend; } - if (dev->emulated & (GAPS_SHADER | GAP_DUAL_SRC_BLEND)) - rewrite_shaders(dev, info, rw); + rewrite_shaders(dev, info, rw); } static void undo_rewrite(struct device *dev, struct pipeline_rewrite *rw) @@ -338,10 +428,6 @@ static void undo_rewrite(struct device *dev, struct pipeline_rewrite *rw) if (rw->clip_prev) rw->clip_prev->pNext = rw->clip_node; for (uint32_t i = 0; i < MAX_STAGES; i++) { - if (rw->in_place[i]) { - rw->in_place[i]->pCode = rw->in_place_code[i]; - rw->in_place[i]->codeSize = rw->in_place_size[i]; - } if (rw->temporary[i] != VK_NULL_HANDLE) dev->DestroyShaderModule(dev->handle, rw->temporary[i], NULL); free(rw->code[i].words); @@ -355,8 +441,15 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelines(VkDevice device, VkPipeli const VkAllocationCallbacks *allocator, VkPipeline *pipelines) { struct device *dev = device_from_handle(device); - VkGraphicsPipelineCreateInfo *copies = malloc(count * sizeof(*copies)); + VkGraphicsPipelineCreateInfo *copies = calloc(count, sizeof(*copies)); struct pipeline_rewrite *rewrites = calloc(count, sizeof(*rewrites)); + if (count && (!copies || !rewrites)) { + for (uint32_t i = 0; i < count; i++) + pipelines[i] = VK_NULL_HANDLE; + free(copies); + free(rewrites); + return VK_ERROR_OUT_OF_HOST_MEMORY; + } for (uint32_t i = 0; i < count; i++) { copies[i] = infos[i]; rewrite_pipeline(dev, &copies[i], &rewrites[i]); @@ -369,6 +462,37 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelines(VkDevice device, VkPipeli return result; } +VKAPI_ATTR VkResult VKAPI_CALL CreateComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t count, + const VkComputePipelineCreateInfo *infos, + const VkAllocationCallbacks *allocator, VkPipeline *pipelines) +{ + struct device *dev = device_from_handle(device); + VkComputePipelineCreateInfo *copies = calloc(count, sizeof(*copies)); + struct pipeline_rewrite *rewrites = calloc(count, sizeof(*rewrites)); + if (count && (!copies || !rewrites)) { + for (uint32_t i = 0; i < count; i++) + pipelines[i] = VK_NULL_HANDLE; + free(copies); + free(rewrites); + return VK_ERROR_OUT_OF_HOST_MEMORY; + } + for (uint32_t i = 0; i < count; i++) { + copies[i] = infos[i]; + struct stage_code code; + find_stage_code(dev, &copies[i].stage, &code); + if (code.capped.words) { + rewrites[i].code[0] = code.capped; + use_stage_code(dev, &copies[i].stage, &rewrites[i], &code, 0); + } + } + VkResult result = dev->CreateComputePipelines(device, cache, count, copies, allocator, pipelines); + for (uint32_t i = 0; i < count; i++) + undo_rewrite(dev, &rewrites[i]); + free(rewrites); + free(copies); + return result; +} + /* The driver has one viewport and one scissor; anything past the first is left out. */ VKAPI_ATTR void VKAPI_CALL CmdSetViewport(VkCommandBuffer cmd, uint32_t first, uint32_t count, const VkViewport *viewports) diff --git a/tools/venus/layer/spirv.c b/tools/venus/layer/spirv.c index 9a9794d9ce..5265adde61 100644 --- a/tools/venus/layer/spirv.c +++ b/tools/venus/layer/spirv.c @@ -15,6 +15,7 @@ #define OPCODE(word) ((word) & 0xffffu) #define LENGTH(word) ((word) >> 16) +#define VERSION_1_3 0x00010300u #define VERSION_1_4 0x00010400u struct words { @@ -103,6 +104,7 @@ static bool declares_result_second(uint32_t op) case SpvOpUndef: case SpvOpVariable: case SpvOpFunction: + case SpvOpFunctionParameter: return true; default: return false; @@ -875,3 +877,300 @@ bool spirv_emulate_clip(const uint32_t *words, size_t count, enum clip_role role unload(&m); return done; } + +struct newer_feature { + uint32_t value; + const char *extension; + const char *alternative; +}; + +#define PHYSICAL_STORAGE_BUFFER "SPV_EXT_physical_storage_buffer", "SPV_KHR_physical_storage_buffer" + +static const struct newer_feature newer_opcodes[] = { + {SpvOpCopyLogical, NULL, NULL}, + {SpvOpPtrEqual, NULL, NULL}, + {SpvOpPtrNotEqual, NULL, NULL}, + {SpvOpPtrDiff, NULL, NULL}, + {SpvOpDemoteToHelperInvocation, "SPV_EXT_demote_to_helper_invocation", NULL}, + {SpvOpSDot, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpUDot, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpSUDot, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpSDotAccSat, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpUDotAccSat, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpSUDotAccSat, "SPV_KHR_integer_dot_product", NULL}, + {SpvOpDecorateString, "SPV_GOOGLE_decorate_string", "SPV_GOOGLE_hlsl_functionality1"}, + {SpvOpMemberDecorateString, "SPV_GOOGLE_decorate_string", "SPV_GOOGLE_hlsl_functionality1"}, +}; + +static const struct newer_feature newer_capabilities[] = { + {SpvCapabilityShaderLayer, NULL, NULL}, + {SpvCapabilityShaderViewportIndex, NULL, NULL}, + {SpvCapabilityUniformDecoration, NULL, NULL}, + {SpvCapabilityStorageBuffer8BitAccess, "SPV_KHR_8bit_storage", NULL}, + {SpvCapabilityUniformAndStorageBuffer8BitAccess, "SPV_KHR_8bit_storage", NULL}, + {SpvCapabilityStoragePushConstant8, "SPV_KHR_8bit_storage", NULL}, + {SpvCapabilityDenormPreserve, "SPV_KHR_float_controls", NULL}, + {SpvCapabilityDenormFlushToZero, "SPV_KHR_float_controls", NULL}, + {SpvCapabilitySignedZeroInfNanPreserve, "SPV_KHR_float_controls", NULL}, + {SpvCapabilityRoundingModeRTE, "SPV_KHR_float_controls", NULL}, + {SpvCapabilityRoundingModeRTZ, "SPV_KHR_float_controls", NULL}, + {SpvCapabilityShaderNonUniform, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityRuntimeDescriptorArray, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityInputAttachmentArrayDynamicIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityUniformTexelBufferArrayDynamicIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityStorageTexelBufferArrayDynamicIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityUniformBufferArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilitySampledImageArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityStorageBufferArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityStorageImageArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityInputAttachmentArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityUniformTexelBufferArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityStorageTexelBufferArrayNonUniformIndexing, "SPV_EXT_descriptor_indexing", NULL}, + {SpvCapabilityVulkanMemoryModel, "SPV_KHR_vulkan_memory_model", NULL}, + {SpvCapabilityVulkanMemoryModelDeviceScope, "SPV_KHR_vulkan_memory_model", NULL}, + {SpvCapabilityPhysicalStorageBufferAddresses, PHYSICAL_STORAGE_BUFFER}, + {SpvCapabilityDemoteToHelperInvocation, "SPV_EXT_demote_to_helper_invocation", NULL}, + {SpvCapabilityDotProductInputAll, "SPV_KHR_integer_dot_product", NULL}, + {SpvCapabilityDotProductInput4x8Bit, "SPV_KHR_integer_dot_product", NULL}, + {SpvCapabilityDotProductInput4x8BitPacked, "SPV_KHR_integer_dot_product", NULL}, + {SpvCapabilityDotProduct, "SPV_KHR_integer_dot_product", NULL}, +}; + +static const struct newer_feature newer_decorations[] = { + {SpvDecorationUniformId, NULL, NULL}, + {SpvDecorationNoSignedWrap, "SPV_KHR_no_integer_wrap_decoration", NULL}, + {SpvDecorationNoUnsignedWrap, "SPV_KHR_no_integer_wrap_decoration", NULL}, + {SpvDecorationNonUniform, "SPV_EXT_descriptor_indexing", NULL}, + {SpvDecorationRestrictPointer, PHYSICAL_STORAGE_BUFFER}, + {SpvDecorationAliasedPointer, PHYSICAL_STORAGE_BUFFER}, + {SpvDecorationCounterBuffer, "SPV_GOOGLE_hlsl_functionality1", NULL}, + {SpvDecorationUserSemantic, "SPV_GOOGLE_hlsl_functionality1", NULL}, +}; + +#define NEWER_LOOP_CONTROLS \ + (SpvLoopControlMinIterationsMask | SpvLoopControlMaxIterationsMask | SpvLoopControlIterationMultipleMask | \ + SpvLoopControlPeelCountMask | SpvLoopControlPartialCountMask) +#define NEWER_IMAGE_OPERANDS \ + (SpvImageOperandsSignExtendMask | SpvImageOperandsZeroExtendMask | SpvImageOperandsNontemporalMask) + +static bool declares_extension(const struct module *m, const char *name) +{ + if (!name) + return false; + size_t size = strlen(name) + 1; + for (size_t i = 5; i < m->first_declaration; i += LENGTH(m->w[i])) { + uint32_t length = LENGTH(m->w[i]); + if (OPCODE(m->w[i]) == SpvOpExtension && (length - 1) * sizeof(uint32_t) >= size && + !memcmp(&m->w[i + 1], name, size)) + return true; + } + return false; +} + +static bool names_prefix(const uint32_t *words, uint32_t count, const char *prefix) +{ + size_t size = strlen(prefix); + return count * sizeof(uint32_t) > size && !memcmp(words, prefix, size); +} + +static bool available_in_1_3(const struct module *m, const struct newer_feature *features, size_t count, + uint32_t value) +{ + for (size_t i = 0; i < count; i++) { + if (features[i].value == value) + return declares_extension(m, features[i].extension) || declares_extension(m, features[i].alternative); + } + return true; +} + +#define AVAILABLE(m, table, value) available_in_1_3(m, table, sizeof(table) / sizeof(table[0]), value) + +static bool declares_capability(const struct module *m, uint32_t capability) +{ + for (size_t i = 5; i < m->first_declaration; i += LENGTH(m->w[i])) { + if (OPCODE(m->w[i]) == SpvOpCapability && LENGTH(m->w[i]) >= 2 && m->w[i + 1] == capability) + return true; + } + return false; +} + +static uint32_t image_operands_at(uint32_t op) +{ + switch (op) { + case SpvOpImageWrite: + return 4; + case SpvOpImageSampleImplicitLod: + case SpvOpImageSampleExplicitLod: + case SpvOpImageSampleProjImplicitLod: + case SpvOpImageSampleProjExplicitLod: + case SpvOpImageFetch: + case SpvOpImageRead: + case SpvOpImageSparseSampleImplicitLod: + case SpvOpImageSparseSampleExplicitLod: + case SpvOpImageSparseSampleProjImplicitLod: + case SpvOpImageSparseSampleProjExplicitLod: + case SpvOpImageSparseFetch: + case SpvOpImageSparseRead: + return 5; + case SpvOpImageSampleDrefImplicitLod: + case SpvOpImageSampleDrefExplicitLod: + case SpvOpImageSampleProjDrefImplicitLod: + case SpvOpImageSampleProjDrefExplicitLod: + case SpvOpImageGather: + case SpvOpImageDrefGather: + case SpvOpImageSparseSampleDrefImplicitLod: + case SpvOpImageSparseSampleDrefExplicitLod: + case SpvOpImageSparseSampleProjDrefImplicitLod: + case SpvOpImageSparseSampleProjDrefExplicitLod: + case SpvOpImageSparseGather: + case SpvOpImageSparseDrefGather: + return 6; + default: + return 0; + } +} + +static uint32_t memory_access_words(uint32_t mask) +{ + uint32_t words = 1; + if (mask & SpvMemoryAccessAlignedMask) + words++; + if (mask & SpvMemoryAccessMakePointerAvailableMask) + words++; + if (mask & SpvMemoryAccessMakePointerVisibleMask) + words++; + return words; +} + +static bool selects_scalar_vector_or_pointer(const struct module *m, uint32_t type) +{ + size_t d = definition(m, type); + if (!d) + return false; + switch (OPCODE(m->w[d])) { + case SpvOpTypeBool: + case SpvOpTypeInt: + case SpvOpTypeFloat: + case SpvOpTypeVector: + case SpvOpTypePointer: + return true; + default: + return false; + } +} + +static bool valid_in_1_3(const struct module *m, size_t i) +{ + uint32_t op = OPCODE(m->w[i]); + uint32_t length = LENGTH(m->w[i]); + if (!AVAILABLE(m, newer_opcodes, op)) + return false; + switch (op) { + case SpvOpMemoryModel: + return length >= 3 && m->w[i + 2] == SpvMemoryModelGLSL450; + case SpvOpCapability: + return length >= 2 && AVAILABLE(m, newer_capabilities, m->w[i + 1]); + case SpvOpExecutionModeId: + return length >= 3 && m->w[i + 2] != SpvExecutionModeLocalSizeId; + case SpvOpDecorate: + case SpvOpDecorateId: + case SpvOpDecorateString: + if (length < 3 || !AVAILABLE(m, newer_decorations, m->w[i + 2])) + return false; + if (m->w[i + 2] == SpvDecorationNonWritable) { + size_t d = definition(m, m->w[i + 1]); + if (!d || (OPCODE(m->w[d]) == SpvOpVariable && + (LENGTH(m->w[d]) < 4 || m->w[d + 3] == SpvStorageClassPrivate || + m->w[d + 3] == SpvStorageClassFunction))) + return false; + if (OPCODE(m->w[d]) == SpvOpFunctionParameter) { + size_t type = LENGTH(m->w[d]) >= 3 ? definition(m, m->w[d + 1]) : 0; + if (!type || OPCODE(m->w[type]) != SpvOpTypePointer || LENGTH(m->w[type]) < 4 || + m->w[type + 2] == SpvStorageClassPrivate || m->w[type + 2] == SpvStorageClassFunction) + return false; + } + } + return true; + case SpvOpMemberDecorate: + case SpvOpMemberDecorateString: + return length >= 4 && AVAILABLE(m, newer_decorations, m->w[i + 3]); + case SpvOpLoopMerge: + return length >= 4 && !(m->w[i + 3] & NEWER_LOOP_CONTROLS); + case SpvOpSelect: + return length >= 6 && selects_scalar_vector_or_pointer(m, m->w[i + 1]); + case SpvOpSpecConstantOp: + return length >= 5 && (m->w[i + 3] != SpvOpUConvert || + declares_capability(m, SpvCapabilityKernel) || + declares_extension(m, "SPV_AMD_gpu_shader_int16")); + case SpvOpExtInstImport: + return length >= 3 && (!names_prefix(&m->w[i + 2], length - 2, "NonSemantic.") || + declares_extension(m, "SPV_KHR_non_semantic_info")); + case SpvOpCopyMemory: + case SpvOpCopyMemorySized: { + uint32_t at = op == SpvOpCopyMemory ? 3 : 4; + return length <= at || at + memory_access_words(m->w[i + at]) >= length; + } + default: { + uint32_t at = image_operands_at(op); + return !at || length <= at || !(m->w[i + at] & NEWER_IMAGE_OPERANDS); + } + } +} + +static bool variable_storage(const struct module *m, uint32_t id, uint32_t *storage) +{ + size_t d = definition(m, id); + if (!d || OPCODE(m->w[d]) != SpvOpVariable) + return false; + *storage = m->w[d + 3]; + return true; +} + +static void trim_entry_interfaces(struct module *m) +{ + for (size_t i = 5; i < m->first_declaration; i += LENGTH(m->w[i])) { + if (OPCODE(m->w[i]) != SpvOpEntryPoint) + continue; + uint32_t length = LENGTH(m->w[i]); + if (length < 4) + continue; + uint32_t first = 3 + string_words(&m->w[i + 3], length - 3); + for (uint32_t k = first; k < length; k++) { + uint32_t id = m->w[i + k]; + uint32_t storage; + if (id < m->original_bound && variable_storage(m, id, &storage) && + storage != SpvStorageClassInput && storage != SpvStorageClassOutput) + m->interface_remove[id] = 1; + } + } +} +uint32_t spirv_version(const uint32_t *words, size_t count) +{ + if (count < 5 || words[0] != SpvMagicNumber) + return 0; + return words[1]; +} + +bool spirv_cap_version(const uint32_t *words, size_t count, struct spirv_code *out) +{ + if (count < 5 || words[0] != SpvMagicNumber || words[1] <= VERSION_1_3) + return false; + struct module m; + if (!load(&m, words, count)) + return false; + for (size_t i = 5; i < m.count; i += LENGTH(m.w[i])) { + if (!valid_in_1_3(&m, i)) { + unload(&m); + return false; + } + } + for (size_t i = 5; i < m.count; i += LENGTH(m.w[i])) { + if (OPCODE(m.w[i]) == SpvOpTerminateInvocation) + m.w[i] = (LENGTH(m.w[i]) << 16) | SpvOpKill; + } + trim_entry_interfaces(&m); + m.w[1] = VERSION_1_3; + bool done = finish(&m, out); + unload(&m); + return done; +} diff --git a/tools/vr/build.sh b/tools/vr/build.sh index f28ef326b9..4e9fb12b95 100755 --- a/tools/vr/build.sh +++ b/tools/vr/build.sh @@ -14,7 +14,7 @@ if [ -z "$vkinc" ]; then for ndk in "${ANDROID_NDK_HOME:-}" "${ANDROID_NDK_LATEST_HOME:-}" \ $(ls -d "${ANDROID_HOME:-$HOME/Library/Android/sdk}"/ndk/* 2>/dev/null | sort -r); do [ -n "$ndk" ] || continue - cand=$(ls -d "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include 2>/dev/null | head -1) + cand=$(ls -d "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include 2>/dev/null | head -1 || true) if [ -n "$cand" ] && [ -f "$cand/vulkan/vk_layer.h" ]; then vkinc=$cand; break; fi done fi diff --git a/tools/xbox/droiddeck-legacy-install.patch b/tools/xbox/droiddeck-legacy-install.patch index 2d34e91679..8de0ebded6 100644 --- a/tools/xbox/droiddeck-legacy-install.patch +++ b/tools/xbox/droiddeck-legacy-install.patch @@ -154,7 +154,7 @@ new file mode 100755 index 0000000..d43c5fc --- /dev/null +++ b/crates/xodus-cli/src/commands/legacy_install.rs -@@ -0,0 +1,1198 @@ +@@ -0,0 +1,1285 @@ +//! Installs a legacy Store title: resolve, license, download, extract. +//! +//! `streaming` only understands MSIXVC, where the container *is* the game and @@ -1119,15 +1119,30 @@ index 0000000..d43c5fc + .map_err(|error| format!("Could not list the package folder: {error}"))? + .filter_map(Result::ok) + { -+ let target = destination.join(entry.file_name()); -+ if target.exists() { -+ if !updating { -+ return Err(format!("Extraction would overwrite {}", target.display())); -+ } -+ let replaced = if target.is_dir() { -+ std::fs::remove_dir_all(&target) ++ let name = entry.file_name(); ++ let target = destination.join(&name); ++ let metadata = is_package_metadata(&name); ++ // The bundle may have written its copy of a packaging file in other letter casing. ++ let existing: Vec<PathBuf> = if metadata { ++ std::fs::read_dir(destination) ++ .map_err(|error| format!("Could not list the game folder: {error}"))? ++ .filter_map(Result::ok) ++ .filter(|other| other.file_name().eq_ignore_ascii_case(&name)) ++ .map(|other| other.path()) ++ .collect() ++ } else if target.exists() { ++ vec![target.clone()] ++ } else { ++ Vec::new() ++ }; ++ if !existing.is_empty() && !updating && !metadata { ++ return Err(format!("Extraction would overwrite {}", target.display())); ++ } ++ for old in existing { ++ let replaced = if old.is_dir() { ++ std::fs::remove_dir_all(&old) + } else { -+ std::fs::remove_file(&target) ++ std::fs::remove_file(&old) + }; + replaced.map_err(|error| format!("Could not replace an installed file: {error}"))?; + } @@ -1138,6 +1153,14 @@ index 0000000..d43c5fc + Ok(()) +} + ++/// Files a package container carries about itself. A bundle leaves its own copies at ++/// the top of the game folder, so the lifted package's copies replace them. ++fn is_package_metadata(name: &std::ffi::OsStr) -> bool { ++ ["AppxBlockMap.xml", "AppxSignature.p7x", "[Content_Types].xml", "AppxMetadata"] ++ .iter() ++ .any(|known| name.eq_ignore_ascii_case(known)) ++} ++ +/// Folders below [root] that carry a manifest, at the depth a nested bundle can +/// write one. A bundle of a bundle is the deepest the extractor produces. +fn nested_packages(root: &Path) -> Vec<PathBuf> { @@ -1261,6 +1284,70 @@ index 0000000..d43c5fc + } + + #[test] ++ fn hoist_replaces_the_bundles_own_packaging_files() { ++ // Halo Wars: Definitive Edition: the bundle leaves AppxBlockmap.xml at the top and ++ // its one package folder has its own. ++ let root = scratch("bundle-metadata"); ++ std::fs::write(root.join("AppxBlockmap.xml"), b"bundle").unwrap(); ++ std::fs::write(root.join("AppxSignature.p7x"), b"bundle").unwrap(); ++ std::fs::create_dir_all(root.join("AppxMetadata")).unwrap(); ++ std::fs::write(root.join("AppxMetadata").join("AppxBundleManifest.xml"), b"bundle").unwrap(); ++ let inner = root.join("Bulldog"); ++ std::fs::create_dir_all(&inner).unwrap(); ++ std::fs::write(inner.join("AppxBlockmap.xml"), b"package").unwrap(); ++ std::fs::write(inner.join("AppxSignature.p7x"), b"package").unwrap(); ++ std::fs::create_dir_all(inner.join("AppxMetadata")).unwrap(); ++ std::fs::write(inner.join("AppxMetadata").join("CodeIntegrity.cat"), b"package").unwrap(); ++ std::fs::write(inner.join(LEGACY_MANIFEST), "<Package/>").unwrap(); ++ std::fs::write(inner.join("xgameFinal.exe"), b"MZ").unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ assert!(root.join(LEGACY_MANIFEST).is_file()); ++ assert!(root.join("xgameFinal.exe").is_file()); ++ assert_eq!(std::fs::read(root.join("AppxBlockmap.xml")).unwrap(), b"package"); ++ assert_eq!(std::fs::read(root.join("AppxSignature.p7x")).unwrap(), b"package"); ++ // The package's AppxMetadata replaces the bundle's whole; nothing of the bundle's is merged in. ++ assert_eq!(std::fs::read(root.join("AppxMetadata").join("CodeIntegrity.cat")).unwrap(), b"package"); ++ assert!(!root.join("AppxMetadata").join("AppxBundleManifest.xml").exists()); ++ assert!(!inner.exists()); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn hoist_replaces_a_packaging_file_the_bundle_wrote_in_other_casing() { ++ let root = scratch("metadata-casing"); ++ std::fs::write(root.join("AppxBlockmap.xml"), b"bundle").unwrap(); ++ let inner = root.join("Game"); ++ std::fs::create_dir_all(&inner).unwrap(); ++ std::fs::write(inner.join("AppxBlockMap.xml"), b"package").unwrap(); ++ std::fs::write(inner.join(LEGACY_MANIFEST), "<Package/>").unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ let maps: Vec<_> = std::fs::read_dir(&root).unwrap().filter_map(Result::ok) ++ .filter(|entry| entry.file_name().eq_ignore_ascii_case("AppxBlockMap.xml")) ++ .collect(); ++ assert_eq!(maps.len(), 1, "the bundle's copy is gone on a case-sensitive filesystem too"); ++ assert_eq!(std::fs::read(maps[0].path()).unwrap(), b"package"); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn hoist_still_refuses_to_overwrite_a_game_file_on_a_fresh_install() { ++ let root = scratch("fresh-collision"); ++ std::fs::write(root.join("Game.exe"), b"other").unwrap(); ++ let inner = root.join("Game"); ++ std::fs::create_dir_all(&inner).unwrap(); ++ std::fs::write(inner.join(LEGACY_MANIFEST), "<Package/>").unwrap(); ++ std::fs::write(inner.join("Game.exe"), b"MZ").unwrap(); ++ ++ assert!(hoist(&root).unwrap_err().contains("would overwrite")); ++ assert_eq!(std::fs::read(root.join("Game.exe")).unwrap(), b"other"); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] + fn hoist_finds_a_manifest_inside_a_nested_bundle() { + let root = scratch("deep"); + let inner = root.join("bundle").join("Microsoft.SunriseBaseGame");